Exemplo n.º 1
0
class VideoStream(MediaStream):
    """Represents a media source by a video."""
    _model_name = Unicode('VideoStreamModel').tag(sync=True)

    url = Unicode('').tag(sync=True)
    play = traitlets.Bool(True).tag(sync=True)
    loop = traitlets.Bool(True).tag(sync=True)
Exemplo n.º 2
0
class Exporter(W.Widget):
    """exports elk diagrams"""

    _model_name = T.Unicode("ELKExporterModel").tag(sync=True)
    _model_module = T.Unicode(EXTENSION_NAME).tag(sync=True)
    _model_module_version = T.Unicode(EXTENSION_SPEC_VERSION).tag(sync=True)
    _view_name = T.Unicode("ELKExporterView").tag(sync=True)
    _view_module = T.Unicode(EXTENSION_NAME).tag(sync=True)
    _view_module_version = T.Unicode(EXTENSION_SPEC_VERSION).tag(sync=True)

    viewer: Viewer = T.Instance(Viewer,
                                allow_none=True).tag(sync=True,
                                                     **W.widget_serialization)
    value: str = T.Unicode(allow_none=True).tag(sync=True)
    enabled: bool = T.Bool(default_value=True).tag(sync=True)
    extra_css: str = T.Unicode(default_value="").tag(sync=True)
    padding: float = T.Float(20).tag(sync=True)
    diagram: Diagram = T.Instance(Diagram, allow_none=True).tag(
        sync=True, **W.widget_serialization)
    strip_ids = T.Bool(default_value=True).tag(sync=True)
    add_xml_header = T.Bool(default_value=True).tag(sync=True)

    @T.observe("diagram")
    def _set_viewer(self, change):
        if change and isinstance(change.new, Diagram):
            self.viewer = change.new.view
Exemplo n.º 3
0
class ToolsToolbar(v.VuetifyTemplate):
    interact_value = traitlets.Unicode(tools_items_default[0]['value'],
                                       allow_none=True).tag(sync=True)
    interact_items = traitlets.Any(tools_items_default).tag(sync=True)
    transform_value = traitlets.Unicode(
        transform_items_default[0]).tag(sync=True)
    transform_items = traitlets.List(
        traitlets.Unicode(),
        default_value=transform_items_default).tag(sync=True)
    supports_transforms = traitlets.Bool(True).tag(sync=True)

    supports_normalize = traitlets.Bool(True).tag(sync=True)
    z_normalize = traitlets.Bool(False, allow_none=True).tag(sync=True)
    normalize = traitlets.Bool(False).tag(sync=True)

    selection_mode_items = traitlets.Any(selection_items_default).tag(
        sync=True)
    selection_mode = traitlets.Unicode('replace').tag(sync=True)

    @traitlets.default('template')
    def _template(self):
        return load_template('vue/tools-toolbar.vue')

    @observe('z_normalize')
    def _observe_normalize(self, change):
        self.normalize = bool(self.z_normalize)
Exemplo n.º 4
0
class LonLatInput(widgets.Text):
    """
    Input for entering lon, lat as comma-separated string

    Link to ``model``, not ``value``! ``model`` is the 2-list of floats,
    ``value`` is the displayed string value.

    Use ``model_is_latlon`` to reverse the order between the ``model`` and the ``value``.
    """

    model = traitlets.List(traitlets.CFloat(),
                           default_value=(0.0, 0.0),
                           minlen=2,
                           maxlen=2)
    model_is_latlon = traitlets.Bool(False)
    description = traitlets.Unicode("Lat, lon (WGS84):").tag(sync=True)
    continuous_update = traitlets.Bool(False).tag(sync=True)

    @traitlets.observe("value")
    def _sync_view_to_model(self, change):
        new = change["new"]
        values = [part.strip() for part in new.split(",")]
        if self.model_is_latlon:
            values.reverse()
        self.model = values

    @traitlets.observe("model")
    def _sync_model_to_view(self, change):
        new = change["new"]
        string = "{:.4f}, {:.4f}".format(
            # https://xkcd.com/2170/
            *(reversed(new) if self.model_is_latlon else new))
        self.value = string
