Ejemplo n.º 1
0
class Mercator(GeoScale):
    """A geographical projection scale commonly used for world maps.

    The Mercator projection is a cylindrical map projection which ensures that
    any course of constant bearing is a straight line.

    Attributes
    ----------
    scale_factor: float (default: 190)
        Specifies the scale value for the projection
    center: tuple (default: (0, 60))
        Specifies the longitude and latitude where the map is centered.
    rotate: tuple (default: (0, 0))
        Degree of rotation in each axis.
    rtype: (Number, Number) (class-level attribute)
        This attribute should not be modifed. The range type of a geo
        scale is a tuple.
    dtype: type (class-level attribute)
        the associated data type / domain type
    """

    scale_factor = Float(190).tag(sync=True)
    center = Tuple((0, 60)).tag(sync=True)
    rotate = Tuple((0, 0)).tag(sync=True)
    rtype = '(Number, Number)'
    dtype = np.number
    _view_name = Unicode('Mercator').tag(sync=True)
    _model_name = Unicode('MercatorModel').tag(sync=True)
Ejemplo n.º 2
0
class DatasetConfig(Configurable):
    # not configurable
    n_sample = Integer(help='Total number of data counted internally')

    # configurable
    descriptor = CaselessStrEnum(
        ['symmetry_function', 'weighted_symmetry_function'],
        default_value='symmetry_function',
        help='Name of descriptor dataset used for input of HDNNP').tag(
            config=True)
    parameters = Dict(
        trait=List,
        help='Parameters used for the specified descriptor dataset. '
        'Set as Dict{key: List[Tuple(parameters)]}. '
        'This will be passed to descriptor dataset as keyword arguments. '
        'ex.) {"type2": [(5.0, 0.01, 2.0)]}').tag(config=True)
    property_ = CaselessStrEnum(
        ['interatomic_potential'],
        default_value='interatomic_potential',
        help='Name of property dataset to be optimized by HDNNP').tag(
            config=True)
    preprocesses = List(
        trait=Tuple(CaselessStrEnum(['pca', 'scaling', 'standardization']),
                    Tuple(), Dict()),
        help='Preprocess to be applied for input of HDNNP (=descriptor). '
        'Set as List[Tuple(Str(name), Tuple(args), Dict{kwargs})]. '
        'Each preprocess instance will be initialized with '
        '(*args, **kwargs). '
        'ex.) [("pca", (20,), {})]').tag(config=True)
    remake = Bool(
        default_value=False,
        help='If the given data file and the loaded dataset are not '
        'compatible, automatically recalculate and overwrite it.').tag(
            config=True)
Ejemplo n.º 3
0
class Orthographic(GeoScale):
    """A perspective projection that depicts a hemisphere as it appears from
    outer space.

    The projection is neither equal-area nor conformal.

    Attributes
    ----------
    scale_factor: float (default: 145)
       Specifies the scale value for the projection
    center: tuple (default: (0, 60))
        Specifies the longitude and latitude where the map is centered.
    rotate: tuple (default: (96, 0))
        Degree of rotation in each axis.
    clip_angle: float (default: 90.)
        Specifies the clipping circle radius to the specified angle in degrees.
    precision: float (default: 0.1)
        Specifies the threshold for the projections adaptive resampling to the
        specified value in pixels.
    """

    scale_factor = Float(145.0).tag(sync=True)
    center = Tuple((0, 60)).tag(sync=True)
    rotate = Tuple((0, 0)).tag(sync=True)
    clip_angle = Float(90.0, min=0.0, max=360.0).tag(sync=True)
    precision = Float(0.1).tag(sync=True)
    rtype = '(Number, Number)'
    dtype = np.number
    _view_name = Unicode('Orthographic').tag(sync=True)
    _model_name = Unicode('OrthographicModel').tag(sync=True)
