Exemplo n.º 1
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)
Exemplo n.º 2
0
class Sheet(widgets.DOMWidget):
    """"""
    _view_name = Unicode('SheetView').tag(sync=True)
    _model_name = Unicode('SheetModel').tag(sync=True)
    _view_module = Unicode('ipysheet').tag(sync=True)
    _model_module = Unicode('ipysheet').tag(sync=True)
    _view_module_version = Unicode(semver_range_frontend).tag(sync=True)
    _model_module_version = Unicode(semver_range_frontend).tag(sync=True)
    rows = CInt(3).tag(sync=True)
    columns = CInt(4).tag(sync=True)
    cells = Tuple().tag(sync=True, **widgets.widget_serialization)
    named_cells = Dict(value={}, allow_none=False).tag(sync=True, **widgets.widget_serialization)
    row_headers = Union([Bool(), List(Unicode())], default_value=True).tag(sync=True)
    column_headers = Union([Bool(), List(Unicode())], default_value=True).tag(sync=True)
    stretch_headers = Unicode('all').tag(sync=True)
    column_width = Union([CInt(), List(CInt())], default_value=None, allow_none=True).tag(sync=True)

    def __getitem__(self, item):
        '''Gets a previously created cell at row and column

        Example:

        >>> sheet = ipysheet.sheet(rows=10, columns=5)
        >>> cell = ipysheet.cell(2,0, value='hello')
        >>> assert sheet[2,0] is cell
        >>> sheet[2,0].value = 'bonjour'

        '''
        row, column = item
        for cell in self.cells:
            if cell.row_start == row and cell.column_start == column \
               and cell.row_end == row and cell.column_end == column:
                return cell
        raise IndexError('no cell was previously created for (row, index) = (%s, %s)'.format(row, column))
Exemplo n.º 3
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)
Exemplo n.º 4
0
class DirectionalLight(Light):
    """DirectionalLight

    Autogenerated by generate-wrappers.js
    See https://threejs.org/docs/#api/lights/DirectionalLight
    """
    def __init__(self, color="#ffffff", intensity=1, **kwargs):
        kwargs['color'] = color
        kwargs['intensity'] = intensity
        super(DirectionalLight, self).__init__(**kwargs)

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

    target = Union([
        Instance(Uninitialized),
        Instance(Object3D),
    ],
                   default_value=UninitializedSentinel,
                   allow_none=False).tag(sync=True,
                                         **unitialized_serialization)

    shadow = Union([
        Instance(Uninitialized),
        Instance(LightShadow),
    ],
                   default_value=UninitializedSentinel,
                   allow_none=False).tag(sync=True,
                                         **unitialized_serialization)

    type = Unicode("DirectionalLight", allow_none=False).tag(sync=True)
Exemplo n.º 5
0
class A(Widget):
    _model_name = Unicode("A").tag(sync=True)
    _model_module = Unicode("test2").tag(sync=True)

    string = Unicode(None, allow_none=True).tag(sync=True)
    boolean = Bool(True).tag(sync=True)
    list = List(Int(), [1, 2, 3]).tag(sync=True)
    tuple = Tuple(Int(), Unicode(), CFloat(), default_value=(3, "foo", 4.5)).tag(
        sync=True
    )
    dict = Dict().tag(sync=True)
    ddict = Dict(default_value={"foo": "bar"}).tag(sync=True)
    enum = Enum(("foo", "bar"), default_value="bar").tag(sync=True)
    enum_none = Enum(("foo", "bar"), default_value=None, allow_none=True).tag(sync=True)
    any = Any(42).tag(sync=True)

    not_synced = Unicode()

    union_defA = Union((Float(), Unicode()), default_value=None, allow_none=True).tag(sync=True)
    union_defB = Union((Float(5.5), Unicode('4.3'))).tag(sync=True)

    union_enum = Union((
        Float(),
        Enum(("foo", "bar"), default_value=None, allow_none=True)
    ), default_value=None, allow_none=True).tag(sync=True)