Exemplo n.º 5
0
class FileInput(v.VuetifyTemplate):
    template = traitlets.Unicode(
        load_template('file_input.vue')).tag(sync=True)
    data = traitlets.Unicode('{myfiles: undefined}').tag(sync=True)

    file_info = traitlets.List().tag(sync=True)
    version = traitlets.Int(0).tag(sync=True)
    multiple = traitlets.Bool(True).tag(sync=True)
    disabled = traitlets.Bool(False).tag(sync=True)
    total_progress = traitlets.Int(0).tag(sync=True)
    show_progress = traitlets.Bool(True).tag(sync=True)
    progress_indeterminate = traitlets.Bool(False).tag(sync=True)

    total_progress_inner = 0
    total_size_inner = 0

    def __init__(self, **kwargs):
        self.chunk_listeners = {}
        self.stats = []
        super().__init__(**kwargs)

    @traitlets.observe('file_info')
    def _file_info_changed(self, _):
        self.version += 1
        self.reset_stats()

    def update_stats(self, file_index, bytes_read):
        self.stats[file_index] += bytes_read
        tot = sum(self.stats)
        percent = round((tot / self.total_size_inner) * 100)
        if percent != self.total_progress_inner:
            self.total_progress_inner = percent
            self.total_progress = percent

    def get_files(self, timeout=30):
        files = []
        for index, file in enumerate(self.file_info):
            file = copy.deepcopy(self.file_info[index])
            file['file_obj'] = ClientSideFile(self, index, timeout=timeout)
            files.append(file)
        return files

    def clear(self):
        self.reset_stats()
        self.send({'method': 'clear', 'args': []})

    def reset_stats(self):
        self.stats = [0 for _ in self.file_info]
        self.total_progress = 0
        self.total_progress_inner = 0
        self.total_size_inner = sum([f['size'] for f in self.file_info])

    def vue_upload(self, content, buffers):
        listener_id = content['id']
        listener = self.chunk_listeners.get(listener_id)
        if listener:
            if listener.version != self.version:
                del self.chunk_listeners[listener_id]
            else:
                listener.handle_chunk(content, buffers[0])
Exemplo n.º 6
0
class SettingsEditor(v.VuetifyTemplate):
    template_file = os.path.join(os.path.dirname(__file__), "vue/vjsf.vue")

    vjsf_loaded = traitlets.Bool(False).tag(sync=True)
    values = traitlets.Dict(default_value={}).tag(sync=True)
    schema = traitlets.Dict().tag(sync=True)
    valid = traitlets.Bool(False).tag(sync=True)
Exemplo n.º 7
0
Arquivo: view.py Projeto: xinhen/vaex
class DataArray(ViewBase):
    """Will display a DataArray interactively, with an optional custom display_function.

    By default, it will simply display(...) the DataArray, using xarray's default display mechanism.
    """

    model = traitlets.Instance(model.DataArray)
    clear_output = traitlets.Bool(True, help="Clear output each time the data changes")
    display_function = traitlets.Any(display)
    matplotlib_autoshow = traitlets.Bool(True, help="Will call plt.show() inside output context if open figure handles exist")
    numpy_errstate = traitlets.Dict({'all': 'ignore'}, help="Default numpy errstate during display to avoid showing error messsages, see :py:data:`numpy.errstate`_ ")

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.output = widgets.Output()
        self.output_data_array = widgets.Output()
        self.children = (self.progress_widget, self.output_data_array, self.output)
        self.model.observe(self.update_output, ['grid', 'grid_sliced'])
        self.update_output()

    def update_output(self, change=None):
        if self.clear_output:
            self.output_data_array.clear_output(wait=True)
        with self.output_data_array, np.errstate(**self.numpy_errstate):
            grid = self.model.grid_sliced
            if grid is None:
                grid = self.model.grid
            if grid is not None:
                self.display_function(grid)
                # make sure show is called inside the output widget
                if self.matplotlib_autoshow and 'matplotlib' in sys.modules:
                    import matplotlib.pyplot as plt
                    if plt.get_fignums():
                        plt.show()
