How to use the traitlets.List function in traitlets

To help you get started, we’ve selected a few traitlets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jupyter / jupyter_kernel_test / jupyter_kernel_test / messagespec.py View on Github external
found = Bool()


class ArgSpec(Reference):
    args = List(Unicode)
    varargs = Unicode()
    varkw = Unicode()
    defaults = List()


class Status(Reference):
    execution_state = Enum((u'busy', u'idle', u'starting'))


class CompleteReply(Reference):
    matches = List(Unicode)
    cursor_start = Integer()
    cursor_end = Integer()
    status = Unicode()

class LanguageInfo(Reference):
    name = Unicode()
    version = Unicode(sys.version.split()[0])

class KernelInfoReply(Reference):
    protocol_version = Version(min='5.0')
    implementation = Unicode()
    implementation_version = Version()
    language_info = Dict()
    banner = Unicode()
    
    def check(self, d):
github vaexio / vaex / packages / vaex-ml / vaex / ml / transformations.py View on Github external
4  red
    >>> encoder = vaex.ml.OneHotEncoder(features=['color'])
    >>> encoder.fit_transform(df)
     #  color      color_blue    color_green    color_red
     0  red                 0              0            1
     1  green               0              1            0
     2  green               0              1            0
     3  blue                1              0            0
     4  red                 0              0            1
    '''

    # title = Unicode(default_value='One-Hot Encoder', read_only=True).tag(ui='HTML')
    prefix = traitlets.Unicode(default_value='', help=help_prefix).tag(ui='Text')
    one = traitlets.Any(1, help='Value to encode when a category is present.')
    zero = traitlets.Any(0, help='Value to encode when category is absent.')
    uniques_ = traitlets.List(traitlets.List(), help='The unique elements found in each feature.').tag(output=True)

    def fit(self, df):
        '''Fit OneHotEncoder to the DataFrame.

        :param df: A vaex DataFrame.
        '''

        uniques = []
        for i in self.features:
            expression = _ensure_strings_from_expressions(i)
            unique = df.unique(expression)
            unique = np.sort(unique)  # this can/should be optimized with @delay
            uniques.append(unique.tolist())
        self.uniques_ = uniques

    def transform(self, df):
github jupyter / nbgrader / nbgrader / validator.py View on Github external
from traitlets.config import LoggingConfigurable
from traitlets import List, Unicode, Integer, Bool
from nbformat import current_nbformat, read as read_nb
from textwrap import fill, dedent
from nbconvert.filters import ansi2html, strip_ansi

from .preprocessors import Execute, ClearOutput, CheckCellMetadata
from . import utils
from nbformat.notebooknode import NotebookNode
import typing


class Validator(LoggingConfigurable):

    preprocessors = List([
        CheckCellMetadata,
        ClearOutput,
        Execute
    ])

    indent = Unicode(
        "    ",
        help="A string containing whitespace that will be used to indent code and errors"
    ).tag(config=True)

    width = Integer(
        90,
        help="Maximum line width for displaying code/errors"
    ).tag(config=True)

    invert = Bool(
github NERSC / sshspawner / sshspawner / sshspawner.py View on Github external
import asyncio, asyncssh
import os
import signal
from textwrap import dedent
import warnings
import random

from traitlets import Any, Bool, Dict, Unicode, Integer, List, default, observe, validate

from jupyterhub.spawner import Spawner
from jupyterhub.utils import maybe_future


class SSHSpawner(Spawner):

    remote_hosts = List(Unicode(),
            help=dedent("""
            Remote hosts available for spawning notebook servers.

            List of remote hosts where notebook servers can be spawned. By
            default, the remote host used to spawn a notebook is selected at 
            random from this list. The `remote_host_selector()` attribute can
            be used to customize the selection algorithm, possibly attempting
            to balance load across all the hosts.

            If this list contains a single remote host, that host will always
            be selected (unless `remote_host_selector()` does something weird
            like just return some other value). That would be appropriate if
            there is just one remote host available, or, if the remote host is
            itself a load balancer or is doing round-robin DNS.
            """),
            config=True)
github altair-viz / altair / altair / schema / _interface / scaleconfig.py View on Github external
useRawDomain: Bool
        Uses the source data range as scale domain instead of aggregated data for aggregate axis.
    """
    bandSize = T.Union([T.CFloat(allow_none=True, default_value=None), BandSize(allow_none=True, default_value=None)])
    barSizeRange = T.List(T.CFloat(), allow_none=True, default_value=None, help="""Default range for bar size scale.""")
    fontSizeRange = T.List(T.CFloat(), allow_none=True, default_value=None, help="""Default range for font size scale.""")
    nominalColorRange = T.Union([T.Unicode(allow_none=True, default_value=None), T.List(T.Unicode(), allow_none=True, default_value=None)])
    opacity = T.List(T.CFloat(), allow_none=True, default_value=None, help="""Default range for opacity.""")
    padding = T.CFloat(allow_none=True, default_value=None, help="""Default padding for `x` and `y` ordinal scales.""")
    pointSizeRange = T.List(T.CFloat(), allow_none=True, default_value=None, help="""Default range for bar size scale.""")
    round = T.Bool(allow_none=True, default_value=None, help="""If true, rounds numeric output values to integers.""")
    ruleSizeRange = T.List(T.CFloat(), allow_none=True, default_value=None, help="""Default range for rule stroke widths.""")
    sequentialColorRange = T.Union([T.Unicode(allow_none=True, default_value=None), T.List(T.Unicode(), allow_none=True, default_value=None)])
    shapeRange = T.Union([T.Unicode(allow_none=True, default_value=None), T.List(T.Unicode(), allow_none=True, default_value=None)])
    textBandWidth = T.CFloat(allow_none=True, default_value=None, min=0, help="""Default band width for `x` ordinal scale when is mark is `text`.""")
    tickSizeRange = T.List(T.CFloat(), allow_none=True, default_value=None, help="""Default range for tick spans.""")
    useRawDomain = T.Bool(allow_none=True, default_value=None, help="""Uses the source data range as scale domain instead of aggregated data for aggregate axis.""")
    
    def __init__(self, bandSize=None, barSizeRange=None, fontSizeRange=None, nominalColorRange=None, opacity=None, padding=None, pointSizeRange=None, round=None, ruleSizeRange=None, sequentialColorRange=None, shapeRange=None, textBandWidth=None, tickSizeRange=None, useRawDomain=None, **kwargs):
        kwds = dict(bandSize=bandSize, barSizeRange=barSizeRange, fontSizeRange=fontSizeRange, nominalColorRange=nominalColorRange, opacity=opacity, padding=padding, pointSizeRange=pointSizeRange, round=round, ruleSizeRange=ruleSizeRange, sequentialColorRange=sequentialColorRange, shapeRange=shapeRange, textBandWidth=textBandWidth, tickSizeRange=tickSizeRange, useRawDomain=useRawDomain)
        kwargs.update({k:v for k, v in kwds.items() if v is not None})
        super(ScaleConfig, self).__init__(**kwargs)
github Ulm-IQO / qudi / logic / notebook.py View on Github external
os.path.join(get_ipython_dir(), 'profile_default', 'static'),
                DEFAULT_STATIC_FILES_PATH)
        ]

    extra_template_paths = List(Unicode(), config=True,
        help="""Extra paths to search for serving jinja templates.

        Can be used to override templates from notebook.templates."""
    )

    @property
    def template_file_path(self):
        """return extra paths + the default locations"""
        return self.extra_template_paths + DEFAULT_TEMPLATE_PATH_LIST

    extra_nbextensions_path = List(Unicode(), config=True,
        help="""extra paths to look for Javascript notebook extensions"""
    )
    
    @property
    def nbextensions_path(self):
        """The path to look for Javascript notebook extensions"""
        path = self.extra_nbextensions_path + jupyter_path('nbextensions')
        # FIXME: remove IPython nbextensions path once migration is setup
        path.append(os.path.join(get_ipython_dir(), 'nbextensions'))
        return path

    websocket_url = Unicode("", config=True,
        help="""The base URL for websockets,
        if it differs from the HTTP server (hint: it almost certainly doesn't).
        
        Should be in the form of an HTTP origin: ws[s]://hostname[:port]
github martinRenou / Odysis / odysis / odysis.py View on Github external
min = Float(allow_none=True, default_value=None).tag(sync=True)
    max = Float(allow_none=True, default_value=None).tag(sync=True)


@register
class Data(Widget):
    """A data widget."""
    # _view_name = Unicode('DataView').tag(sync=True)
    _model_name = Unicode('DataModel').tag(sync=True)
    _view_module = Unicode('odysis').tag(sync=True)
    _model_module = Unicode('odysis').tag(sync=True)
    _view_module_version = Unicode(odysis_version).tag(sync=True)
    _model_module_version = Unicode(odysis_version).tag(sync=True)

    name = Unicode().tag(sync=True)
    components = List(Instance(Component)).tag(sync=True, **widget_serialization)


class BlockType():
    pass


@register
class Block(Widget, BlockType):
    _view_name = Unicode('BlockView').tag(sync=True)
    _model_name = Unicode('BlockModel').tag(sync=True)
    _view_module = Unicode('odysis').tag(sync=True)
    _model_module = Unicode('odysis').tag(sync=True)
    _view_module_version = Unicode(odysis_version).tag(sync=True)
    _model_module_version = Unicode(odysis_version).tag(sync=True)

    _blocks = List(Instance(BlockType)).tag(sync=True, **widget_serialization)
github dalejung / nbx / nbx / nbmanager / gistmiddleware.py View on Github external
from .gist import GistService, model_to_files
from .bundle.bundlenbmanager import BundleNotebookManager
from .dispatch import dispatch_method
from .util import _path_split

_missing = object()

class GistMiddleware(LoggingConfigurable):
    """
    This middleware will save to github if the notebook metadata contains a
    gist_id.

    This requires that the Gist is owned by an account we control.
    """
    github_accounts = List(Tuple, config=True,
                            help="List of Tuple(github_account, github_password)")

    oauth_token = Unicode(config=True)

    def __init__(self, *args, **kwargs):
        super(GistMiddleware, self).__init__(*args, **kwargs)

        self.service = GistService()
        if self.oauth_token:
            self.service.oauth_login(token=self.oauth_token)

        for user, pw in self.github_accounts:
            self.service.login(user, pw)


    def post_save(self, nbm, local_path, model, path):
github altair-viz / altair / altair / schema / _interface / layerspec.py View on Github external
height: CFloat
        
    layers: List(UnitSpec)
        Unit specs that will be layered.
    name: Unicode
        Name of the visualization for later reference.
    transform: Transform
        An object describing filter and new field calculation.
    width: CFloat
        
    """
    config = T.Instance(Config, allow_none=True, default_value=None, help="""Configuration object.""")
    data = T.Instance(Data, allow_none=True, default_value=None, help="""An object describing the data source.""")
    description = T.Unicode(allow_none=True, default_value=None, help="""An optional description of this mark for commenting purpose.""")
    height = T.CFloat(allow_none=True, default_value=None)
    layers = T.List(T.Instance(UnitSpec), allow_none=True, default_value=None, help="""Unit specs that will be layered.""")
    name = T.Unicode(allow_none=True, default_value=None, help="""Name of the visualization for later reference.""")
    transform = T.Instance(Transform, allow_none=True, default_value=None, help="""An object describing filter and new field calculation.""")
    width = T.CFloat(allow_none=True, default_value=None)
    
    def __init__(self, config=None, data=None, description=None, height=None, layers=None, name=None, transform=None, width=None, **kwargs):
        kwds = dict(config=config, data=data, description=description, height=height, layers=layers, name=name, transform=transform, width=width)
        kwargs.update({k:v for k, v in kwds.items() if v is not None})
        super(LayerSpec, self).__init__(**kwargs)
github Autodesk / notebook-molecular-visualization / nbmolviz / viewers / geometry_viewer.py View on Github external
atom_labels_shown = traitlets.Bool(False).tag(sync=True)
    background_color = traitlets.Unicode('#545c85').tag(sync=True)
    background_opacity = traitlets.Float(1.0).tag(sync=True)
    cubefile = traitlets.Unicode().tag(sync=True)
    far_clip = traitlets.Float().tag(sync=True)
    height = traitlets.Unicode(sync=True)
    labels = traitlets.List([]).tag(sync=True)
    model_data = traitlets.Dict({}).tag(sync=True)
    near_clip = traitlets.Float().tag(sync=True)
    outline_color = traitlets.Unicode('#000000').tag(sync=True)
    outline_width = traitlets.Float(0.0).tag(sync=True)
    positions = traitlets.List([]).tag(sync=True)
    selected_atom_indices = traitlets.List().tag(sync=True)
    selection_type = traitlets.Unicode('Atom', choices=['Atom', 'Residue', 'Chain']).tag(sync=True)
    shapes = traitlets.List([]).tag(sync=True)
    styles = traitlets.Dict({}).tag(sync=True)
    volumetric_style = traitlets.Dict({}).tag(sync=True)
    width = traitlets.Unicode(sync=True)

    SHAPE_NAMES = {
        'SPHERE': 'Sphere',
        'ARROW': 'Arrow',
        'CYLINDER': 'Cylinder',
    }

    STYLE_NAMES = {'vdw': 'sphere',
                   'licorice': 'stick',
                   'line': 'line',
                   'ribbon': 'cartoon',
                   None: None}