Ejemplo n.º 4
0
class Stereographic(GeoScale):
    """A perspective projection that uses a bijective and smooth map at every
    point except the projection point.

    The projection is not an equal-area projection but it is conformal.

    Attributes
    ----------
    scale_factor: float (default: 250)
        Specifies the scale value for the projection
    rotate: tuple (default: (96, 0))
        Degree of rotation in each axis.
    center: tuple (default: (0, 60))
        Specifies the longitude and latitude where the map is centered.
    precision: float (default: 0.1)
        Specifies the threshold for the projections adaptive resampling to the
        specified value in pixels.
    clip_angle: float (default: 90.)
        Specifies the clipping circle radius to the specified angle in degrees.
    """

    scale_factor = Float(145.0).tag(sync=True)
    center = Tuple((0, 60)).tag(sync=True)
    precision = Float(0.1).tag(sync=True)
    rotate = Tuple((96, 0)).tag(sync=True)
    clip_angle = Float(179.9999, min=0.0, max=360.0).tag(sync=True)
    rtype = '(Number, Number)'
    dtype = np.number
    _view_name = Unicode('Stereographic').tag(sync=True)
    _model_name = Unicode('StereographicModel').tag(sync=True)
Ejemplo n.º 5
0
class DOMWidget(Widget):
    visible = Bool(True, allow_none=True, help="Whether the widget is visible.  False collapses the empty space, while None preserves the empty space.", sync=True)
    _css = Tuple(sync=True, help="CSS property list: (selector, key, value)")
    _dom_classes = Tuple(sync=True, help="DOM classes applied to widget.$el.")
    
    width = CUnicode(sync=True)
    height = CUnicode(sync=True)
    # A default padding of 2.5 px makes the widgets look nice when displayed inline.
    padding = CUnicode(sync=True)
    margin = CUnicode(sync=True)

    color = Color(None, allow_none=True, sync=True)
    background_color = Color(None, allow_none=True, sync=True)
    border_color = Color(None, allow_none=True, sync=True)

    border_width = CUnicode(sync=True)
    border_radius = CUnicode(sync=True)
    border_style = CaselessStrEnum(values=[ # http://www.w3schools.com/cssref/pr_border-style.asp
        'none', 
        'hidden', 
        'dotted', 
        'dashed', 
        'solid', 
        'double', 
        'groove', 
        'ridge', 
        'inset', 
        'outset', 
        'initial', 
        'inherit', ''],
        default_value='', sync=True)

    font_style = CaselessStrEnum(values=[ # http://www.w3schools.com/cssref/pr_font_font-style.asp
        'normal', 
        'italic', 
        'oblique', 
        'initial', 
        'inherit', ''], 
        default_value='', sync=True)
    font_weight = CaselessStrEnum(values=[ # http://www.w3schools.com/cssref/pr_font_weight.asp
        'normal', 
        'bold', 
        'bolder', 
        'lighter',
        'initial', 
        'inherit', ''] + list(map(str, range(100,1000,100))),
        default_value='', sync=True)
    font_size = CUnicode(sync=True)
    font_family = Unicode(sync=True)

    def __init__(self, *pargs, **kwargs):
        super(DOMWidget, self).__init__(*pargs, **kwargs)

        def _validate_border(name, old, new):
            if new is not None and new != '':
                if name != 'border_width' and not self.border_width:
                    self.border_width = 1
                if name != 'border_style' and self.border_style == '':
                    self.border_style = 'solid'
        self.on_trait_change(_validate_border, ['border_width', 'border_style', 'border_color'])
Ejemplo n.º 6
0
class Scene(_GanyDOMWidgetBase):
    """A 3-D Scene widget."""

    _view_name = Unicode('SceneView').tag(sync=True)
    _model_name = Unicode('SceneModel').tag(sync=True)

    children = List(Instance(Block)).tag(sync=True, **widget_serialization)

    background_color = Color('white').tag(sync=True)
    background_opacity = CFloat(1.).tag(sync=True)

    camera_position = Union((Tuple(trait=CFloat, minlen=3, maxlen=3), ),
                            allow_none=True,
                            default_value=None).tag(sync=True)
    camera_target = Union((Tuple(trait=CFloat, minlen=3, maxlen=3), ),
                          allow_none=True,
                          default_value=None).tag(sync=True)
    camera_up = Tuple(trait=CFloat,
                      minlen=3,
                      maxlen=3,
                      default_value=(0, 1, 0)).tag(sync=True)

    def __init__(self, children=[], **kwargs):
        """Construct a Scene."""
        super(Scene, self).__init__(children=children, **kwargs)