Exemplo n.º 6
0
class SplitMapControl(Control):
    _view_name = Unicode('LeafletSplitMapControlView').tag(sync=True)
    _model_name = Unicode('LeafletSplitMapControlModel').tag(sync=True)

    left_layer = Union(
        (Instance(Layer), List(Instance(Layer)))).tag(sync=True,
                                                      **widget_serialization)
    right_layer = Union(
        (Instance(Layer), List(Instance(Layer)))).tag(sync=True,
                                                      **widget_serialization)

    @default('left_layer')
    def _default_left_layer(self):
        return TileLayer()

    @default('right_layer')
    def _default_right_layer(self):
        return TileLayer()

    def __init__(self, **kwargs):
        super(SplitMapControl, self).__init__(**kwargs)
        self.on_msg(self._handle_leaflet_event)

    def _handle_leaflet_event(self, _, content, buffers):
        if content.get('event', '') == 'dividermove':
            event = content.get('event')
            self.x = event.x
Exemplo n.º 7
0
class Line2(Mesh):
    """Line2

    Autogenerated by generate-wrappers.js
    This class is a custom class for pythreejs, with no
    direct corresponding class in three.js.
    """
    def __init__(self,
                 geometry=UninitializedSentinel,
                 material=UninitializedSentinel,
                 **kwargs):
        kwargs['geometry'] = geometry
        kwargs['material'] = material
        super(Line2, self).__init__(**kwargs)

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

    material = Union([
        Instance(Uninitialized),
        Instance(LineMaterial),
    ],
                     default_value=UninitializedSentinel,
                     allow_none=True).tag(sync=True,
                                          **unitialized_serialization)

    geometry = Union([
        Instance(Uninitialized),
        Instance(LineGeometry),
    ],
                     default_value=UninitializedSentinel,
                     allow_none=True).tag(sync=True,
                                          **unitialized_serialization)

    type = Unicode("Line2", allow_none=False).tag(sync=True)
Exemplo n.º 8
0
class Html(ReactWidget):

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

    children = Union([
        Union([Unicode(), Instance(DOMWidget)], default_value=None),
        List(Union([Unicode(), Instance(DOMWidget)], default_value=None))
    ],
                     default_value=None,
                     allow_none=True).tag(sync=True, **widget_serialization)

    tag = Unicode(None, allow_none=True).tag(sync=True)
Exemplo n.º 9
0
def Face3(**kwargs):
    return Tuple(
        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(),
            List(Vector3(), minlen=3, maxlen=3)]),
        Union([     # color - (optional) Face color or array of vertex colors.
            Unicode(),
            List(Unicode(), minlen=3, maxlen=3)]),
        CInt(),     # materialIndex - (optional) which index of an array of materials to associate with the face.
        )
Exemplo n.º 10
0
 def __init__(self, default_value=Undefined, **kwargs):
     super(Uniform, self).__init__(traits=dict(value=Union((
         Int(),
         Float(),
         Color(),
         Instance('pythreejs.Texture'),
         List(trait=Union((Int(), Float(), Color(),
                           Instance('pythreejs.Texture')))),
     ),
                                                           allow_none=True),
                                               type=Unicode()),
                                   default_value=default_value,
                                   **kwargs)
Exemplo 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
Exemplo n.º 12
0
class Envelope(AudioNode):
    """ADSR envelope generator.

    Envelope outputs a signal which can be connected to a :class:`Signal`.

    """

    _model_name = Unicode("EnvelopeModel").tag(sync=True)

    attack = Float(0.01, help="Envelope attack").tag(sync=True)
    decay = Float(0.1, help="Envelope decay").tag(sync=True)
    sustain = Float(1.0, help="Envelope sustain").tag(sync=True)
    release = Float(0.5, help="Envelope release").tag(sync=True)

    attack_curve = Union([Enum(CURVES), List(Float)], default_value="linear").tag(sync=True)
    decay_curve = Enum(BASIC_CURVES, default_value="exponential").tag(sync=True)
    release_curve = Union([Enum(CURVES), List(Float)], default_value="exponential").tag(sync=True)

    array = Array(allow_none=True, default_value=None, read_only=True, help="Envelope data").tag(
        sync=True, **data_array_serialization
    )
    array_length = Int(1024, help="Envelope data resolution (array length)").tag(sync=True)
    sync_array = Bool(False, help="If True, synchronize envelope data").tag(sync=True)

    def __init__(self, **kwargs):
        if "_output" not in kwargs:
            out_node = Signal(units="normalRange", _create_node=False)
            kwargs.update({"_output": out_node})

        super().__init__(**kwargs)

    def trigger_attack(self, time=None, velocity=1):
        add_or_send_event("triggerAttack", self, {"time": time, "velocity": velocity})
        return self

    def trigger_release(self, time=None):
        add_or_send_event("triggerRelease", self, {"time": time})
        return self

    def trigger_attack_release(self, duration, time=None, velocity=1):
        args = {"duration": duration, "time": time, "velocity": velocity}
        add_or_send_event("triggerAttackRelease", self, args)
        return self

    def _repr_keys(self):
        for key in super()._repr_keys():
            yield key
        for key in ["attack", "decay", "sustain", "release"]:
            yield key