Exemplo n.º 8
0
class QuantitativeScale(Scale):

    type = T.Unicode('quantitative')
    clamp = T.Bool()
    interploate = T.Unicode()
    nice = T.Union([T.Bool(), T.CFloat])
    zero = T.Bool()
Exemplo n.º 9
0
Arquivo: api.py Projeto: mindis/altair
class Shape(Shelf):
    shelf_name = 'shape'
    value = T.Enum([
        'circle', 'square', 'cross', 'diamond', 'triangle-up', 'triangle-down'
    ],
                   default_value='circle')
    aggregate = T.Enum(['count'], default_value=None, allow_none=True)
    legend = T.Bool(True)
    filled = T.Bool(False)
Exemplo n.º 10
0
class CameraStream(MediaStream):
    """Represents a media source by a camera/webcam."""
    _model_name = Unicode('CameraStreamModel').tag(sync=True)

    # Specify audio constraint and video constraint as a boolean or dict.
    audio = traitlets.Bool(True).tag(sync=True)
    video = traitlets.Bool(True).tag(sync=True)

    def close(self):
        self.send({'msg': 'close'})
Exemplo n.º 11
0
class FlatMaterial(Material):
    """Renders the object as a uniform color without any shading.
  If holdout is true, then the pixels of the object will be transparent in the final image (alpha=0).
  (Note, that this is not the same as a transparent object. It still "occludes" other objects)

  The indirect_visibility flag controls if the object casts shadows, can be seen in reflections and
  emits light.
  """
    color = ktl.RGBA(default_value=Color.from_name('white'))
    holdout = tl.Bool(False)
    indirect_visibility = tl.Bool(True)
Exemplo n.º 12
0
class PortLabelPlacement(LayoutOptionWidget):
    """Decides on a placement method for port labels; if empty, the node label’s
    position is not modified.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-portLabels-placement.html
    """

    identifier = "org.eclipse.elk.portLabels.placement"
    metadata_provider = "org.options.CoreOptions"
    applies_to = [ElkNode]
    group = "portLabels"

    inside = T.Bool(default_value=True)
    next_to_port = T.Bool(default_value=True)
    always_same_side = T.Bool(default_value=False)
    space_efficient = T.Bool(default_value=True)

    value = T.Unicode(allow_none=True)

    def _ui(self) -> List[W.Widget]:
        cb_inside = W.Checkbox(description="Inside")
        cb_next_to_port = W.Checkbox(description="Next to Port if Possible")
        cb_always_same_side = W.Checkbox(description="Always Same Side")
        cb_space_efficient = W.Checkbox(description="Space Efficient")

        T.link((self, "inside"), (cb_inside, "value"))
        T.link((self, "next_to_port"), (cb_next_to_port, "value"))
        T.link((self, "always_same_side"), (cb_always_same_side, "value"))
        T.link((self, "space_efficient"), (cb_space_efficient, "value"))

        return [
            cb_inside,
            cb_next_to_port,
            cb_always_same_side,
            cb_space_efficient,
        ]

    @T.observe("inside", "next_to_port", "always_same_side", "space_efficient")
    def _update_value(self, change=None):
        options = ["INSIDE" if self.inside else "OUTSIDE"]
        if self.next_to_port:
            options.append("NEXT_TO_PORT_IF_POSSIBLE")
        if self.always_same_side:
            options.append("ALWAYS_SAME_SIDE")
            self.space_efficient = False

        if self.space_efficient:
            options.append("SPACE_EFFICIENT")

        if options:
            self.value = " ".join(options)
        else:
            self.value = None