Ejemplo n.º 7
0
class SelectionRangeSlider(_MultipleSelectionNonempty):
    """
    Slider to select multiple contiguous items from a list.

    The index, value, and label attributes contain the start and end of
    the selection range, not all items in the range.

    Parameters
    ----------
    {multiple_selection_params}

    {slider_params}
    """

    _view_name = Unicode("SelectionRangeSliderView").tag(sync=True)
    _model_name = Unicode("SelectionRangeSliderModel").tag(sync=True)

    value = Tuple(help="Min and max selected values")
    label = Tuple(help="Min and max selected labels")
    index = Tuple((0, 0), help="Min and max selected indices").tag(sync=True)

    @observe("options")
    def _propagate_options(self, change):
        "Select the first range"
        options = self._options_full
        self.set_trait("_options_labels", tuple(i[0] for i in options))
        self._options_values = tuple(i[1] for i in options)
        if self._initializing_traits_ is not True:
            self.index = (0, 0)

    @validate("index")
    def _validate_index(self, proposal):
        "Make sure we have two indices and check the range of each proposed index."
        if len(proposal.value) != 2:
            raise TraitError(
                "Invalid selection: index must have two values, but is %r" %
                (proposal.value, ))
        if all(0 <= i < len(self._options_labels) for i in proposal.value):
            return proposal.value
        else:
            raise TraitError("Invalid selection: index out of bounds: %s" %
                             (proposal.value, ))

    orientation = CaselessStrEnum(
        values=["horizontal", "vertical"],
        default_value="horizontal",
        help="Vertical or horizontal.",
    ).tag(sync=True)
    readout = Bool(
        True,
        help="Display the current selected label next to the slider").tag(
            sync=True)
    continuous_update = Bool(
        True,
        help="Update the value of the widget as the user is holding the slider."
    ).tag(sync=True)
Ejemplo n.º 8
0
class _MultipleSelection(_Selection):
    """Base class for MultipleSelection widgets.

    As with ``_Selection``, ``options`` can be specified as a list or dict. If
    given as a list, it will be transformed to a dict of the form
    ``{str(value): value}``.

    Despite their names, ``value`` (and ``selected_label``) will be tuples, even
    if only a single option is selected.
    """

    value = Tuple(help="Selected values")
    selected_labels = Tuple(help="The labels of the selected options",
                            sync=True)

    @property
    def selected_label(self):
        raise AttributeError(
            "Does not support selected_label, use selected_labels")

    def _value_in_options(self):
        # ensure that the chosen value is one of the choices
        if self.options:
            old_value = self.value or []
            new_value = []
            for value in old_value:
                if value in self._options_dict.values():
                    new_value.append(value)
            if new_value:
                self.value = new_value
            else:
                self.value = [next(iter(self._options_dict.values()))]

    def _value_changed(self, name, old, new):
        """Called when value has been changed"""
        if self.value_lock.acquire(False):
            try:
                self.selected_labels = [
                    self._options_labels[self._options_values.index(v)]
                    for v in new
                ]
            except:
                self.value = old
                raise KeyError(new)
            finally:
                self.value_lock.release()

    def _selected_labels_changed(self, name, old, new):
        """Called when the selected label has been changed (typically by the
        frontend)."""
        if self.value_lock.acquire(False):
            try:
                self.value = [self._options_dict[name] for name in new]
            finally:
                self.value_lock.release()
Ejemplo n.º 9
0
class Icon(UILayer):
    _view_name = Unicode('LeafletIconView').tag(sync=True)
    _model_name = Unicode('LeafletIconModel').tag(sync=True)

    icon_url = Unicode('').tag(sync=True, o=True)
    shadow_url = Unicode(None, allow_none=True).tag(sync=True, o=True)
    icon_size = Tuple((10, 10), allow_none=True).tag(sync=True, o=True)
    shadow_size = Tuple((10, 10), allow_none=True).tag(sync=True, o=True)
    icon_anchor = Tuple((0, 0), allow_none=True).tag(sync=True, o=True)
    shadow_anchor = Tuple((0, 0), allow_none=True).tag(sync=True, o=True)
    popup_anchor = Tuple((0, 0), allow_none=True).tag(sync=True, o=True)