Exemplo n.º 13
0
def CSSColor(default_value):
    """Create a color trait.

    Temporary workaround to allow both hsl(h,s,l) syntax
    and linking to the standard color picker widget.
    """
    return Union([Color(default_value), Unicode()])
Exemplo n.º 14
0
class AnimationAction(AnimationActionBase, DOMWidget):
    """AnimationAction is a three widget that also has its own view.

    The view offers animation action controls.
    """
    _view_name = Unicode('AnimationActionView').tag(sync=True)
    _view_module = Unicode(npm_pkg_name).tag(sync=True)
    _view_module_version = Unicode(EXTENSION_SPEC_VERSION).tag(sync=True)

    _previewable = False

    # Normally an int, but can also be inf:
    repititions = Union([CInt(), CFloat()], default_value=float('inf'), allow_none=False).tag(sync=True)

    def play(self):
        content = {
            "type": "play",
        }
        self.send(content=content, buffers=None)

    def pause(self):
        content = {
            "type": "pause",
        }
        self.send(content=content, buffers=None)

    def stop(self):
        content = {
            "type": "stop",
        }
        self.send(content=content, buffers=None)
Exemplo n.º 15
0
class Component(_GanyWidgetBase):
    """A data component widget."""

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

    name = Unicode().tag(sync=True)
    array = Union((Instance(Widget), Array())).tag(sync=True,
                                                   **data_array_serialization)

    min = CFloat(allow_none=True, default_value=None)
    max = CFloat(allow_none=True, default_value=None)

    def __init__(self, name, array, **kwargs):
        """Create a new Component instance given its name and array."""
        super(Component, self).__init__(name=name, array=array, **kwargs)

        if self.min is None:
            self.min = np.min(
                self.array) if not isinstance(self.array, Widget) else np.min(
                    self.array.array)

        if self.max is None:
            self.max = np.max(
                self.array) if not isinstance(self.array, Widget) else np.max(
                    self.array.array)
Exemplo n.º 16
0
class VueWidget(DOMWidget, Events):

    # Force the loading of jupyter-vue before dependent extensions when in a static context (embed,
    # voila)
    _jupyter_vue = Any(force_load_instance,
                       read_only=True).tag(sync=True, **widget_serialization)

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

    _view_name = Unicode('VueView').tag(sync=True)

    _view_module = Unicode('jupyter-vue').tag(sync=True)

    _model_module = Unicode('jupyter-vue').tag(sync=True)

    _view_module_version = Unicode(semver).tag(sync=True)

    _model_module_version = Unicode(semver).tag(sync=True)

    children = List(Union([Instance(DOMWidget), Unicode()],
                          default_value=None)).tag(sync=True,
                                                   **widget_serialization)

    slot = Unicode(None, allow_none=True).tag(sync=True)

    _events = List(Unicode(), default_value=None,
                   allow_none=True).tag(sync=True)

    v_model = Any('!!disabled!!', allow_none=True).tag(sync=True)

    style_ = Unicode(None, allow_none=True).tag(sync=True)

    class_ = Unicode(None, allow_none=True).tag(sync=True)
Exemplo n.º 17
0
class StructureUploadWidget(ipw.VBox):
    """Class that allows to upload structures from user's computer."""
    structure = Union([Instance(Atoms), Instance(Data)], allow_none=True)

    def __init__(self, title='', description="Upload Structure"):
        self.title = title
        self.file_upload = ipw.FileUpload(description=description,
                                          multiple=False,
                                          layout={'width': 'initial'})
        supported_formats = ipw.HTML(
            """<a href="https://wiki.fysik.dtu.dk/ase/_modules/ase/io/formats.html" target="_blank">
        Supported structure formats
        </a>""")
        self.file_upload.observe(self._on_file_upload, names='value')
        super().__init__(children=[self.file_upload, supported_formats])

    def _on_file_upload(self, change=None):
        """When file upload button is pressed."""
        for fname, item in change['new'].items():
            frmt = fname.split('.')[-1]
            if frmt == 'cif':
                self.structure = CifData(file=io.BytesIO(item['content']))
            else:
                self.structure = get_ase_from_file(io.StringIO(
                    item['content'].decode()),
                                                   format=frmt)
            self.file_upload.value.clear()
            break