Exemplo n.º 13
0
class PipelineStatusView(PipeStatusView):

    toggle_btn = T.Instance(W.Button)
    include_exception = T.Bool(default_value=True)
    collapsed = T.Bool(default_value=True)
    statuses = T.List()

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

    @T.default("toggle_btn")
    def _default_toggle(self):
        btn = W.Button(icon="chevron-down").add_class("elk-pipe-toggle-btn")
        toggle_cls = "elk-pipe-closed"

        @btn.on_click
        def toggle(b):
            self.collapsed = not self.collapsed
            if self.collapsed:
                btn.add_class(toggle_cls)
            else:
                btn.remove_class(toggle_cls)

        return btn

    @T.observe("collapsed", "statuses")
    def _update_children(self, change=None):
        children = [
            W.HBox(
                [
                    self.toggle_btn,
                    self.html,
                ]
            ),
        ]
        if not self.collapsed:
            children.extend(self.statuses)
        self.children = children

    def update_children(self, pipe: "Pipeline"):
        statuses = [p.status_widget for p in pipe.pipes]
        self.statuses = [
            W.HBox(
                [
                    W.HTML(value="<pre>  </pre>").add_class("elk-pipe-space"),
                    status,
                    W.HTML(value=f'<pre class="elk-pipe-accessor">.pipes[{i}]</pre>'),
                ]
            )
            for i, status in enumerate(statuses)
        ]
Exemplo n.º 14
0
class _InfoSnackbar(ipyvuetify.VuetifyTemplate):
    color = traitlets.Unicode("primary").tag(sync=True, allow_null=True)
    message = traitlets.Unicode("").tag(sync=True, allow_null=False)
    timeout = traitlets.Integer(5000).tag(sync=True, allow_null=True)
    active = traitlets.Bool(True).tag(sync=True, allow_null=True)
    multi_line = traitlets.Bool(True).tag(sync=True, allow_null=True)

    template = traitlets.Unicode(
        """
        <template>
            <v-snackbar
                v-model="active"
                centered=true
                :color="color"
                elevation=0
                :multi-line="multi_line"
                :timeout="timeout"
            >
              {{message}}

            <v-btn
              color="white"
              text
              @click="active = false"
            >
              Close
            </v-btn>

            </v-snackbar>
          </template>

        """
    ).tag(sync=True)

    def __init__(
        self,
        snackbar=False,
        message=None,
        multi_line=True,
        color="primary",
        timeout=6000,
        active=True,
        *args,
        **kwargs
    ):
        super().__init__(*args, **kwargs)
        self.color = color
        self.timeout = timeout
        self.active = active
        self.message = message
        self.multi_line = multi_line
Exemplo n.º 15
0
Arquivo: api.py Projeto: mindis/altair
class Scale(BaseObject):
    """Scale object that represents the Scale property common to: X, Y, Size, Color"""
    # TODO: Supported types for type
    # TODO: Supported types for reverse
    # TODO: Supported types for zero
    # TODO: Supported types for nice

    type = T.Enum(['linear', 'log', 'pow', 'sqrt', 'quantile'],
                  default_value='linear')
    reverse = T.Bool(False)
    zero = T.Bool(True)
    nice = T.Enum(['second', 'minute', 'hour', 'day', 'week', 'month', 'year'],
                  allow_none=True)
    useRawDomain = T.Bool(default_value=None, allow_none=True)
Exemplo n.º 16
0
class Pipe(W.Widget):
    disposition = T.Instance(PipeDisposition)
    enabled: bool = T.Bool(default_value=True)
    inlet: MarkElementWidget = T.Instance(MarkElementWidget, kw={})
    outlet: MarkElementWidget = T.Instance(MarkElementWidget, kw={})
    dirty: bool = T.Bool(default_value=True)
    observes: Tuple[str] = TypedTuple(T.Unicode(), kw={})
    reports: Tuple[str] = TypedTuple(T.Unicode(), kw={})
    _task: asyncio.Future = None

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

    def schedule_run(self, change: T.Bunch = None) -> asyncio.Task:
        # schedule task on loop
        if self._task:
            self._task.cancel()
        self._task = asyncio.create_task(self.run())

        self._task.add_done_callback(self._post_run)
        return self._task

    def _post_run(self, future: asyncio.Future):
        try:
            future.exception()
        except asyncio.CancelledError:
            pass
        except Exception as E:
            raise E

    async def run(self):
        # do work
        self.outlet.value = self.inlet.value

    def check_dirty(self) -> bool:
        flow = self.inlet.flow

        if any(
                any(re.match(f"^{obs}$", f) for f in flow)
                for obs in self.observes):
            # mark this pipe as dirty so will run
            self.dirty = True
            self.disposition = PipeDisposition.waiting
            # add this pipes reporting to the outlet flow
            flow = tuple(set([*flow, *self.reports]))
        else:
            self.dirty = False
            self.disposition = PipeDisposition.done
        self.outlet.flow = flow
        return self.dirty