Ejemplo n.º 10
0
class PlainGeometry(Geometry):
    _view_name = Unicode('PlainGeometryView').tag(sync=True)
    _model_name = Unicode('PlainGeometryModel').tag(sync=True)

    vertices = List(vector3(CFloat)).tag(sync=True)
    colors = List(Color).tag(sync=True)
    faces = List(List(CFloat)).tag(sync=True)
    # TODO: type this better. Can handle lists of string colors, or lists of lists of string colors.
    faceColors = Tuple().tag(sync=True)
    # TODO: type this better. Can handle lists of vector3(CFloat), or lists of lists of vector3(CFloat).
    faceNormals = Tuple().tag(sync=True)
Ejemplo n.º 11
0
class Warp(Effect):
    """A warp effect to another block."""

    _model_name = Unicode('WarpModel').tag(sync=True)

    offset = Union((Tuple(trait=Unicode, minlen=3, maxlen=3), CFloat(0.)),
                   default_value=0.).tag(sync=True)
    factor = Union((Tuple(trait=Unicode, minlen=3, maxlen=3), CFloat(0.)),
                   default_value=1.).tag(sync=True)

    @property
    def input_dim(self):
        """Input dimension."""
        return 3
Ejemplo n.º 12
0
class SelectionRangeSlider(_MultipleSelection):
    """Slider to select a single item from a list or dictionary."""
    _view_name = Unicode('SelectionRangeSliderView').tag(sync=True)
    _model_name = Unicode('SelectionRangeSliderModel').tag(sync=True)

    value = Tuple(help="Min and max selected values")
    label = Tuple(help="Min and max selected labels")
    index = Tuple((0, 0), help="Min and max selected indices").tag(sync=True)

    @validate('options')
    def _validate_options(self, proposal):
        options = _make_options(proposal.value)
        if len(options) == 0:
            raise TraitError("Option list must be nonempty")
        return options

    @observe('options')
    def _propagate_options(self, change):
        "Unselect any option"
        if self._initializing_traits_ is not True:
            self.index = (0, 0)
        self.set_trait('_options_labels', tuple(i[0] for i in change.new))
        self._options_values = tuple(i[1] for i in change.new)

    @validate('index')
    def _validate_index(self, proposal):
        "Make sure we have two indices and check the range of each proposed index."
        if len(proposal.value) != 2:
            raise TraitError(
                'Invalid selection: index must have two values, but is %r' %
                (proposal.value, ))
        if all(0 <= i < len(self._options_labels) for i in proposal.value):
            return proposal.value
        else:
            raise TraitError('Invalid selection: index out of bounds')

    orientation = CaselessStrEnum(
        values=['horizontal', 'vertical'],
        default_value='horizontal',
        allow_none=False,
        help="Vertical or horizontal.").tag(sync=True)
    readout = Bool(
        True,
        help="Display the current selected label next to the slider").tag(
            sync=True)
    continuous_update = Bool(
        True,
        help="Update the value of the widget as the user is holding the slider."
    ).tag(sync=True)
Ejemplo n.º 13
0
class Classifier(widgets.DOMWidget, Updater):
    _view_module = Unicode(
        "nbextensions/openseat-notebook/js/widget_openseat", sync=True)
    _view_name = Unicode("ClassifierView", sync=True)
    _model_name = Unicode("ClassifierModel", sync=True)

    book = Instance(klass=ConceptBook, sync=True, **widget_serialization)
    rows = Tuple(sync=True, **widget_serialization)
    columns = Tuple(sync=True, **widget_serialization)
    row_property = Unicode(sync=True)
    column_property = Unicode(sync=True)

    def __init__(self, *args, **kwargs):
        super(Classifier, self).__init__(*args, **kwargs)
        link((self.book, "_updated"), (self, "_updated"))