class Settings(SingletonConfigurable):
    """
    Stores the settings for the registry
    """
    DEFAULT_EXTENSION_TYPES = [
        "yuuno.vs.extension.VapourSynth",
    ]

    registry_type: str = DottedObjectName("yuuno.core.registry.Registry",
                                          config=True)
    registry = Any()

    extension_types = List(Union([DottedObjectName(), Type()]), config=True)

    @observe('registry_type')
    def _reset_registry_on_reset(self, change: dict) -> None:
        self.registry = import_item(change['new'])()

    @default('registry')
    def _auto_registry(self) -> All:
        return import_item(self.registry_type)()

    @default('extension_types')
    def _auto_extension_types(self):
        return self.DEFAULT_EXTENSION_TYPES + list(discover_extensions())
Exemplo n.º 19
0
class Marker(UILayer):
    _view_name = Unicode('LeafletMarkerView').tag(sync=True)
    _model_name = Unicode('LeafletMarkerModel').tag(sync=True)

    location = List(def_loc).tag(sync=True)
    opacity = Float(1.0, min=0.0, max=1.0).tag(sync=True)
    visible = Bool(True).tag(sync=True)
    icon = Union((Instance(Icon), Instance(AwesomeIcon)),
                 allow_none=True,
                 default_value=None).tag(sync=True, **widget_serialization)

    # Options
    z_index_offset = Int(0).tag(sync=True, o=True)
    draggable = Bool(True).tag(sync=True, o=True)
    keyboard = Bool(True).tag(sync=True, o=True)
    title = Unicode('').tag(sync=True, o=True)
    alt = Unicode('').tag(sync=True, o=True)
    rise_on_hover = Bool(False).tag(sync=True, o=True)
    rise_offset = Int(250).tag(sync=True, o=True)
    rotation_angle = Float(0).tag(sync=True, o=True)
    rotation_origin = Unicode('').tag(sync=True, o=True)

    _move_callbacks = Instance(CallbackDispatcher, ())

    def __init__(self, **kwargs):
        super(Marker, self).__init__(**kwargs)
        self.on_msg(self._handle_leaflet_event)

    def _handle_leaflet_event(self, _, content, buffers):
        if content.get('event', '') == 'move':
            self._move_callbacks(**content)

    def on_move(self, callback, remove=False):
        self._move_callbacks.register_callback(callback, remove=remove)
Exemplo n.º 20
0
class PointLight(Light):
    """PointLight

    Autogenerated by generate-wrappers.js
    See https://threejs.org/docs/#api/lights/PointLight
    """
    def __init__(self,
                 color="#ffffff",
                 intensity=1,
                 distance=0,
                 decay=1,
                 **kwargs):
        kwargs['color'] = color
        kwargs['intensity'] = intensity
        kwargs['distance'] = distance
        kwargs['decay'] = decay
        super(PointLight, self).__init__(**kwargs)

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

    power = CFloat(12.566370614359172, allow_none=False).tag(sync=True)

    distance = CFloat(0, allow_none=False).tag(sync=True)

    decay = CFloat(1, allow_none=False).tag(sync=True)

    shadow = Union([
        Instance(Uninitialized),
        Instance(LightShadow),
    ],
                   default_value=UninitializedSentinel,
                   allow_none=False).tag(sync=True,
                                         **unitialized_serialization)

    type = Unicode("PointLight", allow_none=False).tag(sync=True)
Exemplo n.º 21
0
class Scene(Object3D):
    """Scene

    Autogenerated by generate-wrappers.js
    See https://threejs.org/docs/#api/scenes/Scene
    """
    def __init__(self, **kwargs):
        super(Scene, self).__init__(**kwargs)

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

    fog = Union(
        [Instance(Fog, allow_none=True),
         Instance(FogExp2, allow_none=True)]).tag(sync=True,
                                                  **widget_serialization)

    overrideMaterial = Instance(Material,
                                allow_none=True).tag(sync=True,
                                                     **widget_serialization)

    autoUpdate = Bool(True, allow_none=False).tag(sync=True)

    background = Color("#ffffff", allow_none=True).tag(sync=True)

    type = Unicode("Scene", allow_none=False).tag(sync=True)