Exemplo n.º 17
0
class VolumeRendererThree(widgets.DOMWidget):
    """Widget class representing a volume (rendering) using three.js"""
    _view_name = Unicode('VolumeRendererThreeView').tag(sync=True)
    _view_module = Unicode('ipyvolume').tag(sync=True)
    _model_name = Unicode('VolumeRendererThreeModel').tag(sync=True)
    _model_module = Unicode('ipyvolume').tag(sync=True)

    data = Array(default_value=None,
                 allow_none=True).tag(sync=True,
                                      **array_cube_png_serialization)
    data_min = traitlets.CFloat().tag(sync=True)
    data_max = traitlets.CFloat().tag(sync=True)
    tf = traitlets.Instance(TransferFunction, allow_none=True).tag(
        sync=True, **ipywidgets.widget_serialization)
    angle1 = traitlets.Float(0.1).tag(sync=True)
    angle2 = traitlets.Float(0.2).tag(sync=True)

    scatters = traitlets.List(traitlets.Instance(Scatter), [],
                              allow_none=False).tag(
                                  sync=True, **ipywidgets.widget_serialization)

    animation = traitlets.Float(1000.0).tag(sync=True)

    ambient_coefficient = traitlets.Float(0.5).tag(sync=True)
    diffuse_coefficient = traitlets.Float(0.8).tag(sync=True)
    specular_coefficient = traitlets.Float(0.5).tag(sync=True)
    specular_exponent = traitlets.Float(5).tag(sync=True)
    stereo = traitlets.Bool(False).tag(sync=True)
    fullscreen = traitlets.Bool(False).tag(sync=True)

    width = traitlets.CInt(500).tag(sync=True)
    height = traitlets.CInt(400).tag(sync=True)
    downscale = traitlets.CInt(1).tag(sync=True)
    show = traitlets.Unicode("Volume").tag(sync=True)  # for debugging

    xlim = traitlets.List(traitlets.CFloat,
                          default_value=[0, 1],
                          minlen=2,
                          maxlen=2).tag(sync=True)
    ylim = traitlets.List(traitlets.CFloat,
                          default_value=[0, 1],
                          minlen=2,
                          maxlen=2).tag(sync=True)
    zlim = traitlets.List(traitlets.CFloat,
                          default_value=[0, 1],
                          minlen=2,
                          maxlen=2).tag(sync=True)

    style = traitlets.Dict(default_value=default_style).tag(sync=True)
Exemplo n.º 18
0
class ToolsToolbar(v.VuetifyTemplate):
    interact_value = traitlets.Unicode(tools_items_default[0]['value'],
                                       allow_none=True).tag(sync=True)
    interact_items = traitlets.Any(tools_items_default).tag(sync=True)
    transform_value = traitlets.Unicode(
        transform_items_default[0]).tag(sync=True)
    transform_items = traitlets.List(
        traitlets.Unicode(),
        default_value=transform_items_default).tag(sync=True)
    supports_transforms = traitlets.Bool(True).tag(sync=True)
    supports_normalize = traitlets.Bool(True).tag(sync=True)

    @traitlets.default('template')
    def _template(self):
        return load_template('vue/tools-toolbar.vue')
Exemplo n.º 19
0
class NASAURSSessionMixin(RequestsSessionMixin):
    check_url = tl.Unicode()
    hostname = tl.Unicode(default_value="urs.earthdata.nasa.gov")
    auth_required = tl.Bool(True)

    def _create_session(self):
        """Creates an authenticated :class:`requests.Session` with username and password defined

        Returns
        -------
        :class:`requests.Session`

        Notes
        -----
        The session is authenticated against the user-provided self.check_url
        """

        try:
            s = pydap_setup_session(self.username, self.password, check_url=self.check_url)
        except ValueError as e:
            if self.auth_required:
                raise e
            else:
                _log.warning("No auth provided for session")

        return s