Ejemplo n.º 14
0
class Gnomonic(GeoScale):
    """A perspective projection which displays great circles as straight lines.

    The projection is neither equal-area nor conformal.

    Attributes
    ----------
    scale_factor: float (default: 145)
       Specifies the scale value for the projection
    center: tuple (default: (0, 60))
        Specifies the longitude and latitude where the map is centered.
    precision: float (default: 0.1)
        Specifies the threshold for the projections adaptive resampling to the
        specified value in pixels.
    clip_angle: float (default: 89.999)
        Specifies the clipping circle radius to the specified angle in degrees.
    """

    scale_factor = Float(145.0).tag(sync=True)
    center = Tuple((0, 60)).tag(sync=True)
    precision = Float(0.1).tag(sync=True)
    clip_angle = Float(89.999, min=0.0, max=360.0).tag(sync=True)
    rtype = '(Number, Number)'
    dtype = np.number
    _view_name = Unicode('Gnomonic').tag(sync=True)
    _model_name = Unicode('GnomonicModel').tag(sync=True)
Ejemplo n.º 15
0
class Box(DOMWidget, CoreWidget):
    """Displays multiple widgets in a group."""
    _model_module = Unicode('jupyter-js-widgets').tag(sync=True)
    _view_module = Unicode('jupyter-js-widgets').tag(sync=True)
    _model_name = Unicode('BoxModel').tag(sync=True)
    _view_name = Unicode('BoxView').tag(sync=True)

    # Child widgets in the container.
    # Using a tuple here to force reassignment to update the list.
    # When a proper notifying-list trait exists, that is what should be used here.
    children = Tuple().tag(sync=True, **widget_serialization)

    box_style = CaselessStrEnum(
        values=['success', 'info', 'warning', 'danger', ''],
        default_value='',
        help="""Use a predefined styling for the box.""").tag(sync=True)

    def __init__(self, children=(), **kwargs):
        kwargs['children'] = children
        super(Box, self).__init__(**kwargs)
        self.on_displayed(Box._fire_children_displayed)

    def _fire_children_displayed(self):
        for child in self.children:
            child._handle_displayed()
Ejemplo n.º 16
0
class DOMWidget(Widget):
    """Widget that can be inserted into the DOM"""

    _model_name = Unicode('DOMWidgetModel').tag(sync=True)

    visible = Bool(True, allow_none=True, help="Whether the widget is visible.  False collapses the empty space, while None preserves the empty space.").tag(sync=True)
    _dom_classes = Tuple(help="DOM classes applied to widget.$el.").tag(sync=True)

    layout = Instance(Layout, allow_none=True).tag(sync=True, **widget_serialization)
    def _layout_default(self):
        return Layout()

    def add_class(self, className):
        """
        Adds a class to the top level element of the widget.

        Doesn't add the class if it already exists.
        """
        if className not in self._dom_classes:
            self._dom_classes = list(self._dom_classes) + [className]
        return self

    def remove_class(self, className):
        """
        Removes a class from the top level element of the widget.

        Doesn't remove the class if it doesn't exist.
        """
        if className in self._dom_classes:
            self._dom_classes = [c for c in self._dom_classes if c != className]
        return self
Ejemplo n.º 17
0
class GoogleOAuthenticator(OAuthenticator, GoogleOAuth2Mixin):

    login_handler = GoogleLoginHandler
    callback_handler = GoogleOAuthHandler

    hosted_domain = Tuple(
        config=True,
        help=
        """Tuple of hosted domains used to restrict sign-in, e.g. mycollege.edu"""
    )
    login_service = Unicode(
        os.environ.get('LOGIN_SERVICE', 'Google'),
        config=True,
        help="""Google Apps hosted domain string, e.g. My College""")

    @default('hosted_domain')
    def _get_hosted_domain(self):
        domains = os.environ.get('HOSTED_DOMAIN', '')
        return tuple([domain.strip() for domain in domains.split(',')])

    @gen.coroutine
    def authenticate(self, handler, data=None):
        code = handler.get_argument('code', False)
        if not code:
            raise HTTPError(400, "oauth callback made without a token")
        handler.settings['google_oauth'] = {
            'key': self.client_id,
            'secret': self.client_secret,
            'scope': ['openid', 'email']
        }
        user = yield handler.get_authenticated_user(
            redirect_uri=self.get_callback_url(handler), code=code)
        access_token = str(user['access_token'])

        http_client = handler.get_auth_http_client()

        response = yield http_client.fetch(self._OAUTH_USERINFO_URL +
                                           '?access_token=' + access_token)

        if not response:
            self.clear_all_cookies()
            raise HTTPError(500, 'Google authentication failed')

        body = response.body.decode()
        self.log.debug('response.body.decode(): {}'.format(body))
        bodyjs = json.loads(body)

        username = bodyjs['email']

        self.hosted_domains = self._get_hosted_domain()

        if self.hosted_domains:
            username, _, domain = username.partition('@')
            if not domain in self.hosted_domains or \
                bodyjs['hd'] not in self.hosted_domains:
                raise HTTPError(
                    403,
                    "You are not signed in to your {} account.".format(domain))

        return username