Exemplo n.º 22
0
class ResourceUseDisplay(Configurable):
    """
    Holds server-side configuration for nbresuse
    """

    mem_warning_threshold = Float(default_value=0.1,
                                  help="""
        Warn user with flashing lights when memory usage is within this fraction
        memory limit.

        For example, if memory limit is 128MB, `mem_warning_threshold` is 0.1,
        we will start warning the user when they use (128 - (128 * 0.1)) MB.

        Set to 0 to disable warning.
        """).tag(config=True)

    mem_limit = Union(trait_types=[Int(), Callable()],
                      help="""
        Memory limit to display to the user, in bytes.
        Can also be a function which calculates the memory limit.

        Note that this does not actually limit the user's memory usage!

        Defaults to reading from the `MEM_LIMIT` environment variable. If
        set to 0, the max memory available is displayed.
        """).tag(config=True)

    @default('mem_limit')
    def _mem_limit_default(self):
        return int(os.environ.get('MEM_LIMIT', 0))

    track_cpu_percent = Bool(default_value=False,
                             help="""
        Set to True in order to enable reporting of CPU usage statistics.
        """).tag(config=True)

    cpu_warning_threshold = Float(default_value=0.1,
                                  help="""
        Warn user with flashing lights when CPU usage is within this fraction
        CPU usage limit.

        For example, if CPU limit is 150%, `cpu_warning_threshold` is 0.1,
        we will start warning the user when they use (150 - (150 * 0.1)) %.

        Set to 0 to disable warning.
        """).tag(config=True)

    cpu_limit = Float(default_value=0,
                      help="""
        CPU usage limit to display to the user.

        Note that this does not actually limit the user's CPU usage!

        Defaults to reading from the `CPU_LIMIT` environment variable. If
        set to 0, the total CPU count available is displayed.
        """).tag(config=True)

    @default('cpu_limit')
    def _cpu_limit_default(self):
        return float(os.environ.get('CPU_LIMIT', 0))
Exemplo n.º 23
0
class ContourPlot(Plot2D):
    """Represent a contour plot."""

    linecolor = Unicode('black')
    linewidth = Int(2)
    contours = Union([List(Float()), Int()], default_value=25)

    @observe('contours', 'linecolor', 'linewidth')
    def _set_need_rebuild(self, _):
        """Handle changes to attributes that need to regenerate everything."""
        # Because matplotlib doesn't let you just change these properties, we need
        # to trigger a clear and re-call of contour()
        self.clear()

    def clear_handle(self):
        """Clear the handle to the plot instance."""
        for col in self.handle.collections:
            col.remove()
        self.handle = None

    def _build(self):
        """Build the plot by calling any plotting methods as necessary."""
        x, y, imdata = self.plotdata
        self.handle = self.parent.ax.contour(
            x,
            y,
            imdata,
            self.contours,
            colors=self.linecolor,
            linewidths=self.linewidth,
            transform=imdata.metpy.cartopy_crs)
Exemplo n.º 24
0
class BeakerxComboBox(Dropdown, EasyFormComponent):
    def __init__(self, **kwargs):
        super(BeakerxComboBox, self).__init__(**kwargs)

    _view_name = Unicode('ComboBoxView').tag(sync=True)
    _model_name = Unicode('ComboBoxModel').tag(sync=True)
    _view_module = Unicode('beakerx').tag(sync=True)
    _model_module = Unicode('beakerx').tag(sync=True)
    _model_module_version = Unicode('*').tag(sync=True)
    _view_module_version = Unicode('*').tag(sync=True)
    editable = Bool(default_value=False).tag(sync=True)
    value = Any(None, allow_none=True).tag(sync=True)
    original_options = Union([List(), Dict()])
    style = None

    def _update_options_list(self, new_value):
        if new_value not in self.options:
            self.options = self.original_options[:]
            self.options += (new_value, )
            self._options_values = tuple(tuple(self.options))

    def _handle_msg(self, msg):
        if 'value' in msg['content']['data']['state']:
            value = msg['content']['data']['state']['value']
            self._update_options_list(value)
            self.value = value
        super(BeakerxComboBox, self)._handle_msg(msg)

    def set_value(self, value):
        if self.editable:
            self._update_options_list(value)
        self.value = value
Exemplo n.º 25
0
class Warp(Effect):
    """A warp effect to another block."""

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

    input = Union((Tuple(trait=Unicode, minlen=2,
                         maxlen=2), Unicode(), CFloat(0.))).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)

    @default('input')
    def _default_input(self):
        return self.parent.data[0].name