Exemplo n.º 20
0
class ToggleButtonWithHint(widgets.VBox):

    value = traitlets.Bool(default_value=False)
    description = traitlets.Unicode()

    def __init__(self, label: str, button_width: str, *args, **kwargs):
        """Create a Toggle-button.

        Parameters
        ----------
        label : str
            The button label.
        button_width : str
            The width of the button.
        """

        kwargs["layout"] = kwargs.get("layout",
                                      widgets.Layout(width=button_width))

        super().__init__(children=[], *args, **kwargs)
        self.button = widgets.ToggleButton(description=str(label),
                                           layout=widgets.Layout(width="95%"))
        widgets.link((self, "value"), (self.button, "value"))

        self.hint = widgets.Output()
        self.children = [self.button, self.hint]

        self.description = label
        widgets.link((self, "description"), (self.button, "description"))

    def __enter__(self):
        return self.hint.__enter__()

    def __exit__(self, *args, **kwargs):
        return self.hint.__exit__(*args, **kwargs)
Exemplo n.º 21
0
class VersionSelectorWidget(ipw.VBox):
    """Class to choose app's version."""

    disabled = traitlets.Bool()
    available_versions = traitlets.Dict(traitlets.Unicode())

    def __init__(self, *args, **kwargs):
        style = {'description_width': '100px'}
        self.release_line = ipw.Dropdown(
            description='Release line',
            style=style,
        )
        self.installed_version = ipw.Text(
            description='Installed version',
            disabled=True,
            style=style,
        )
        self.info = StatusHTML('')

        super().__init__(
            children=[self.release_line, self.installed_version, self.info],
            layout={'min_width': '300px'},
            *args,
            **kwargs,
        )

    @traitlets.observe('disabled')
    def _observe_disabled(self, change):
        self.release_line.disabled = change['new']
Exemplo n.º 22
0
class LayoutPartitioning(LayoutOptionWidget):
    """Whether to activate partitioned layout. This will allow to group nodes
    through the Layout Partition option. a pair of nodes with different
    partition indices is then placed such that the node with lower index is
    placed to the left of the other node (with left-to-right layout direction).
    Depending on the layout algorithm, this may only be guaranteed to work if
    all nodes have a layout partition configured, or at least if edges that
    cross partitions are not part of a partition-crossing cycle.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-partitioning-activate.html
    """

    identifier = "org.eclipse.elk.partitioning.active"
    metadata_provider = "core.options.CoreOptions"
    applies_to = ["parents"]

    active = T.Bool(default_value=False)

    def _ui(self) -> List[W.Widget]:
        cb = W.Checkbox(description="Layout Partitioning")
        T.link((self, "active"), (cb, "value"))
        return [cb]

    @T.observe("active")
    def _update_value(self, change: T.Bunch = None):
        self.value = "true" if self.active else "false"
Exemplo n.º 23
0
class AllowNonFlowPortsToSwitchSides(LayoutOptionWidget):
    """Specifies whether non-flow ports may switch sides if their node’s port
    constraints are either FIXED_SIDE or FIXED_ORDER. A non-flow port is a port
    on a side that is not part of the currently configured layout flow. For
    instance, given a left-to-right layout direction, north and south ports
    would be considered non-flow ports. Further note that the underlying
    criterium whether to switch sides or not solely relies on the minimization
    of edge crossings. Hence, edge length and other aesthetics criteria are not
    addressed.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-layered-allowNonFlowPortsToSwitchSides.html
    """

    identifier = "org.eclipse.elk.layered.allowNonFlowPortsToSwitchSides"
    metadata_provider = "options.LayeredMetaDataProvider"
    applies_to = [ElkPort]

    allow_switch = T.Bool(default_value=False)

    def _ui(self) -> List[W.Widget]:
        cb = W.Checkbox(description="Allow Non-Flow Ports To Switch Sides")

        T.link((self, "allow_switch"), (cb, "value"))

        return [cb]

    @T.observe("allow_switch")
    def _update_value(self, change: T.Bunch = None):
        if self.allow_switch:
            self.value = "true"
        else:
            self.value = "false"