Ejemplo n.º 18
0
class _MultipleSelection(_Selection):
    """Base class for MultipleSelection widgets.

    As with ``_Selection``, ``options`` can be specified as a list or dict. If
    given as a list, it will be transformed to a dict of the form
    ``{unicode_type(value): value}``.

    Despite its name, the ``value`` attribute is a tuple, even if only a single
    option is selected.
    """

    value = Tuple(help="Selected values").tag(sync=True,
                                              to_json=_values_to_labels,
                                              from_json=_labels_to_values)

    @observe('options')
    def _value_in_options(self, change):
        new_value = []
        for v in self.value:
            if v in self._options_dict.values():
                new_value.append(v)
        self.value = new_value

    @validate('value')
    def _validate_value(self, proposal):
        value = proposal['value']
        try:
            for v in value:
                _value_to_label(v, self)
            return value
        except StopIteration:
            raise TraitError('Invalid selection')
Ejemplo n.º 19
0
class _IntRange(_Int):
    value = Tuple(CInt(),
                  CInt(),
                  default_value=(0, 1),
                  help="Tuple of (lower, upper) bounds").tag(sync=True)

    @property
    def lower(self):
        return self.value[0]

    @lower.setter
    def lower(self, lower):
        self.value = (lower, self.value[1])

    @property
    def upper(self):
        return self.value[1]

    @upper.setter
    def upper(self, upper):
        self.value = (self.value[0], upper)

    @validate('value')
    def _validate_value(self, proposal):
        lower, upper = proposal['value']
        if upper < lower:
            raise TraitError('setting lower > upper')
        return lower, upper
Ejemplo n.º 20
0
class Mesh(Object3D):
    """Mesh

    Autogenerated by generate-wrappers.js
    See https://threejs.org/docs/#api/objects/Mesh
    """
    def __init__(self, geometry=None, material=[], **kwargs):
        kwargs['geometry'] = geometry
        kwargs['material'] = material
        super(Mesh, self).__init__(**kwargs)

    _model_name = Unicode('MeshModel').tag(sync=True)

    material = Union([Instance(Material), Tuple()]).tag(sync=True,
                                                        **widget_serialization)

    geometry = Union([
        Instance(BaseGeometry, allow_none=False),
        Instance(BaseBufferGeometry, allow_none=False)
    ]).tag(sync=True, **widget_serialization)

    drawMode = Enum(DrawModes, "TrianglesDrawMode",
                    allow_none=False).tag(sync=True)

    morphTargetInfluences = List().tag(sync=True)

    type = Unicode("Mesh", allow_none=False).tag(sync=True)
Ejemplo n.º 21
0
class _IntRange(_Int):
    value = Tuple(CInt(), CInt(), default_value=(0, 1), help="Tuple of (lower, upper) bounds", sync=True)
    lower = CInt(0, help="Lower bound", sync=False)
    upper = CInt(1, help="Upper bound", sync=False)
    
    def __init__(self, *pargs, **kwargs):
        value_given = 'value' in kwargs
        lower_given = 'lower' in kwargs
        upper_given = 'upper' in kwargs
        if value_given and (lower_given or upper_given):
            raise ValueError("Cannot specify both 'value' and 'lower'/'upper' for range widget")
        if lower_given != upper_given:
            raise ValueError("Must specify both 'lower' and 'upper' for range widget")
        
        super(_IntRange, self).__init__(*pargs, **kwargs)
        
        # ensure the traits match, preferring whichever (if any) was given in kwargs
        if value_given:
            self.lower, self.upper = self.value
        else:
            self.value = (self.lower, self.upper)

        self.on_trait_change(self._validate, ['value', 'upper', 'lower'])
    
    def _validate(self, name, old, new):
        if name == 'value':
            self.lower, self.upper = min(new), max(new)
        elif name == 'lower':
            self.value = (new, self.value[1])
        elif name == 'upper':
            self.value = (self.value[0], new)