Exemplo n.º 26
0
class LightShadow(ThreeWidget):
    """LightShadow

    Autogenerated by generate-wrappers.js
    See https://threejs.org/docs/#api/lights/LightShadow
    """
    def __init__(self, camera=UninitializedSentinel, **kwargs):
        kwargs['camera'] = camera
        super(LightShadow, self).__init__(**kwargs)

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

    camera = Union([
        Instance(Uninitialized),
        Instance(Camera),
    ],
                   default_value=UninitializedSentinel,
                   allow_none=False).tag(sync=True,
                                         **unitialized_serialization)

    bias = CFloat(0, allow_none=False).tag(sync=True)

    mapSize = Vector2(default_value=[512, 512]).tag(sync=True)

    radius = CFloat(1, allow_none=False).tag(sync=True)
Exemplo n.º 27
0
class ResourceUseDisplay(Configurable):
    """
    Holds server-side configuration for nbresuse
    """

    trash_dir = Union(
        trait_types=[Unicode(), Callable()],
        default_value=os.getcwd(),
        help="""
        The directory that the notebook copies Trash to on deletion

        Defaults to reading from the `TRASH_DIR` environment variable. If
        not defined, it effectively defaults to $HOME/.local/share/Trash/
        """,
    ).tag(config=True)

    @default("trash_dir")
    def _trash_dir_default(self):
        return str(
            os.environ.get(
                "TRASH_DIR",
                os.path.join(
                    os.environ.get("HOME", os.getcwd()), ".local/share/Trash/"
                ),
            )
        )
Exemplo n.º 28
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)
     )
Exemplo n.º 29
0
class Pattern(Widget):
    """Create a Pattern.

    Args:
        image (Canvas or MultiCanvas or ipywidgets.Image): The source to be used as the pattern's image
        repetition (str): A string indicating how to repeat the pattern's image, can be "repeat" (both directions), "repeat-x" (horizontal only), "repeat-y" (vertical only), "no-repeat" (neither direction)
    """

    _model_module = Unicode(module_name).tag(sync=True)
    _model_module_version = Unicode(module_version).tag(sync=True)

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

    image = Union((Instance(Image), Instance('ipycanvas.Canvas'),
                   Instance('ipycanvas.MultiCanvas')),
                  allow_none=False,
                  read_only=True).tag(sync=True, **widget_serialization)
    repetition = Enum(['repeat', 'repeat-x', 'repeat-y', 'no-repeat'],
                      allow_none=False,
                      read_only=True).tag(sync=True)

    def __init__(self, image, repetition='repeat'):
        """Create a Pattern object given the image and the type of repetition."""
        self.set_trait('image', image)
        self.set_trait('repetition', repetition)

        super(Pattern, self).__init__()

    def _ipython_display_(self, *args, **kwargs):
        return self.image._ipython_display_(*args, **kwargs)
Exemplo n.º 30
0
class PanelContainer(HasTraits):
    """Hold multiple panels of plots."""

    size = Union(
        [Tuple(Int(), Int()), Instance(type(None))], default_value=None)
    panels = List(Instance(Panel))

    @property
    def panel(self):
        """Provide simple access for a single panel."""
        return self.panels[0]

    @panel.setter
    def panel(self, val):
        self.panels = [val]

    @observe('panels')
    def _panels_changed(self, change):
        for panel in change.new:
            panel.parent = self
            panel.observe(self.refresh, names=('_need_redraw'))

    @property
    def figure(self):
        """Provide access to the underlying figure object."""
        if not hasattr(self, '_fig'):
            self._fig = plt.figure(figsize=self.size)
        return self._fig

    def refresh(self, _):
        """Refresh the rendering of all panels."""
        # First make sure everything is properly constructed
        self.draw()

        # Trigger the graphics refresh
        self.figure.canvas.draw()

        # Flush out interactive events--only ok on Agg for newer matplotlib
        try:
            self.figure.canvas.flush_events()
        except NotImplementedError:
            pass

    def draw(self):
        """Draw the collection of panels."""
        for panel in self.panels:
            with panel.hold_trait_notifications():
                panel.draw()

    def save(self, *args, **kwargs):
        """Save the constructed graphic as an image file."""
        self.draw()
        self.figure.savefig(*args, **kwargs)

    def show(self):
        """Show the constructed graphic on the screen."""
        self.draw()
        self.figure.show()