Exemplo n.º 24
0
class LabelEncoder(Transformer):
    '''Encode categorical columns with integer values between 0 and num_classes-1.

    Example:

    >>> import vaex
    >>> df = vaex.from_arrays(color=['red', 'green', 'green', 'blue', 'red'])
    >>> df
     #  color
     0  red
     1  green
     2  green
     3  blue
     4  red
    >>> encoder = vaex.ml.LabelEncoder(features=['color'])
    >>> encoder.fit_transform(df)
     #  color      label_encoded_color
     0  red                          2
     1  green                        1
     2  green                        1
     3  blue                         0
     4  red                          2
    '''
    # title = traitlets.Unicode(default_value='Label Encoder', read_only=True).tag(ui='HTML')
    prefix = traitlets.Unicode(default_value='label_encoded_', help=help_prefix).tag(ui='Text')
    labels_ = traitlets.Dict(default_value={}, allow_none=True, help='The encoded labels of each feature.').tag(output=True)
    allow_unseen = traitlets.Bool(default_value=False, allow_none=False, help='If True, unseen values will be \
                                  encoded with -1, otherwise an error is raised').tag(ui='Checkbox')

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

        :param df: A vaex DataFrame.
        '''

        for feature in self.features:
            labels = vaex.array_types.tolist(df[feature].unique())
            self.labels_[feature] = dict(zip(labels, np.arange(len(labels))))

    def transform(self, df):
        '''
        Transform a DataFrame with a fitted LabelEncoder.

        :param df: A vaex DataFrame.

        Returns:
        :return copy: A shallow copy of the DataFrame that includes the encodings.
        :rtype: DataFrame
        '''

        default_value = None
        if self.allow_unseen:
            default_value = -1

        copy = df.copy()
        for feature in self.features:
            name = self.prefix + feature
            copy[name] = copy[feature].map(mapper=self.labels_[feature], default_value=default_value)

        return copy
class EmployeeObservation(HasTraits):
    employee_id = Int()
    employee_name = Unicode
    employee_salary = Int()
    employee_address = Dict()
    change_triggered = traitlets.Bool()

    def __init__(self, e_id, e_name):
        self.employee_id = e_id
        self.employee_name = e_name
        # self.change_triggered = False # By default value set in False.

    def reset_trigger(self):
        self.change_triggered = False

    @traitlets.observe("employee_salary")
    def change_in_employee_salary(self, salary_delta):
        print("change in salary old: ", salary_delta["old"])
        print("change in salary new: ", salary_delta["new"])
        self.change_triggered = True

    @traitlets.observe("employee_id", "employee_name")
    def monitor_address_change(self, change_details):
        print("Old Data : ", change_details["old"])
        print("New Data : ", change_details["new"])
        self.change_triggered = True
Exemplo n.º 26
0
class Shelf(BaseObject):

    skip = ['shorthand', 'config']

    def __init__(self, shorthand, **kwargs):
        kwargs['shorthand'] = shorthand
        super(Shelf, self).__init__(**kwargs)

    def _infer_type(self, data):
        if self.type is None and self.name in data:
            self.type = infer_vegalite_type(data[self.name])

    def _shorthand_changed(self, name, old, new):
        D = parse_shorthand(self.shorthand)
        for key, val in D.items():
            setattr(self, key, val)

    shorthand = T.Unicode('')
    name = T.Unicode('', config=True)
    type = T.Enum(['N', 'O', 'Q', 'T'],
                  default_value=None,
                  allow_none=True,
                  config=True)
    timeUnit = T.Enum(
        ['year', 'month', 'day', 'date', 'hours', 'minutes', 'seconds'],
        default_value=None,
        allow_none=True)
    bin = T.Union([T.Bool(), T.Instance(Bin)], default_value=False)
    sort = T.List(T.Instance(SortItems), default_value=None, allow_none=True)
    aggregate = T.Enum(['avg', 'sum', 'median', 'min', 'max', 'count'],
                       default_value=None,
                       allow_none=True,
                       config=True)
Exemplo n.º 27
0
class TreatPortLabelsAsGroup(LayoutOptionWidget):
    """If this option is true (default), the labels of a port will be treated as
    a group when it comes to centering them next to their port. If this option
    is false, only the first label will be centered next to the port, with the
    others being placed below. This only applies to labels of eastern and
    western ports and will have no effect if labels are not placed next to their
    port.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-portLabels-treatAsGroup.html
    """

    identifier = "org.eclipse.elk.portLabels.treatAsGroup"
    metadata_provider = "org.options.CoreOptions"
    applies_to = ElkNode
    group = "portLabels"

    treat_as_group = T.Bool(default_value=True)

    def _ui(self) -> List[W.Widget]:
        cb = W.Checkbox(description="Treat Port Labels as Group")

        T.link((self, "treat_as_group"), (cb, "value"))

        return [cb]

    @T.observe("treat_as_group")
    def _update_value(self, change: T.Bunch = None):
        self.value = "true" if self.treat_as_group else "false"
Exemplo n.º 28
0
class MergeHierarchyCrossingEdges(LayoutOptionWidget):
    """If hierarchical layout is active, hierarchy-crossing edges use as few
    hierarchical ports as possible. They are broken by the algorithm, with
    hierarchical ports inserted as required. Usually, one such port is created
    for each edge at each hierarchy crossing point. With this option set to
    true, we try to create as few hierarchical ports as possible in the process.
    In particular, all edges that form a hyperedge can share a port.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-layered-mergeHierarchyEdges.html
    """

    identifier = "org.eclipse.elk.layered.mergeHierarchyEdges"
    metadata_provider = "options.LayeredMetaDataProvider"
    applies_to = ["parents"]

    merge = T.Bool(default_value=True)

    def _ui(self) -> List[W.Widget]:
        cb = W.Checkbox(description="Merge Hierarchy Crossing Edges")
        T.link((self, "merge"), (cb, "value"))
        return [cb]

    @T.observe("merge")
    def _update_value(self, change: T.Bunch = None):
        self.value = "true" if self.merge else "false"
Exemplo n.º 29
0
class Remote(W.Widget):
    """a remote DVCS repository"""

    name = T.Unicode()
    url = T.Unicode()
    heads = T.Dict(value_trait=T.Unicode(), default_value=tuple())
    auto_fetch = T.Bool(True)

    executor = ThreadPoolExecutor(max_workers=1)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.auto_fetch:
            self._on_auto_fetch()

    async def fetch(self):
        """fetch from the remote"""
        await self._fetch()
        self.heads = await self._update_heads()

    async def push(self, ref):
        """push to the remote"""
        await self._push(ref)

    @T.observe("auto_fetch")
    def _on_auto_fetch(self, _change=None):
        """handle changing the auto fetch preference"""
        if self.auto_fetch:
            IOLoop.current().add_callback(self.fetch)
Exemplo n.º 30
0
class InlineEdgeLabels(LayoutOptionWidget):
    """If true, an edge label is placed directly on its edge. May only apply to
    center edge labels. This kind of label placement is only advisable if the
    label’s rendering is such that it is not crossed by its edge and thus stays
    legible.

    https://www.eclipse.org/elk/reference/options/org-eclipse-elk-edgeLabels-inline.html
    """

    identifier = "org.eclipse.elk.edgeLabels.inline"
    applies_to = ElkLabel

    group = "edgeLabels"

    inline = T.Bool(default_value=False)

    def _ui(self) -> List[W.Widget]:
        cb = W.Checkbox(description="Inline Edge Labels")

        T.link((self, "inline"), (cb, "value"))
        return [cb]

    @T.observe("inline")
    def _update_value(self, change: T.Bunch = None):
        self.value = "true" if self.inline else "false"