Ejemplo n.º 22
0
class Bar(Configurable):

    b = Integer(0, help="The integer b.").tag(config=True)
    enabled = Bool(True, help="Enable bar.").tag(config=True)
    tb = Tuple(()).tag(config=True, multiplicity='*')
    aset = Set().tag(config=True, multiplicity='+')
    bdict = Dict().tag(config=True)
Ejemplo n.º 23
0
class Box(DOMWidget):
    """Displays multiple widgets in a group."""
    _model_name = Unicode('BoxModel', sync=True)
    _view_name = Unicode('BoxView', sync=True)

    # Child widgets in the container.
    # Using a tuple here to force reassignment to update the list.
    # When a proper notifying-list trait exists, that is what should be used here.
    children = Tuple(sync=True, **widget_serialization)
    
    _overflow_values = ['visible', 'hidden', 'scroll', 'auto', 'initial', 'inherit', '']
    overflow_x = CaselessStrEnum(
        values=_overflow_values, 
        default_value='', sync=True, help="""Specifies what
        happens to content that is too large for the rendered region.""")
    overflow_y = CaselessStrEnum(
        values=_overflow_values, 
        default_value='', sync=True, help="""Specifies what
        happens to content that is too large for the rendered region.""")

    box_style = CaselessStrEnum(
        values=['success', 'info', 'warning', 'danger', ''], 
        default_value='', allow_none=True, sync=True, help="""Use a
        predefined styling for the box.""")

    def __init__(self, children = (), **kwargs):
        kwargs['children'] = children
        super(Box, self).__init__(**kwargs)
        self.on_displayed(Box._fire_children_displayed)

    def _fire_children_displayed(self):
        for child in self.children:
            child._handle_displayed()
Ejemplo n.º 24
0
class DOMWidget(Widget):
    """Widget that can be inserted into the DOM"""

    _model_name = Unicode('DOMWidgetModel').tag(sync=True)
    _dom_classes = Tuple(help="CSS classes applied to widget DOM element").tag(
        sync=True)
    layout = InstanceDict(Layout).tag(sync=True, **widget_serialization)

    def add_class(self, className):
        """
        Adds a class to the top level element of the widget.

        Doesn't add the class if it already exists.
        """
        if className not in self._dom_classes:
            self._dom_classes = list(self._dom_classes) + [className]
        return self

    def remove_class(self, className):
        """
        Removes a class from the top level element of the widget.

        Doesn't remove the class if it doesn't exist.
        """
        if className in self._dom_classes:
            self._dom_classes = [
                c for c in self._dom_classes if c != className
            ]
        return self
Ejemplo n.º 25
0
class _MultipleSelection(_Selection):
    """Base class for MultipleSelection widgets.

    As with ``_Selection``, ``options`` can be specified as a list or dict. If
    given as a list, it will be transformed to a dict of the form
    ``{str(value): value}``.

    Despite its name, the ``value`` attribute is a tuple, even if only a single
    option is selected.
    """

    value = Tuple(help="Selected values").tag(sync=True,
                                              to_json=_values_to_labels,
                                              from_json=_labels_to_values)

    def _value_in_options(self):
        if self.options:
            old_value = self.value or []
            new_value = []
            for value in old_value:
                if value in self._options_dict.values():
                    new_value.append(value)
            if new_value:
                self.value = new_value
            else:
                self.value = [next(iter(self._options_dict.values()))]

    @validate('value')
    def _validate_value(self, proposal):
        value = proposal['value']
        if all(_value_to_label(v, self) is not None for v in value):
            return value
        else:
            raise TraitError('Invalid selection')
Ejemplo n.º 26
0
class _MultipleSelection(_Selection):
    """Base class for MultipleSelection widgets.

    As with ``_Selection``, ``options`` can be specified as a list or dict.

    Despite its name, the ``value`` attribute is a tuple, even if only a single
    option is selected.
    """

    value = Tuple(help="Selected values").tag(sync=True,
                                              to_json=_values_to_labels,
                                              from_json=_labels_to_values)

    @observe('options')
    def _value_in_options(self, change):
        "Filter and reset the current value to make sure it is valid."
        new_value = []
        for v in self.value:
            try:
                _value_to_label(v, self)
                new_value.append(v)
            except KeyError:
                continue
        if len(self.value) != len(new_value):
            self.value = tuple(new_value)

    @validate('value')
    def _validate_value(self, proposal):
        value = proposal['value']
        try:
            for v in value:
                _value_to_label(v, self)
            return value
        except KeyError as k:
            raise TraitError('Invalid selection: %r' % (k.args[0], ))
Ejemplo n.º 27
0
class FiltersList(widgets.DOMWidget):
    _view_name = Unicode('FiltersListView').tag(sync=True)
    _model_name = Unicode('FiltersListModel').tag(sync=True)
    _view_module = Unicode('ipydataframe').tag(sync=True)
    _model_module = Unicode('ipydataframe').tag(sync=True)
    children = Tuple(help="List of widget children").tag(
        sync=True, **widgets.widget_serialization)
    in_df = Instance(pd.DataFrame)
    out_df = Instance(pd.DataFrame)

    def __init__(self, df, *args, **kwargs):
        self.in_df = df
        super(FiltersList, self).__init__(*args, **kwargs)
        self.in_df_link = dlink((self, 'in_df'), (self, 'out_df'))
        self.out_df_link = None

    def add_transformation(self, transformation_id):
        try:
            last_child = self.children[-1]
        except IndexError:
            new_transformation = TRANSFORMATION_IDS[transformation_id](
                self.in_df)
            self.children = [new_transformation]
            self.out_df = new_transformation.out_df
            self.in_df_link.unlink()
            self.in_df_link = dlink((self, 'in_df'),
                                    (new_transformation, 'in_df'))
            self.out_df_link = dlink((new_transformation, 'out_df'),
                                     (self, 'out_df'))
Ejemplo n.º 28
0
class MarkerCluster(Layer):
    _view_name = Unicode('LeafletMarkerClusterView').tag(sync=True)
    _model_name = Unicode('LeafletMarkerClusterModel').tag(sync=True)

    markers = Tuple().tag(trait=Instance(Marker),
                          sync=True,
                          **widget_serialization)
Ejemplo n.º 29
0
 def __init__(self, **kwargs):
     super(Face3, self).__init__(
         CInt(),     # a - Vertex A index.
         CInt(),     # b - Vertex B index.
         CInt(),     # c - Vertex C index.
         Union([     # normal - (optional) Face normal (Vector3) or array of 3 vertex normals.
             Vector3(allow_none=True),
             Tuple((Vector3(),) * 3),
         ]),
         Union([     # color - (optional) Face color or array of vertex colors.
             Unicode(allow_none=True),
             Tuple((Unicode(),) * 3),
         ]),
         CInt(allow_none=True),     # materialIndex - (optional) which index of an array of materials to associate with the face.
         default_value=(0, 0, 0, None, None, None)
     )
Ejemplo n.º 30
0
class LayerGroup(Layer):
    _view_name = Unicode('LeafletLayerGroupView').tag(sync=True)
    _model_name = Unicode('LeafletLayerGroupModel').tag(sync=True)

    layers = Tuple(trait=Instance(Layer)).tag(sync=True, **widget_serialization)

    _layer_ids = List()

    @validate('layers')
    def _validate_layers(self, proposal):
        '''Validate layers list.

        Makes sure only one instance of any given layer can exist in the
        layers list.
        '''
        self._layer_ids = [l.model_id for l in proposal.value]
        if len(set(self._layer_ids)) != len(self._layer_ids):
            raise LayerException('duplicate layer detected, only use each layer once')
        return proposal.value

    def add_layer(self, layer):
        if isinstance(layer, dict):
            layer = basemap_to_tiles(layer)
        if layer.model_id in self._layer_ids:
            raise LayerException('layer already in layergroup: %r' % layer)
        self.layers = tuple([l for l in self.layers] + [layer])

    def remove_layer(self, layer):
        if layer.model_id not in self._layer_ids:
            raise LayerException('layer not on in layergroup: %r' % layer)
        self.layers = tuple([l for l in self.layers if l.model_id != layer.model_id])

    def clear_layers(self):
        self.layers = ()