content
stringlengths 1
103k
⌀ | path
stringlengths 8
216
| filename
stringlengths 2
179
| language
stringclasses 15
values | size_bytes
int64 2
189k
| quality_score
float64 0.5
0.95
| complexity
float64 0
1
| documentation_ratio
float64 0
1
| repository
stringclasses 5
values | stars
int64 0
1k
| created_date
stringdate 2023-07-10 19:21:08
2025-07-09 19:11:45
| license
stringclasses 4
values | is_test
bool 2
classes | file_hash
stringlengths 32
32
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Contains the DOMWidget class"""\n\nfrom traitlets import Bool, Unicode\nfrom .widget import Widget, widget_serialization\nfrom .trait_types import InstanceDict, TypedTuple\nfrom .widget_layout import Layout\nfrom .widget_style import Style\n\n\nclass DOMWidget(Widget):\n """Widget that can be inserted into the DOM\n\n Parameters\n ----------\n tooltip: str\n tooltip caption\n layout: InstanceDict(Layout)\n widget layout\n """\n\n _model_name = Unicode('DOMWidgetModel').tag(sync=True)\n _dom_classes = TypedTuple(trait=Unicode(), help="CSS classes applied to widget DOM element").tag(sync=True)\n tabbable = Bool(help="Is widget tabbable?", allow_none=True, default_value=None).tag(sync=True)\n tooltip = Unicode(None, allow_none=True, help="A tooltip caption.").tag(sync=True)\n layout = InstanceDict(Layout).tag(sync=True, **widget_serialization)\n\n def add_class(self, className):\n """\n Adds a class to the top level element of the widget.\n\n Doesn't add the class if it already exists.\n """\n if className not in self._dom_classes:\n self._dom_classes = list(self._dom_classes) + [className]\n return self\n\n def remove_class(self, className):\n """\n Removes a class from the top level element of the widget.\n\n Doesn't remove the class if it doesn't exist.\n """\n if className in self._dom_classes:\n self._dom_classes = [c for c in self._dom_classes if c != className]\n return self\n\n def focus(self):\n """\n Focus on the widget.\n """\n self.send({'do':'focus'})\n\n def blur(self):\n """\n Blur the widget.\n """\n self.send({'do':'blur'})\n\n def _repr_keys(self):\n for key in super()._repr_keys():\n # Exclude layout if it had the default value\n if key == 'layout':\n value = getattr(self, key)\n if repr(value) == '%s()' % value.__class__.__name__:\n continue\n yield key\n # We also need to include _dom_classes in repr for reproducibility\n if self._dom_classes:\n yield '_dom_classes'\n
|
.venv\Lib\site-packages\ipywidgets\widgets\domwidget.py
|
domwidget.py
|
Python
| 2,290 | 0.95 | 0.319444 | 0.067797 |
react-lib
| 356 |
2023-09-06T06:45:53.319114
|
BSD-3-Clause
| false |
46ef7832a08f0fb8286be59b10dec5c1
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom pathlib import Path\nimport sys\nimport inspect\nimport warnings\n\ndef _get_frame(level):\n """Get the frame at the given stack level."""\n # sys._getframe is much faster than inspect.stack, but isn't guaranteed to\n # exist in all python implementations, so we fall back to inspect.stack()\n\n # We need to add one to level to account for this get_frame call.\n if hasattr(sys, '_getframe'):\n frame = sys._getframe(level+1)\n else:\n frame = inspect.stack(context=0)[level+1].frame\n return frame\n\n\n# This function is from https://github.com/python/cpython/issues/67998\n# (https://bugs.python.org/file39550/deprecated_module_stacklevel.diff) and\n# calculates the appropriate stacklevel for deprecations to target the\n# deprecation for the caller, no matter how many internal stack frames we have\n# added in the process. For example, with the deprecation warning in the\n# __init__ below, the appropriate stacklevel will change depending on how deep\n# the inheritance hierarchy is.\ndef _external_stacklevel(internal):\n """Find the stacklevel of the first frame that doesn't contain any of the given internal strings\n\n The depth will be 1 at minimum in order to start checking at the caller of\n the function that called this utility method.\n """\n # Get the level of my caller's caller\n level = 2\n frame = _get_frame(level)\n\n # Normalize the path separators:\n normalized_internal = [str(Path(s)) for s in internal]\n\n # climb the stack frames while we see internal frames\n while frame and any(s in str(Path(frame.f_code.co_filename)) for s in normalized_internal):\n level +=1\n frame = frame.f_back\n\n # Return the stack level from the perspective of whoever called us (i.e., one level up)\n return level-1\n\ndef deprecation(message, internal='ipywidgets/widgets/'):\n """Generate a deprecation warning targeting the first frame that is not 'internal'\n \n internal is a string or list of strings, which if they appear in filenames in the\n frames, the frames will be considered internal. Changing this can be useful if, for examnple,\n we know that ipywidgets is calling out to traitlets internally.\n """\n if isinstance(internal, str):\n internal = [internal]\n\n # stack level of the first external frame from here\n stacklevel = _external_stacklevel(internal)\n\n # The call to .warn adds one frame, so bump the stacklevel up by one\n warnings.warn(message, DeprecationWarning, stacklevel=stacklevel+1)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\utils.py
|
utils.py
|
Python
| 2,608 | 0.95 | 0.265625 | 0.352941 |
vue-tools
| 27 |
2024-05-02T08:58:36.734867
|
GPL-3.0
| false |
2681a19f0f96c8e2beaad22f6a15ac87
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Contains the ValueWidget class"""\n\nfrom .widget import Widget\nfrom traitlets import Any\n\n\nclass ValueWidget(Widget):\n """Widget that can be used for the input of an interactive function"""\n\n value = Any(help="The value of the widget.")\n\n def get_interact_value(self):\n """Return the value for this widget which should be passed to\n interactive functions. Custom widgets can change this method\n to process the raw value ``self.value``.\n """\n return self.value\n\n def _repr_keys(self):\n # Ensure value key comes first, and is always present\n yield 'value'\n for key in super()._repr_keys():\n if key != 'value':\n yield key\n
|
.venv\Lib\site-packages\ipywidgets\widgets\valuewidget.py
|
valuewidget.py
|
Python
| 817 | 0.95 | 0.333333 | 0.15 |
awesome-app
| 446 |
2025-02-06T20:29:56.215862
|
BSD-3-Clause
| false |
3f0ee92646d39eacc6914842a5665a6f
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Bool class.\n\nRepresents a boolean using a widget.\n"""\n\nfrom .widget_description import DescriptionStyle, DescriptionWidget\nfrom .widget_core import CoreWidget\nfrom .valuewidget import ValueWidget\nfrom .widget import register, widget_serialization\nfrom .trait_types import Color, InstanceDict\nfrom traitlets import Unicode, Bool, CaselessStrEnum\n\n\n@register\nclass CheckboxStyle(DescriptionStyle, CoreWidget):\n """Checkbox widget style."""\n _model_name = Unicode('CheckboxStyleModel').tag(sync=True)\n background = Unicode(None, allow_none=True, help="Background specifications.").tag(sync=True)\n\n\n@register\nclass ToggleButtonStyle(DescriptionStyle, CoreWidget):\n """ToggleButton widget style."""\n _model_name = Unicode('ToggleButtonStyleModel').tag(sync=True)\n font_family = Unicode(None, allow_none=True, help="Toggle button text font family.").tag(sync=True)\n font_size = Unicode(None, allow_none=True, help="Toggle button text font size.").tag(sync=True)\n font_style = Unicode(None, allow_none=True, help="Toggle button text font style.").tag(sync=True)\n font_variant = Unicode(None, allow_none=True, help="Toggle button text font variant.").tag(sync=True)\n font_weight = Unicode(None, allow_none=True, help="Toggle button text font weight.").tag(sync=True)\n text_color = Color(None, allow_none=True, help="Toggle button text color").tag(sync=True)\n text_decoration = Unicode(None, allow_none=True, help="Toggle button text decoration.").tag(sync=True)\n\n\nclass _Bool(DescriptionWidget, ValueWidget, CoreWidget):\n """A base class for creating widgets that represent booleans."""\n value = Bool(False, help="Bool value").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes.").tag(sync=True)\n\n def __init__(self, value=None, **kwargs):\n if value is not None:\n kwargs['value'] = value\n super().__init__(**kwargs)\n\n _model_name = Unicode('BoolModel').tag(sync=True)\n\n\n@register\nclass Checkbox(_Bool):\n """Displays a boolean `value` in the form of a checkbox.\n\n Parameters\n ----------\n value : {True,False}\n value of the checkbox: True-checked, False-unchecked\n description : str\n description displayed next to the checkbox\n indent : {True,False}\n indent the control to align with other controls with a description. The style.description_width attribute controls this width for consistence with other controls.\n """\n _view_name = Unicode('CheckboxView').tag(sync=True)\n _model_name = Unicode('CheckboxModel').tag(sync=True)\n indent = Bool(True, help="Indent the control to align with other controls with a description.").tag(sync=True)\n style = InstanceDict(CheckboxStyle, help="Styling customizations").tag(sync=True, **widget_serialization)\n\n\n\n@register\nclass ToggleButton(_Bool):\n """Displays a boolean `value` in the form of a toggle button.\n\n Parameters\n ----------\n value : {True,False}\n value of the toggle button: True-pressed, False-unpressed\n description : str\n description displayed on the button\n icon: str\n font-awesome icon name\n style: instance of DescriptionStyle\n styling customizations\n button_style: enum\n button predefined styling\n """\n _view_name = Unicode('ToggleButtonView').tag(sync=True)\n _model_name = Unicode('ToggleButtonModel').tag(sync=True)\n\n icon = Unicode('', help= "Font-awesome icon.").tag(sync=True)\n\n button_style = CaselessStrEnum(\n values=['primary', 'success', 'info', 'warning', 'danger', ''], default_value='',\n help="""Use a predefined styling for the button.""").tag(sync=True)\n style = InstanceDict(ToggleButtonStyle, help="Styling customizations").tag(sync=True, **widget_serialization)\n\n\n@register\nclass Valid(_Bool):\n """Displays a boolean `value` in the form of a green check (True / valid)\n or a red cross (False / invalid).\n\n Parameters\n ----------\n value: {True,False}\n value of the Valid widget\n """\n readout = Unicode('Invalid', help="Message displayed when the value is False").tag(sync=True)\n _view_name = Unicode('ValidView').tag(sync=True)\n _model_name = Unicode('ValidModel').tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_bool.py
|
widget_bool.py
|
Python
| 4,328 | 0.95 | 0.118182 | 0.022989 |
react-lib
| 52 |
2024-03-01T02:22:52.125837
|
GPL-3.0
| false |
c4e18b2b073d14780d87bea8e575bf98
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Button class.\n\nRepresents a button in the frontend using a widget. Allows user to listen for\nclick events on the button and trigger backend code when the clicks are fired.\n"""\n\nfrom .utils import deprecation\nfrom .domwidget import DOMWidget\nfrom .widget import CallbackDispatcher, register, widget_serialization\nfrom .widget_core import CoreWidget\nfrom .widget_style import Style\nfrom .trait_types import Color, InstanceDict\n\nfrom traitlets import Unicode, Bool, CaselessStrEnum, Instance, validate, default\n\n\n@register\nclass ButtonStyle(Style, CoreWidget):\n """Button style widget."""\n _model_name = Unicode('ButtonStyleModel').tag(sync=True)\n button_color = Color(None, allow_none=True, help="Color of the button").tag(sync=True)\n font_family = Unicode(None, allow_none=True, help="Button text font family.").tag(sync=True)\n font_size = Unicode(None, allow_none=True, help="Button text font size.").tag(sync=True)\n font_style = Unicode(None, allow_none=True, help="Button text font style.").tag(sync=True)\n font_variant = Unicode(None, allow_none=True, help="Button text font variant.").tag(sync=True)\n font_weight = Unicode(None, allow_none=True, help="Button text font weight.").tag(sync=True)\n text_color = Unicode(None, allow_none=True, help="Button text color.").tag(sync=True)\n text_decoration = Unicode(None, allow_none=True, help="Button text decoration.").tag(sync=True)\n\n\n@register\nclass Button(DOMWidget, CoreWidget):\n """Button widget.\n\n This widget has an `on_click` method that allows you to listen for the\n user clicking on the button. The click event itself is stateless.\n\n Parameters\n ----------\n description: str\n description displayed on the button\n icon: str\n font-awesome icon names, without the 'fa-' prefix\n disabled: bool\n whether user interaction is enabled\n """\n _view_name = Unicode('ButtonView').tag(sync=True)\n _model_name = Unicode('ButtonModel').tag(sync=True)\n\n description = Unicode(help="Button label.").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes.").tag(sync=True)\n icon = Unicode('', help="Font-awesome icon names, without the 'fa-' prefix.").tag(sync=True)\n\n button_style = CaselessStrEnum(\n values=['primary', 'success', 'info', 'warning', 'danger', ''], default_value='',\n help="""Use a predefined styling for the button.""").tag(sync=True)\n\n style = InstanceDict(ButtonStyle).tag(sync=True, **widget_serialization)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._click_handlers = CallbackDispatcher()\n self.on_msg(self._handle_button_msg)\n\n @validate('icon')\n def _validate_icon(self, proposal):\n """Strip 'fa-' if necessary'"""\n value = proposal['value']\n if 'fa-' in value:\n deprecation("icons names no longer need 'fa-', "\n "just use the class names themselves (for example, 'gear spin' instead of 'fa-gear fa-spin')",\n internal=['ipywidgets/widgets/', 'traitlets/traitlets.py', '/contextlib.py'])\n value = value.replace('fa-', '')\n return value\n\n def on_click(self, callback, remove=False):\n """Register a callback to execute when the button is clicked.\n\n The callback will be called with one argument, the clicked button\n widget instance.\n\n Parameters\n ----------\n remove: bool (optional)\n Set to true to remove the callback from the list of callbacks.\n """\n self._click_handlers.register_callback(callback, remove=remove)\n\n def click(self):\n """Programmatically trigger a click event.\n\n This will call the callbacks registered to the clicked button\n widget instance.\n """\n self._click_handlers(self)\n\n def _handle_button_msg(self, _, content, buffers):\n """Handle a msg from the front-end.\n\n Parameters\n ----------\n content: dict\n Content of the msg.\n """\n if content.get('event', '') == 'click':\n self.click()\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_button.py
|
widget_button.py
|
Python
| 4,204 | 0.95 | 0.146789 | 0.022989 |
python-kit
| 369 |
2024-08-14T12:56:06.159378
|
Apache-2.0
| false |
d3166d0074f290204e6071b17c8720ab
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Color class.\n\nRepresents an HTML Color .\n"""\n\nfrom .widget_description import DescriptionWidget\nfrom .valuewidget import ValueWidget\nfrom .widget import register\nfrom .widget_core import CoreWidget\nfrom .trait_types import Color\nfrom traitlets import Unicode, Bool\n\n\n@register\nclass ColorPicker(DescriptionWidget, ValueWidget, CoreWidget):\n value = Color('black', help="The color value.").tag(sync=True)\n concise = Bool(help="Display short version with just a color selector.").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes.").tag(sync=True)\n\n _view_name = Unicode('ColorPickerView').tag(sync=True)\n _model_name = Unicode('ColorPickerModel').tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_color.py
|
widget_color.py
|
Python
| 807 | 0.95 | 0.083333 | 0.111111 |
awesome-app
| 96 |
2023-11-15T22:54:02.701356
|
BSD-3-Clause
| false |
003a665123dbd5cd962356c0772fa82d
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Controller class.\n\nRepresents a Gamepad or Joystick controller.\n"""\n\nfrom .valuewidget import ValueWidget\nfrom .widget import register, widget_serialization\nfrom .domwidget import DOMWidget\nfrom .widget_core import CoreWidget\nfrom .trait_types import TypedTuple\nfrom traitlets import Bool, Int, Float, Unicode, Instance\n\n\n@register\nclass Button(DOMWidget, ValueWidget, CoreWidget):\n """Represents a gamepad or joystick button."""\n value = Float(min=0.0, max=1.0, read_only=True, help="The value of the button.").tag(sync=True)\n pressed = Bool(read_only=True, help="Whether the button is pressed.").tag(sync=True)\n\n _view_name = Unicode('ControllerButtonView').tag(sync=True)\n _model_name = Unicode('ControllerButtonModel').tag(sync=True)\n\n\n@register\nclass Axis(DOMWidget, ValueWidget, CoreWidget):\n """Represents a gamepad or joystick axis."""\n value = Float(min=-1.0, max=1.0, read_only=True, help="The value of the axis.").tag(sync=True)\n\n _view_name = Unicode('ControllerAxisView').tag(sync=True)\n _model_name = Unicode('ControllerAxisModel').tag(sync=True)\n\n\n@register\nclass Controller(DOMWidget, CoreWidget):\n """Represents a game controller."""\n index = Int(help="The id number of the controller.").tag(sync=True)\n\n # General information about the gamepad, button and axes mapping, name.\n # These values are all read-only and set by the JavaScript side.\n name = Unicode(read_only=True, help="The name of the controller.").tag(sync=True)\n mapping = Unicode(read_only=True, help="The name of the control mapping.").tag(sync=True)\n connected = Bool(read_only=True, help="Whether the gamepad is connected.").tag(sync=True)\n timestamp = Float(read_only=True, help="The last time the data from this gamepad was updated.").tag(sync=True)\n\n # Buttons and axes - read-only\n buttons = TypedTuple(trait=Instance(Button), read_only=True, help="The buttons on the gamepad.").tag(sync=True, **widget_serialization)\n axes = TypedTuple(trait=Instance(Axis), read_only=True, help="The axes on the gamepad.").tag(sync=True, **widget_serialization)\n\n _view_name = Unicode('ControllerView').tag(sync=True)\n _model_name = Unicode('ControllerModel').tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_controller.py
|
widget_controller.py
|
Python
| 2,320 | 0.95 | 0.075472 | 0.128205 |
awesome-app
| 411 |
2023-08-16T22:37:53.134944
|
MIT
| false |
69ccc31898e86365a4c4207a00cfca8c
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Base widget class for widgets provided in Core"""\n\nfrom .widget import Widget\nfrom .._version import __jupyter_widgets_controls_version__\n\nfrom traitlets import Unicode\n\nclass CoreWidget(Widget):\n\n _model_module = Unicode('@jupyter-widgets/controls').tag(sync=True)\n _model_module_version = Unicode(__jupyter_widgets_controls_version__).tag(sync=True)\n _view_module = Unicode('@jupyter-widgets/controls').tag(sync=True)\n _view_module_version = Unicode(__jupyter_widgets_controls_version__).tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_core.py
|
widget_core.py
|
Python
| 622 | 0.95 | 0.1875 | 0.181818 |
react-lib
| 495 |
2024-03-07T21:44:11.724879
|
MIT
| false |
7937dc6bf8d721cadde1cfb667de7147
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Color class.\n\nRepresents an HTML Color .\n"""\n\nfrom .widget_description import DescriptionWidget\nfrom .valuewidget import ValueWidget\nfrom .widget import register\nfrom .widget_core import CoreWidget\nfrom .trait_types import Date, date_serialization\nfrom traitlets import Unicode, Bool, Union, CInt, CaselessStrEnum, TraitError, validate\n\n\n@register\nclass DatePicker(DescriptionWidget, ValueWidget, CoreWidget):\n """\n Display a widget for picking dates.\n\n Parameters\n ----------\n\n value: datetime.date\n The current value of the widget.\n\n disabled: bool\n Whether to disable user changes.\n\n Examples\n --------\n\n >>> import datetime\n >>> import ipywidgets as widgets\n >>> date_pick = widgets.DatePicker()\n >>> date_pick.value = datetime.date(2019, 7, 9)\n """\n\n _view_name = Unicode('DatePickerView').tag(sync=True)\n _model_name = Unicode('DatePickerModel').tag(sync=True)\n\n value = Date(None, allow_none=True).tag(sync=True, **date_serialization)\n disabled = Bool(False, help="Enable or disable user changes.").tag(sync=True)\n\n min = Date(None, allow_none=True).tag(sync=True, **date_serialization)\n max = Date(None, allow_none=True).tag(sync=True, **date_serialization)\n step = Union(\n (CInt(1), CaselessStrEnum(["any"])),\n help='The date step to use for the picker, in days, or "any".',\n ).tag(sync=True)\n\n @validate("value")\n def _validate_value(self, proposal):\n """Cap and floor value"""\n value = proposal["value"]\n if value is None:\n return value\n if self.min and self.min > value:\n value = max(value, self.min)\n if self.max and self.max < value:\n value = min(value, self.max)\n return value\n\n @validate("min")\n def _validate_min(self, proposal):\n """Enforce min <= value <= max"""\n min = proposal["value"]\n if min is None:\n return min\n if self.max and min > self.max:\n raise TraitError("Setting min > max")\n if self.value and min > self.value:\n self.value = min\n return min\n\n @validate("max")\n def _validate_max(self, proposal):\n """Enforce min <= value <= max"""\n max = proposal["value"]\n if max is None:\n return max\n if self.min and max < self.min:\n raise TraitError("setting max < min")\n if self.value and max < self.value:\n self.value = max\n return max\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_date.py
|
widget_date.py
|
Python
| 2,597 | 0.95 | 0.183908 | 0.028169 |
node-utils
| 915 |
2025-02-09T01:54:31.215732
|
Apache-2.0
| false |
40c0ee7ba04dd70afa38da24a55cf7cc
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Contains the DOMWidget class"""\n\nfrom traitlets import Bool, Unicode\nfrom .widget import Widget, widget_serialization, register\nfrom .trait_types import InstanceDict\nfrom .widget_style import Style\nfrom .widget_core import CoreWidget\nfrom .domwidget import DOMWidget\nfrom .utils import deprecation\n\nimport warnings\n\n@register\nclass DescriptionStyle(Style, CoreWidget, Widget):\n """Description style widget."""\n _model_name = Unicode('DescriptionStyleModel').tag(sync=True)\n description_width = Unicode(help="Width of the description to the side of the control.").tag(sync=True)\n\n\nclass DescriptionWidget(DOMWidget, CoreWidget):\n """Widget that has a description label to the side."""\n _model_name = Unicode('DescriptionModel').tag(sync=True)\n description = Unicode('', help="Description of the control.").tag(sync=True)\n description_allow_html = Bool(False, help="Accept HTML in the description.").tag(sync=True)\n style = InstanceDict(DescriptionStyle, help="Styling customizations").tag(sync=True, **widget_serialization)\n\n def __init__(self, *args, **kwargs):\n if 'description_tooltip' in kwargs:\n deprecation("the description_tooltip argument is deprecated, use tooltip instead")\n kwargs.setdefault('tooltip', kwargs['description_tooltip'])\n del kwargs['description_tooltip']\n super().__init__(*args, **kwargs)\n\n def _repr_keys(self):\n for key in super()._repr_keys():\n # Exclude style if it had the default value\n if key == 'style':\n value = getattr(self, key)\n if repr(value) == '%s()' % value.__class__.__name__:\n continue\n yield key\n\n @property\n def description_tooltip(self):\n """The tooltip information.\n .. deprecated :: 8.0.0\n Use tooltip attribute instead.\n """\n deprecation(".description_tooltip is deprecated, use .tooltip instead")\n return self.tooltip\n\n @description_tooltip.setter\n def description_tooltip(self, tooltip):\n deprecation(".description_tooltip is deprecated, use .tooltip instead")\n self.tooltip = tooltip\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_description.py
|
widget_description.py
|
Python
| 2,278 | 0.95 | 0.206897 | 0.0625 |
react-lib
| 597 |
2023-07-13T13:45:35.778626
|
MIT
| false |
27f30feebda50edd70bfae403717319b
|
"""Float class.\n\nRepresents an unbounded float using a widget.\n"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import (\n Instance, Unicode, CFloat, Bool, CaselessStrEnum, Tuple, TraitError, validate, default\n)\nfrom .widget_description import DescriptionWidget\nfrom .trait_types import InstanceDict, NumberFormat\nfrom .valuewidget import ValueWidget\nfrom .widget import register, widget_serialization\nfrom .widget_core import CoreWidget\nfrom .widget_int import ProgressStyle, SliderStyle\n\n\nclass _Float(DescriptionWidget, ValueWidget, CoreWidget):\n value = CFloat(0.0, help="Float value").tag(sync=True)\n\n def __init__(self, value=None, **kwargs):\n if value is not None:\n kwargs['value'] = value\n super().__init__(**kwargs)\n\n\nclass _BoundedFloat(_Float):\n max = CFloat(100.0, help="Max value").tag(sync=True)\n min = CFloat(0.0, help="Min value").tag(sync=True)\n\n @validate('value')\n def _validate_value(self, proposal):\n """Cap and floor value"""\n value = proposal['value']\n if self.min > value or self.max < value:\n value = min(max(value, self.min), self.max)\n return value\n\n @validate('min')\n def _validate_min(self, proposal):\n """Enforce min <= value <= max"""\n min = proposal['value']\n if min > self.max:\n raise TraitError('Setting min > max')\n if min > self.value:\n self.value = min\n return min\n\n @validate('max')\n def _validate_max(self, proposal):\n """Enforce min <= value <= max"""\n max = proposal['value']\n if max < self.min:\n raise TraitError('setting max < min')\n if max < self.value:\n self.value = max\n return max\n\nclass _BoundedLogFloat(_Float):\n max = CFloat(4.0, help="Max value for the exponent").tag(sync=True)\n min = CFloat(0.0, help="Min value for the exponent").tag(sync=True)\n base = CFloat(10.0, help="Base of value").tag(sync=True)\n value = CFloat(1.0, help="Float value").tag(sync=True)\n\n @validate('value')\n def _validate_value(self, proposal):\n """Cap and floor value"""\n value = proposal['value']\n if self.base ** self.min > value or self.base ** self.max < value:\n value = min(max(value, self.base ** self.min), self.base ** self.max)\n return value\n\n @validate('min')\n def _validate_min(self, proposal):\n """Enforce base ** min <= value <= base ** max"""\n min = proposal['value']\n if min > self.max:\n raise TraitError('Setting min > max')\n if self.base ** min > self.value:\n self.value = self.base ** min\n return min\n\n @validate('max')\n def _validate_max(self, proposal):\n """Enforce base ** min <= value <= base ** max"""\n max = proposal['value']\n if max < self.min:\n raise TraitError('setting max < min')\n if self.base ** max < self.value:\n self.value = self.base ** max\n return max\n\n\n@register\nclass FloatText(_Float):\n """ Displays a float value within a textbox. For a textbox in\n which the value must be within a specific range, use BoundedFloatText.\n\n Parameters\n ----------\n value : float\n value displayed\n step : float\n step of the increment (if None, any step is allowed)\n description : str\n description displayed next to the text box\n """\n _view_name = Unicode('FloatTextView').tag(sync=True)\n _model_name = Unicode('FloatTextModel').tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n continuous_update = Bool(False, help="Update the value as the user types. If False, update on submission, e.g., pressing Enter or navigating away.").tag(sync=True)\n step = CFloat(None, allow_none=True, help="Minimum step to increment the value").tag(sync=True)\n\n\n@register\nclass BoundedFloatText(_BoundedFloat):\n """ Displays a float value within a textbox. Value must be within the range specified.\n\n For a textbox in which the value doesn't need to be within a specific range, use FloatText.\n\n Parameters\n ----------\n value : float\n value displayed\n min : float\n minimal value of the range of possible values displayed\n max : float\n maximal value of the range of possible values displayed\n step : float\n step of the increment (if None, any step is allowed)\n description : str\n description displayed next to the textbox\n """\n _view_name = Unicode('FloatTextView').tag(sync=True)\n _model_name = Unicode('BoundedFloatTextModel').tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n continuous_update = Bool(False, help="Update the value as the user types. If False, update on submission, e.g., pressing Enter or navigating away.").tag(sync=True)\n step = CFloat(None, allow_none=True, help="Minimum step to increment the value").tag(sync=True)\n\n@register\nclass FloatSlider(_BoundedFloat):\n """ Slider/trackbar of floating values with the specified range.\n\n Parameters\n ----------\n value : float\n position of the slider\n min : float\n minimal position of the slider\n max : float\n maximal position of the slider\n step : float\n step of the trackbar\n description : str\n name of the slider\n orientation : {'horizontal', 'vertical'}\n default is 'horizontal', orientation of the slider\n readout : {True, False}\n default is True, display the current value of the slider next to it\n behavior : str\n slider handle and connector dragging behavior. Default is 'drag-tap'.\n readout_format : str\n default is '.2f', specifier for the format function used to represent\n slider value for human consumption, modeled after Python 3's format\n specification mini-language (PEP 3101).\n """\n _view_name = Unicode('FloatSliderView').tag(sync=True)\n _model_name = Unicode('FloatSliderModel').tag(sync=True)\n step = CFloat(0.1, allow_none=True, help="Minimum step to increment the value").tag(sync=True)\n orientation = CaselessStrEnum(values=['horizontal', 'vertical'],\n default_value='horizontal', help="Vertical or horizontal.").tag(sync=True)\n readout = Bool(True, help="Display the current value of the slider next to it.").tag(sync=True)\n readout_format = NumberFormat(\n '.2f', help="Format for the readout").tag(sync=True)\n continuous_update = Bool(True, help="Update the value of the widget as the user is holding the slider.").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n style = InstanceDict(SliderStyle).tag(sync=True, **widget_serialization)\n behavior = CaselessStrEnum(values=['drag-tap', 'drag-snap', 'tap', 'drag', 'snap'],\n default_value='drag-tap', help="Slider dragging behavior.").tag(sync=True)\n\n\n@register\nclass FloatLogSlider(_BoundedLogFloat):\n """ Slider/trackbar of logarithmic floating values with the specified range.\n\n Parameters\n ----------\n value : float\n position of the slider\n base : float\n base of the logarithmic scale. Default is 10\n min : float\n minimal position of the slider in log scale, i.e., actual minimum is base ** min\n max : float\n maximal position of the slider in log scale, i.e., actual maximum is base ** max\n step : float\n step of the trackbar, denotes steps for the exponent, not the actual value\n description : str\n name of the slider\n orientation : {'horizontal', 'vertical'}\n default is 'horizontal', orientation of the slider\n readout : {True, False}\n default is True, display the current value of the slider next to it\n behavior : str\n slider handle and connector dragging behavior. Default is 'drag-tap'.\n readout_format : str\n default is '.3g', specifier for the format function used to represent\n slider value for human consumption, modeled after Python 3's format\n specification mini-language (PEP 3101).\n """\n _view_name = Unicode('FloatLogSliderView').tag(sync=True)\n _model_name = Unicode('FloatLogSliderModel').tag(sync=True)\n step = CFloat(0.1, allow_none=True, help="Minimum step in the exponent to increment the value").tag(sync=True)\n orientation = CaselessStrEnum(values=['horizontal', 'vertical'],\n default_value='horizontal', help="Vertical or horizontal.").tag(sync=True)\n readout = Bool(True, help="Display the current value of the slider next to it.").tag(sync=True)\n readout_format = NumberFormat(\n '.3g', help="Format for the readout").tag(sync=True)\n continuous_update = Bool(True, help="Update the value of the widget as the user is holding the slider.").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n base = CFloat(10., help="Base for the logarithm").tag(sync=True)\n style = InstanceDict(SliderStyle).tag(sync=True, **widget_serialization)\n behavior = CaselessStrEnum(values=['drag-tap', 'drag-snap', 'tap', 'drag', 'snap'],\n default_value='drag-tap', help="Slider dragging behavior.").tag(sync=True)\n\n\n@register\nclass FloatProgress(_BoundedFloat):\n """ Displays a progress bar.\n\n Parameters\n -----------\n value : float\n position within the range of the progress bar\n min : float\n minimal position of the slider\n max : float\n maximal position of the slider\n description : str\n name of the progress bar\n orientation : {'horizontal', 'vertical'}\n default is 'horizontal', orientation of the progress bar\n bar_style: {'success', 'info', 'warning', 'danger', ''}\n color of the progress bar, default is '' (blue)\n colors are: 'success'-green, 'info'-light blue, 'warning'-orange, 'danger'-red\n """\n _view_name = Unicode('ProgressView').tag(sync=True)\n _model_name = Unicode('FloatProgressModel').tag(sync=True)\n orientation = CaselessStrEnum(values=['horizontal', 'vertical'],\n default_value='horizontal', help="Vertical or horizontal.").tag(sync=True)\n\n bar_style = CaselessStrEnum(\n values=['success', 'info', 'warning', 'danger', ''],\n default_value='', allow_none=True,\n help="Use a predefined styling for the progress bar.").tag(sync=True)\n\n style = InstanceDict(ProgressStyle).tag(sync=True, **widget_serialization)\n\n\nclass _FloatRange(_Float):\n value = Tuple(CFloat(), CFloat(), default_value=(0.0, 1.0),\n help="Tuple of (lower, upper) bounds").tag(sync=True)\n\n @property\n def lower(self):\n return self.value[0]\n\n @lower.setter\n def lower(self, lower):\n self.value = (lower, self.value[1])\n\n @property\n def upper(self):\n return self.value[1]\n\n @upper.setter\n def upper(self, upper):\n self.value = (self.value[0], upper)\n\n @validate('value')\n def _validate_value(self, proposal):\n lower, upper = proposal['value']\n if upper < lower:\n raise TraitError('setting lower > upper')\n return lower, upper\n\n\nclass _BoundedFloatRange(_FloatRange):\n step = CFloat(1.0, help="Minimum step that the value can take (ignored by some views)").tag(sync=True)\n max = CFloat(100.0, help="Max value").tag(sync=True)\n min = CFloat(0.0, help="Min value").tag(sync=True)\n\n def __init__(self, *args, **kwargs):\n min, max = kwargs.get('min', 0.0), kwargs.get('max', 100.0)\n if kwargs.get('value', None) is None:\n kwargs['value'] = (0.75 * min + 0.25 * max,\n 0.25 * min + 0.75 * max)\n elif not isinstance(kwargs['value'], tuple):\n try:\n kwargs['value'] = tuple(kwargs['value'])\n except:\n raise TypeError(\n "A 'range' must be able to be cast to a tuple. The input of type"\n " {} could not be cast to a tuple".format(type(kwargs['value']))\n )\n super().__init__(*args, **kwargs)\n\n @validate('min', 'max')\n def _validate_bounds(self, proposal):\n trait = proposal['trait']\n new = proposal['value']\n if trait.name == 'min' and new > self.max:\n raise TraitError('setting min > max')\n if trait.name == 'max' and new < self.min:\n raise TraitError('setting max < min')\n if trait.name == 'min':\n self.value = (max(new, self.value[0]), max(new, self.value[1]))\n if trait.name == 'max':\n self.value = (min(new, self.value[0]), min(new, self.value[1]))\n return new\n\n @validate('value')\n def _validate_value(self, proposal):\n lower, upper = super()._validate_value(proposal)\n lower, upper = min(lower, self.max), min(upper, self.max)\n lower, upper = max(lower, self.min), max(upper, self.min)\n return lower, upper\n\n\n@register\nclass FloatRangeSlider(_BoundedFloatRange):\n """ Slider/trackbar that represents a pair of floats bounded by minimum and maximum value.\n\n Parameters\n ----------\n value : float tuple\n range of the slider displayed\n min : float\n minimal position of the slider\n max : float\n maximal position of the slider\n step : float\n step of the trackbar\n description : str\n name of the slider\n orientation : {'horizontal', 'vertical'}\n default is 'horizontal'\n readout : {True, False}\n default is True, display the current value of the slider next to it\n behavior : str\n slider handle and connector dragging behavior. Default is 'drag-tap'.\n readout_format : str\n default is '.2f', specifier for the format function used to represent\n slider value for human consumption, modeled after Python 3's format\n specification mini-language (PEP 3101).\n """\n _view_name = Unicode('FloatRangeSliderView').tag(sync=True)\n _model_name = Unicode('FloatRangeSliderModel').tag(sync=True)\n step = CFloat(0.1, allow_none=True, help="Minimum step to increment the value").tag(sync=True)\n orientation = CaselessStrEnum(values=['horizontal', 'vertical'],\n default_value='horizontal', help="Vertical or horizontal.").tag(sync=True)\n readout = Bool(True, help="Display the current value of the slider next to it.").tag(sync=True)\n readout_format = NumberFormat(\n '.2f', help="Format for the readout").tag(sync=True)\n continuous_update = Bool(True, help="Update the value of the widget as the user is sliding the slider.").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n style = InstanceDict(SliderStyle).tag(sync=True, **widget_serialization)\n behavior = CaselessStrEnum(values=['drag-tap', 'drag-snap', 'tap', 'drag', 'snap'],\n default_value='drag-tap', help="Slider dragging behavior.").tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_float.py
|
widget_float.py
|
Python
| 15,028 | 0.95 | 0.172507 | 0.006173 |
node-utils
| 396 |
2024-07-27T22:29:40.989892
|
MIT
| false |
fb1551ddb00aa1e30351f5fdcea050b7
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Int class.\n\nRepresents an unbounded int using a widget.\n"""\n\nfrom .widget_description import DescriptionWidget, DescriptionStyle\nfrom .valuewidget import ValueWidget\nfrom .widget import register, widget_serialization\nfrom .widget_core import CoreWidget\nfrom traitlets import Instance\nfrom .trait_types import Color, InstanceDict, NumberFormat\nfrom traitlets import (\n Unicode, CInt, Bool, CaselessStrEnum, Tuple, TraitError, default, validate\n)\n\n_int_doc_t = """\nParameters\n----------\nvalue: integer\n The initial value.\n"""\n\n_bounded_int_doc_t = """\nParameters\n----------\nvalue: integer\n The initial value.\nmin: integer\n The lower limit for the value.\nmax: integer\n The upper limit for the value.\nstep: integer\n The step between allowed values.\nbehavior : str\n slider handle and connector dragging behavior. Default is 'drag-tap'.\n"""\n\ndef _int_doc(cls):\n """Add int docstring template to class init."""\n def __init__(self, value=None, **kwargs):\n if value is not None:\n kwargs['value'] = value\n super(cls, self).__init__(**kwargs)\n\n __init__.__doc__ = _int_doc_t\n cls.__init__ = __init__\n return cls\n\ndef _bounded_int_doc(cls):\n """Add bounded int docstring template to class init."""\n def __init__(self, value=None, min=None, max=None, step=None, **kwargs):\n if value is not None:\n kwargs['value'] = value\n if min is not None:\n kwargs['min'] = min\n if max is not None:\n kwargs['max'] = max\n if step is not None:\n kwargs['step'] = step\n super(cls, self).__init__(**kwargs)\n\n __init__.__doc__ = _bounded_int_doc_t\n cls.__init__ = __init__\n return cls\n\n\nclass _Int(DescriptionWidget, ValueWidget, CoreWidget):\n """Base class for widgets that represent an integer."""\n value = CInt(0, help="Int value").tag(sync=True)\n\n def __init__(self, value=None, **kwargs):\n if value is not None:\n kwargs['value'] = value\n super().__init__(**kwargs)\n\n\nclass _BoundedInt(_Int):\n """Base class for widgets that represent an integer bounded from above and below.\n """\n max = CInt(100, help="Max value").tag(sync=True)\n min = CInt(0, help="Min value").tag(sync=True)\n\n def __init__(self, value=None, min=None, max=None, step=None, **kwargs):\n if value is not None:\n kwargs['value'] = value\n if min is not None:\n kwargs['min'] = min\n if max is not None:\n kwargs['max'] = max\n if step is not None:\n kwargs['step'] = step\n super().__init__(**kwargs)\n\n @validate('value')\n def _validate_value(self, proposal):\n """Cap and floor value"""\n value = proposal['value']\n if self.min > value or self.max < value:\n value = min(max(value, self.min), self.max)\n return value\n\n @validate('min')\n def _validate_min(self, proposal):\n """Enforce min <= value <= max"""\n min = proposal['value']\n if min > self.max:\n raise TraitError('setting min > max')\n if min > self.value:\n self.value = min\n return min\n\n @validate('max')\n def _validate_max(self, proposal):\n """Enforce min <= value <= max"""\n max = proposal['value']\n if max < self.min:\n raise TraitError('setting max < min')\n if max < self.value:\n self.value = max\n return max\n\n@register\n@_int_doc\nclass IntText(_Int):\n """Textbox widget that represents an integer."""\n _view_name = Unicode('IntTextView').tag(sync=True)\n _model_name = Unicode('IntTextModel').tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n continuous_update = Bool(False, help="Update the value as the user types. If False, update on submission, e.g., pressing Enter or navigating away.").tag(sync=True)\n step = CInt(1, help="Minimum step to increment the value").tag(sync=True)\n\n\n@register\n@_bounded_int_doc\nclass BoundedIntText(_BoundedInt):\n """Textbox widget that represents an integer bounded from above and below.\n """\n _view_name = Unicode('IntTextView').tag(sync=True)\n _model_name = Unicode('BoundedIntTextModel').tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n continuous_update = Bool(False, help="Update the value as the user types. If False, update on submission, e.g., pressing Enter or navigating away.").tag(sync=True)\n step = CInt(1, help="Minimum step to increment the value").tag(sync=True)\n\n\n@register\nclass SliderStyle(DescriptionStyle, CoreWidget):\n """Button style widget."""\n _model_name = Unicode('SliderStyleModel').tag(sync=True)\n handle_color = Color(None, allow_none=True, help="Color of the slider handle.").tag(sync=True)\n\n\n@register\n@_bounded_int_doc\nclass IntSlider(_BoundedInt):\n """Slider widget that represents an integer bounded from above and below.\n """\n _view_name = Unicode('IntSliderView').tag(sync=True)\n _model_name = Unicode('IntSliderModel').tag(sync=True)\n step = CInt(1, help="Minimum step to increment the value").tag(sync=True)\n orientation = CaselessStrEnum(values=['horizontal', 'vertical'],\n default_value='horizontal', help="Vertical or horizontal.").tag(sync=True)\n readout = Bool(True, help="Display the current value of the slider next to it.").tag(sync=True)\n readout_format = NumberFormat(\n 'd', help="Format for the readout").tag(sync=True)\n continuous_update = Bool(True, help="Update the value of the widget as the user is holding the slider.").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n style = InstanceDict(SliderStyle).tag(sync=True, **widget_serialization)\n behavior = CaselessStrEnum(values=['drag-tap', 'drag-snap', 'tap', 'drag', 'snap'],\n default_value='drag-tap', help="Slider dragging behavior.").tag(sync=True)\n\n\n@register\nclass ProgressStyle(DescriptionStyle, CoreWidget):\n """Button style widget."""\n _model_name = Unicode('ProgressStyleModel').tag(sync=True)\n bar_color = Color(None, allow_none=True, help="Color of the progress bar.").tag(sync=True)\n\n\n@register\n@_bounded_int_doc\nclass IntProgress(_BoundedInt):\n """Progress bar that represents an integer bounded from above and below.\n """\n _view_name = Unicode('ProgressView').tag(sync=True)\n _model_name = Unicode('IntProgressModel').tag(sync=True)\n orientation = CaselessStrEnum(values=['horizontal', 'vertical'],\n default_value='horizontal', help="Vertical or horizontal.").tag(sync=True)\n\n bar_style = CaselessStrEnum(\n values=['success', 'info', 'warning', 'danger', ''], default_value='',\n help="""Use a predefined styling for the progress bar.""").tag(sync=True)\n\n style = InstanceDict(ProgressStyle).tag(sync=True, **widget_serialization)\n\n\nclass _IntRange(_Int):\n value = Tuple(CInt(), CInt(), default_value=(0, 1),\n help="Tuple of (lower, upper) bounds").tag(sync=True)\n\n @property\n def lower(self):\n return self.value[0]\n\n @lower.setter\n def lower(self, lower):\n self.value = (lower, self.value[1])\n\n @property\n def upper(self):\n return self.value[1]\n\n @upper.setter\n def upper(self, upper):\n self.value = (self.value[0], upper)\n\n @validate('value')\n def _validate_value(self, proposal):\n lower, upper = proposal['value']\n if upper < lower:\n raise TraitError('setting lower > upper')\n return lower, upper\n\n@register\nclass Play(_BoundedInt):\n """Play/repeat buttons to step through values automatically, and optionally loop.\n """\n _view_name = Unicode('PlayView').tag(sync=True)\n _model_name = Unicode('PlayModel').tag(sync=True)\n\n playing = Bool(help="Whether the control is currently playing.").tag(sync=True)\n repeat = Bool(help="Whether the control will repeat in a continuous loop.").tag(sync=True)\n\n interval = CInt(100, help="The time between two animation steps (ms).").tag(sync=True)\n step = CInt(1, help="Increment step").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n show_repeat = Bool(True, help="Show the repeat toggle button in the widget.").tag(sync=True)\n\n\nclass _BoundedIntRange(_IntRange):\n max = CInt(100, help="Max value").tag(sync=True)\n min = CInt(0, help="Min value").tag(sync=True)\n\n def __init__(self, *args, **kwargs):\n min, max = kwargs.get('min', 0), kwargs.get('max', 100)\n if kwargs.get('value', None) is None:\n kwargs['value'] = (0.75 * min + 0.25 * max,\n 0.25 * min + 0.75 * max)\n elif not isinstance(kwargs['value'], tuple):\n try:\n kwargs['value'] = tuple(kwargs['value'])\n except:\n raise TypeError(\n "A 'range' must be able to be cast to a tuple. The input of type"\n " {} could not be cast to a tuple".format(type(kwargs['value']))\n )\n super().__init__(*args, **kwargs)\n\n @validate('min', 'max')\n def _validate_bounds(self, proposal):\n trait = proposal['trait']\n new = proposal['value']\n if trait.name == 'min' and new > self.max:\n raise TraitError('setting min > max')\n if trait.name == 'max' and new < self.min:\n raise TraitError('setting max < min')\n if trait.name == 'min':\n self.value = (max(new, self.value[0]), max(new, self.value[1]))\n if trait.name == 'max':\n self.value = (min(new, self.value[0]), min(new, self.value[1]))\n return new\n\n @validate('value')\n def _validate_value(self, proposal):\n lower, upper = super()._validate_value(proposal)\n lower, upper = min(lower, self.max), min(upper, self.max)\n lower, upper = max(lower, self.min), max(upper, self.min)\n return lower, upper\n\n\n@register\nclass IntRangeSlider(_BoundedIntRange):\n """Slider/trackbar that represents a pair of ints bounded by minimum and maximum value.\n\n Parameters\n ----------\n value : int tuple\n The pair (`lower`, `upper`) of integers\n min : int\n The lowest allowed value for `lower`\n max : int\n The highest allowed value for `upper`\n step : int\n step of the trackbar\n description : str\n name of the slider\n orientation : {'horizontal', 'vertical'}\n default is 'horizontal'\n readout : {True, False}\n default is True, display the current value of the slider next to it\n behavior : str\n slider handle and connector dragging behavior. Default is 'drag-tap'.\n readout_format : str\n default is '.2f', specifier for the format function used to represent\n slider value for human consumption, modeled after Python 3's format\n specification mini-language (PEP 3101).\n """\n _view_name = Unicode('IntRangeSliderView').tag(sync=True)\n _model_name = Unicode('IntRangeSliderModel').tag(sync=True)\n step = CInt(1, help="Minimum step that the value can take").tag(sync=True)\n orientation = CaselessStrEnum(values=['horizontal', 'vertical'],\n default_value='horizontal', help="Vertical or horizontal.").tag(sync=True)\n readout = Bool(True, help="Display the current value of the slider next to it.").tag(sync=True)\n readout_format = NumberFormat(\n 'd', help="Format for the readout").tag(sync=True)\n continuous_update = Bool(True, help="Update the value of the widget as the user is sliding the slider.").tag(sync=True)\n style = InstanceDict(SliderStyle, help="Slider style customizations.").tag(sync=True, **widget_serialization)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n behavior = CaselessStrEnum(values=['drag-tap', 'drag-snap', 'tap', 'drag', 'snap'],\n default_value='drag-tap', help="Slider dragging behavior.").tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_int.py
|
widget_int.py
|
Python
| 12,125 | 0.95 | 0.21118 | 0.007326 |
react-lib
| 370 |
2024-07-09T02:12:26.050443
|
Apache-2.0
| false |
d9b61ca7916cbb19eb81a84717d3cf8d
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport mimetypes\n\nfrom .widget_core import CoreWidget\nfrom .domwidget import DOMWidget\nfrom .valuewidget import ValueWidget\nfrom .widget import register\nfrom traitlets import Unicode, CUnicode, Bool\nfrom .trait_types import CByteMemoryView\n\n\n@register\nclass _Media(DOMWidget, ValueWidget, CoreWidget):\n """Base class for Image, Audio and Video widgets.\n\n The `value` of this widget accepts a byte string. The byte string is the\n raw data that you want the browser to display.\n\n If you pass `"url"` to the `"format"` trait, `value` will be interpreted\n as a URL as bytes encoded in UTF-8.\n """\n\n # Define the custom state properties to sync with the front-end\n value = CByteMemoryView(help="The media data as a memory view of bytes.").tag(sync=True)\n\n @classmethod\n def _from_file(cls, tag, filename, **kwargs):\n """\n Create an :class:`Media` from a local file.\n\n Parameters\n ----------\n filename: str\n The location of a file to read into the value from disk.\n\n **kwargs:\n The keyword arguments for `Media`\n\n Returns an `Media` with the value set from the filename.\n """\n value = cls._load_file_value(filename)\n\n if 'format' not in kwargs:\n format = cls._guess_format(tag, filename)\n if format is not None:\n kwargs['format'] = format\n\n return cls(value=value, **kwargs)\n\n @classmethod\n def from_url(cls, url, **kwargs):\n """\n Create an :class:`Media` from a URL.\n\n :code:`Media.from_url(url)` is equivalent to:\n\n .. code-block: python\n\n med = Media(value=url, format='url')\n\n But both unicode and bytes arguments are allowed for ``url``.\n\n Parameters\n ----------\n url: [str, bytes]\n The location of a URL to load.\n """\n if isinstance(url, str):\n # If str, it needs to be encoded to bytes\n url = url.encode('utf-8')\n\n return cls(value=url, format='url', **kwargs)\n\n def set_value_from_file(self, filename):\n """\n Convenience method for reading a file into `value`.\n\n Parameters\n ----------\n filename: str\n The location of a file to read into value from disk.\n """\n value = self._load_file_value(filename)\n\n self.value = value\n\n @classmethod\n def _load_file_value(cls, filename):\n if getattr(filename, 'read', None) is not None:\n return filename.read()\n else:\n with open(filename, 'rb') as f:\n return f.read()\n\n @classmethod\n def _guess_format(cls, tag, filename):\n # file objects may have a .name parameter\n name = getattr(filename, 'name', None)\n name = name or filename\n\n try:\n mtype, _ = mimetypes.guess_type(name)\n if not mtype.startswith('{}/'.format(tag)):\n return None\n\n return mtype[len('{}/'.format(tag)):]\n except Exception:\n return None\n\n def _get_repr(self, cls):\n # Truncate the value in the repr, since it will\n # typically be very, very large.\n class_name = self.__class__.__name__\n\n # Return value first like a ValueWidget\n signature = []\n\n sig_value = 'value={!r}'.format(self.value[:40].tobytes())\n if self.value.nbytes > 40:\n sig_value = sig_value[:-1]+"..."+sig_value[-1]\n signature.append(sig_value)\n\n for key in super(cls, self)._repr_keys():\n if key == 'value':\n continue\n value = str(getattr(self, key))\n signature.append('{}={!r}'.format(key, value))\n signature = ', '.join(signature)\n return '{}({})'.format(class_name, signature)\n\n\n@register\nclass Image(_Media):\n """Displays an image as a widget.\n\n The `value` of this widget accepts a byte string. The byte string is the\n raw image data that you want the browser to display. You can explicitly\n define the format of the byte string using the `format` trait (which\n defaults to "png").\n\n If you pass `"url"` to the `"format"` trait, `value` will be interpreted\n as a URL as bytes encoded in UTF-8.\n """\n _view_name = Unicode('ImageView').tag(sync=True)\n _model_name = Unicode('ImageModel').tag(sync=True)\n\n # Define the custom state properties to sync with the front-end\n format = Unicode('png', help="The format of the image.").tag(sync=True)\n width = CUnicode(help="Width of the image in pixels. Use layout.width "\n "for styling the widget.").tag(sync=True)\n height = CUnicode(help="Height of the image in pixels. Use layout.height "\n "for styling the widget.").tag(sync=True)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n @classmethod\n def from_file(cls, filename, **kwargs):\n return cls._from_file('image', filename, **kwargs)\n\n def __repr__(self):\n return self._get_repr(Image)\n\n\n@register\nclass Video(_Media):\n """Displays a video as a widget.\n\n The `value` of this widget accepts a byte string. The byte string is the\n raw video data that you want the browser to display. You can explicitly\n define the format of the byte string using the `format` trait (which\n defaults to "mp4").\n\n If you pass `"url"` to the `"format"` trait, `value` will be interpreted\n as a URL as bytes encoded in UTF-8.\n """\n _view_name = Unicode('VideoView').tag(sync=True)\n _model_name = Unicode('VideoModel').tag(sync=True)\n\n # Define the custom state properties to sync with the front-end\n format = Unicode('mp4', help="The format of the video.").tag(sync=True)\n width = CUnicode(help="Width of the video in pixels.").tag(sync=True)\n height = CUnicode(help="Height of the video in pixels.").tag(sync=True)\n autoplay = Bool(True, help="When true, the video starts when it's displayed").tag(sync=True)\n loop = Bool(True, help="When true, the video will start from the beginning after finishing").tag(sync=True)\n controls = Bool(True, help="Specifies that video controls should be displayed (such as a play/pause button etc)").tag(sync=True)\n\n @classmethod\n def from_file(cls, filename, **kwargs):\n return cls._from_file('video', filename, **kwargs)\n\n def __repr__(self):\n return self._get_repr(Video)\n\n\n@register\nclass Audio(_Media):\n """Displays a audio as a widget.\n\n The `value` of this widget accepts a byte string. The byte string is the\n raw audio data that you want the browser to display. You can explicitly\n define the format of the byte string using the `format` trait (which\n defaults to "mp3").\n\n If you pass `"url"` to the `"format"` trait, `value` will be interpreted\n as a URL as bytes encoded in UTF-8.\n """\n _view_name = Unicode('AudioView').tag(sync=True)\n _model_name = Unicode('AudioModel').tag(sync=True)\n\n # Define the custom state properties to sync with the front-end\n format = Unicode('mp3', help="The format of the audio.").tag(sync=True)\n autoplay = Bool(True, help="When true, the audio starts when it's displayed").tag(sync=True)\n loop = Bool(True, help="When true, the audio will start from the beginning after finishing").tag(sync=True)\n controls = Bool(True, help="Specifies that audio controls should be displayed (such as a play/pause button etc)").tag(sync=True)\n\n @classmethod\n def from_file(cls, filename, **kwargs):\n return cls._from_file('audio', filename, **kwargs)\n\n def __repr__(self):\n return self._get_repr(Audio)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_media.py
|
widget_media.py
|
Python
| 7,783 | 0.95 | 0.15625 | 0.070175 |
awesome-app
| 370 |
2024-05-25T19:38:20.615750
|
Apache-2.0
| false |
81f0462dc156a392b351f2d77a12740b
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Output class.\n\nRepresents a widget that can be used to display output within the widget area.\n"""\n\nimport sys\nfrom functools import wraps\n\nfrom .domwidget import DOMWidget\nfrom .trait_types import TypedTuple\nfrom .widget import register\nfrom .._version import __jupyter_widgets_output_version__\n\nfrom traitlets import Unicode, Dict\nfrom IPython.core.interactiveshell import InteractiveShell\nfrom IPython.display import clear_output\nfrom IPython import get_ipython\nimport traceback\n\n@register\nclass Output(DOMWidget):\n """Widget used as a context manager to display output.\n\n This widget can capture and display stdout, stderr, and rich output. To use\n it, create an instance of it and display it.\n\n You can then use the widget as a context manager: any output produced while in the\n context will be captured and displayed in the widget instead of the standard output\n area.\n\n You can also use the .capture() method to decorate a function or a method. Any output\n produced by the function will then go to the output widget. This is useful for\n debugging widget callbacks, for example.\n\n Example::\n import ipywidgets as widgets\n from IPython.display import display\n out = widgets.Output()\n display(out)\n\n print('prints to output area')\n\n with out:\n print('prints to output widget')\n\n @out.capture()\n def func():\n print('prints to output widget')\n """\n _view_name = Unicode('OutputView').tag(sync=True)\n _model_name = Unicode('OutputModel').tag(sync=True)\n _view_module = Unicode('@jupyter-widgets/output').tag(sync=True)\n _model_module = Unicode('@jupyter-widgets/output').tag(sync=True)\n _view_module_version = Unicode(__jupyter_widgets_output_version__).tag(sync=True)\n _model_module_version = Unicode(__jupyter_widgets_output_version__).tag(sync=True)\n\n msg_id = Unicode('', help="Parent message id of messages to capture").tag(sync=True)\n outputs = TypedTuple(trait=Dict(), help="The output messages synced from the frontend.").tag(sync=True)\n\n __counter = 0\n\n def clear_output(self, *pargs, **kwargs):\n """\n Clear the content of the output widget.\n\n Parameters\n ----------\n\n wait: bool\n If True, wait to clear the output until new output is\n available to replace it. Default: False\n """\n with self:\n clear_output(*pargs, **kwargs)\n\n # PY3: Force passing clear_output and clear_kwargs as kwargs\n def capture(self, clear_output=False, *clear_args, **clear_kwargs):\n """\n Decorator to capture the stdout and stderr of a function.\n\n Parameters\n ----------\n\n clear_output: bool\n If True, clear the content of the output widget at every\n new function call. Default: False\n\n wait: bool\n If True, wait to clear the output until new output is\n available to replace it. This is only used if clear_output\n is also True.\n Default: False\n """\n def capture_decorator(func):\n @wraps(func)\n def inner(*args, **kwargs):\n if clear_output:\n self.clear_output(*clear_args, **clear_kwargs)\n with self:\n return func(*args, **kwargs)\n return inner\n return capture_decorator\n\n def __enter__(self):\n """Called upon entering output widget context manager."""\n self._flush()\n ip = get_ipython()\n kernel = None\n if ip and getattr(ip, "kernel", None) is not None:\n kernel = ip.kernel\n elif self.comm is not None and getattr(self.comm, 'kernel', None) is not None:\n kernel = self.comm.kernel\n\n if kernel:\n parent = None\n if hasattr(kernel, "get_parent"):\n parent = kernel.get_parent()\n elif hasattr(kernel, "_parent_header"):\n # ipykernel < 6: kernel._parent_header is the parent *request*\n parent = kernel._parent_header\n\n if parent and parent.get("header"):\n self.msg_id = parent["header"]["msg_id"]\n self.__counter += 1\n\n def __exit__(self, etype, evalue, tb):\n """Called upon exiting output widget context manager."""\n kernel = None\n if etype is not None:\n ip = get_ipython()\n if ip:\n kernel = ip\n ip.showtraceback((etype, evalue, tb), tb_offset=0)\n elif (self.comm is not None and\n getattr(self.comm, "kernel", None) is not None and\n # Check if it's ipykernel\n getattr(self.comm.kernel, "send_response", None) is not None):\n kernel = self.comm.kernel\n kernel.send_response(kernel.iopub_socket,\n u'error',\n {\n u'traceback': ["".join(traceback.format_exception(etype, evalue, tb))],\n u'evalue': repr(evalue.args),\n u'ename': etype.__name__\n })\n self._flush()\n self.__counter -= 1\n if self.__counter == 0:\n self.msg_id = ''\n # suppress exceptions when in IPython, since they are shown above,\n # otherwise let someone else handle it\n return True if kernel else None\n\n def _flush(self):\n """Flush stdout and stderr buffers."""\n sys.stdout.flush()\n sys.stderr.flush()\n\n def _append_stream_output(self, text, stream_name):\n """Append a stream output."""\n self.outputs += (\n {'output_type': 'stream', 'name': stream_name, 'text': text},\n )\n\n def append_stdout(self, text):\n """Append text to the stdout stream."""\n self._append_stream_output(text, stream_name='stdout')\n\n def append_stderr(self, text):\n """Append text to the stderr stream."""\n self._append_stream_output(text, stream_name='stderr')\n\n def append_display_data(self, display_object):\n """Append a display object as an output.\n\n Parameters\n ----------\n display_object : IPython.core.display.DisplayObject\n The object to display (e.g., an instance of\n `IPython.display.Markdown` or `IPython.display.Image`).\n """\n fmt = InteractiveShell.instance().display_formatter.format\n data, metadata = fmt(display_object)\n self.outputs += (\n {\n 'output_type': 'display_data',\n 'data': data,\n 'metadata': metadata\n },\n )\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_output.py
|
widget_output.py
|
Python
| 6,823 | 0.95 | 0.165803 | 0.043478 |
python-kit
| 771 |
2025-05-03T03:16:18.118484
|
MIT
| false |
b75a3cd1f7153c3268c6254550f9413f
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Selection classes.\n\nRepresents an enumeration using a widget.\n"""\n\nfrom collections.abc import Iterable, Mapping\nfrom itertools import chain\n\nfrom .widget_description import DescriptionWidget, DescriptionStyle\nfrom .valuewidget import ValueWidget\nfrom .widget_core import CoreWidget\nfrom .widget_style import Style\nfrom .trait_types import InstanceDict, TypedTuple\nfrom .widget import register, widget_serialization\nfrom .widget_int import SliderStyle\nfrom .docutils import doc_subst\nfrom traitlets import (Unicode, Bool, Int, Any, Dict, TraitError, CaselessStrEnum,\n Tuple, Union, observe, validate)\n\n_doc_snippets = {}\n_doc_snippets['selection_params'] = """\n options: list\n The options for the dropdown. This can either be a list of values, e.g.\n ``['Galileo', 'Brahe', 'Hubble']`` or ``[0, 1, 2]``, a list of\n (label, value) pairs, e.g.\n ``[('Galileo', 0), ('Brahe', 1), ('Hubble', 2)]``, or a Mapping between\n labels and values, e.g., ``{'Galileo': 0, 'Brahe': 1, 'Hubble': 2}``.\n\n index: int\n The index of the current selection.\n\n value: any\n The value of the current selection. When programmatically setting the\n value, a reverse lookup is performed among the options to check that\n the value is valid. The reverse lookup uses the equality operator by\n default, but another predicate may be provided via the ``equals``\n keyword argument. For example, when dealing with numpy arrays, one may\n set ``equals=np.array_equal``.\n\n label: str\n The label corresponding to the selected value.\n\n disabled: bool\n Whether to disable user changes.\n\n description: str\n Label for this input group. This should be a string\n describing the widget.\n"""\n\n_doc_snippets['multiple_selection_params'] = """\n options: dict or list\n The options for the dropdown. This can either be a list of values, e.g.\n ``['Galileo', 'Brahe', 'Hubble']`` or ``[0, 1, 2]``, or a list of\n (label, value) pairs, e.g.\n ``[('Galileo', 0), ('Brahe', 1), ('Hubble', 2)]``, or a Mapping between\n labels and values, e.g., ``{'Galileo': 0, 'Brahe': 1, 'Hubble': 2}``.\n The labels are the strings that will be displayed in the UI,\n representing the actual Python choices, and should be unique.\n\n index: iterable of int\n The indices of the options that are selected.\n\n value: iterable\n The values that are selected. When programmatically setting the\n value, a reverse lookup is performed among the options to check that\n the value is valid. The reverse lookup uses the equality operator by\n default, but another predicate may be provided via the ``equals``\n keyword argument. For example, when dealing with numpy arrays, one may\n set ``equals=np.array_equal``.\n\n label: iterable of str\n The labels corresponding to the selected value.\n\n disabled: bool\n Whether to disable user changes.\n\n description: str\n Label for this input group. This should be a string\n describing the widget.\n"""\n\n_doc_snippets['slider_params'] = """\n orientation: str\n Either ``'horizontal'`` or ``'vertical'``. Defaults to ``horizontal``.\n\n readout: bool\n Display the current label next to the slider. Defaults to ``True``.\n\n continuous_update: bool\n If ``True``, update the value of the widget continuously as the user\n holds the slider. Otherwise, the model is only updated after the\n user has released the slider. Defaults to ``True``.\n"""\n\n\ndef _exhaust_iterable(x):\n """Exhaust any non-mapping iterable into a tuple"""\n if isinstance(x, Iterable) and not isinstance(x, Mapping):\n return tuple(x)\n return x\n\n\ndef _make_options(x):\n """Standardize the options tuple format.\n\n The returned tuple should be in the format (('label', value), ('label', value), ...).\n\n The input can be\n * an iterable of (label, value) pairs\n * an iterable of values, and labels will be generated\n * a Mapping between labels and values\n """\n if isinstance(x, Mapping):\n x = x.items()\n\n # only iterate once through the options.\n xlist = tuple(x)\n\n # Check if x is an iterable of (label, value) pairs\n if all((isinstance(i, (list, tuple)) and len(i) == 2) for i in xlist):\n return tuple((str(k), v) for k, v in xlist)\n\n # Otherwise, assume x is an iterable of values\n return tuple((str(i), i) for i in xlist)\n\ndef findvalue(array, value, compare = lambda x, y: x == y):\n "A function that uses the compare function to return a value from the list."\n try:\n return next(x for x in array if compare(x, value))\n except StopIteration:\n raise ValueError('%r not in array'%value)\n\nclass _Selection(DescriptionWidget, ValueWidget, CoreWidget):\n """Base class for Selection widgets\n\n ``options`` can be specified as a list of values or a list of (label, value)\n tuples. The labels are the strings that will be displayed in the UI,\n representing the actual Python choices, and should be unique.\n If labels are not specified, they are generated from the values.\n\n When programmatically setting the value, a reverse lookup is performed\n among the options to check that the value is valid. The reverse lookup uses\n the equality operator by default, but another predicate may be provided via\n the ``equals`` keyword argument. For example, when dealing with numpy arrays,\n one may set equals=np.array_equal.\n """\n\n value = Any(None, help="Selected value", allow_none=True)\n label = Unicode(None, help="Selected label", allow_none=True)\n index = Int(None, help="Selected index", allow_none=True).tag(sync=True)\n\n options = Any((),\n help="""Iterable of values, (label, value) pairs, or Mapping between labels and values that the user can select.\n\n The labels are the strings that will be displayed in the UI, representing the\n actual Python choices, and should be unique.\n """)\n\n _options_full = None\n\n # This being read-only means that it cannot be changed by the user.\n _options_labels = TypedTuple(trait=Unicode(), read_only=True, help="The labels for the options.").tag(sync=True)\n\n disabled = Bool(help="Enable or disable user changes").tag(sync=True)\n\n def __init__(self, *args, **kwargs):\n self.equals = kwargs.pop('equals', lambda x, y: x == y)\n # We have to make the basic options bookkeeping consistent\n # so we don't have errors the first time validators run\n self._initializing_traits_ = True\n kwargs['options'] = _exhaust_iterable(kwargs.get('options', ()))\n self._options_full = _make_options(kwargs['options'])\n self._propagate_options(None)\n\n # Select the first item by default, if we can\n if 'index' not in kwargs and 'value' not in kwargs and 'label' not in kwargs:\n options = self._options_full\n nonempty = (len(options) > 0)\n kwargs['index'] = 0 if nonempty else None\n kwargs['label'], kwargs['value'] = options[0] if nonempty else (None, None)\n\n super().__init__(*args, **kwargs)\n self._initializing_traits_ = False\n\n @validate('options')\n def _validate_options(self, proposal):\n # if an iterator is provided, exhaust it\n proposal.value = _exhaust_iterable(proposal.value)\n # throws an error if there is a problem converting to full form\n self._options_full = _make_options(proposal.value)\n return proposal.value\n\n @observe('options')\n def _propagate_options(self, change):\n "Set the values and labels, and select the first option if we aren't initializing"\n options = self._options_full\n self.set_trait('_options_labels', tuple(i[0] for i in options))\n self._options_values = tuple(i[1] for i in options)\n\n if self.index is None:\n # Do nothing, we don't want to force a selection if\n # the options list changed\n return\n\n if self._initializing_traits_ is not True:\n if len(options) > 0:\n if self.index == 0:\n # Explicitly trigger the observers to pick up the new value and\n # label. Just setting the value would not trigger the observers\n # since traitlets thinks the value hasn't changed.\n self._notify_trait('index', 0, 0)\n else:\n self.index = 0\n else:\n self.index = None\n\n @validate('index')\n def _validate_index(self, proposal):\n if proposal.value is None or 0 <= proposal.value < len(self._options_labels):\n return proposal.value\n else:\n raise TraitError('Invalid selection: index out of bounds')\n\n @observe('index')\n def _propagate_index(self, change):\n "Propagate changes in index to the value and label properties"\n label = self._options_labels[change.new] if change.new is not None else None\n value = self._options_values[change.new] if change.new is not None else None\n if self.label is not label:\n self.label = label\n if self.value is not value:\n self.value = value\n\n @validate('value')\n def _validate_value(self, proposal):\n value = proposal.value\n try:\n return findvalue(self._options_values, value, self.equals) if value is not None else None\n except ValueError:\n raise TraitError('Invalid selection: value not found')\n\n @observe('value')\n def _propagate_value(self, change):\n if change.new is None:\n index = None\n elif self.index is not None and self.equals(self._options_values[self.index], change.new):\n index = self.index\n else:\n index = self._options_values.index(change.new)\n if self.index != index:\n self.index = index\n\n @validate('label')\n def _validate_label(self, proposal):\n if (proposal.value is not None) and (proposal.value not in self._options_labels):\n raise TraitError('Invalid selection: label not found')\n return proposal.value\n\n @observe('label')\n def _propagate_label(self, change):\n if change.new is None:\n index = None\n elif self.index is not None and self._options_labels[self.index] == change.new:\n index = self.index\n else:\n index = self._options_labels.index(change.new)\n if self.index != index:\n self.index = index\n\n def _repr_keys(self):\n keys = super()._repr_keys()\n # Include options manually, as it isn't marked as synced:\n for key in sorted(chain(keys, ('options',))):\n if key == 'index' and self.index == 0:\n # Index 0 is default when there are options\n continue\n yield key\n\n\nclass _MultipleSelection(DescriptionWidget, ValueWidget, CoreWidget):\n """Base class for multiple Selection widgets\n\n ``options`` can be specified as a list of values, list of (label, value)\n tuples, or a dict of {label: value}. The labels are the strings that will be\n displayed in the UI, representing the actual Python choices, and should be\n unique. If labels are not specified, they are generated from the values.\n\n When programmatically setting the value, a reverse lookup is performed\n among the options to check that the value is valid. The reverse lookup uses\n the equality operator by default, but another predicate may be provided via\n the ``equals`` keyword argument. For example, when dealing with numpy arrays,\n one may set equals=np.array_equal.\n """\n\n value = TypedTuple(trait=Any(), help="Selected values")\n label = TypedTuple(trait=Unicode(), help="Selected labels")\n index = TypedTuple(trait=Int(), help="Selected indices").tag(sync=True)\n\n options = Any((),\n help="""Iterable of values, (label, value) pairs, or Mapping between labels and values that the user can select.\n\n The labels are the strings that will be displayed in the UI, representing the\n actual Python choices, and should be unique.\n """)\n _options_full = None\n\n # This being read-only means that it cannot be changed from the frontend!\n _options_labels = TypedTuple(trait=Unicode(), read_only=True, help="The labels for the options.").tag(sync=True)\n\n disabled = Bool(help="Enable or disable user changes").tag(sync=True)\n\n def __init__(self, *args, **kwargs):\n self.equals = kwargs.pop('equals', lambda x, y: x == y)\n\n # We have to make the basic options bookkeeping consistent\n # so we don't have errors the first time validators run\n self._initializing_traits_ = True\n kwargs['options'] = _exhaust_iterable(kwargs.get('options', ()))\n self._options_full = _make_options(kwargs['options'])\n self._propagate_options(None)\n\n super().__init__(*args, **kwargs)\n self._initializing_traits_ = False\n\n @validate('options')\n def _validate_options(self, proposal):\n proposal.value = _exhaust_iterable(proposal.value)\n # throws an error if there is a problem converting to full form\n self._options_full = _make_options(proposal.value)\n return proposal.value\n\n @observe('options')\n def _propagate_options(self, change):\n "Unselect any option"\n options = self._options_full\n self.set_trait('_options_labels', tuple(i[0] for i in options))\n self._options_values = tuple(i[1] for i in options)\n if self._initializing_traits_ is not True:\n self.index = ()\n\n @validate('index')\n def _validate_index(self, proposal):\n "Check the range of each proposed index."\n if all(0 <= i < len(self._options_labels) for i in proposal.value):\n return proposal.value\n else:\n raise TraitError('Invalid selection: index out of bounds')\n\n @observe('index')\n def _propagate_index(self, change):\n "Propagate changes in index to the value and label properties"\n label = tuple(self._options_labels[i] for i in change.new)\n value = tuple(self._options_values[i] for i in change.new)\n # we check equality so we can avoid validation if possible\n if self.label != label:\n self.label = label\n if self.value != value:\n self.value = value\n\n @validate('value')\n def _validate_value(self, proposal):\n "Replace all values with the actual objects in the options list"\n try:\n return tuple(findvalue(self._options_values, i, self.equals) for i in proposal.value)\n except ValueError:\n raise TraitError('Invalid selection: value not found')\n\n @observe('value')\n def _propagate_value(self, change):\n index = tuple(self._options_values.index(i) for i in change.new)\n if self.index != index:\n self.index = index\n\n @validate('label')\n def _validate_label(self, proposal):\n if any(i not in self._options_labels for i in proposal.value):\n raise TraitError('Invalid selection: label not found')\n return proposal.value\n\n @observe('label')\n def _propagate_label(self, change):\n index = tuple(self._options_labels.index(i) for i in change.new)\n if self.index != index:\n self.index = index\n\n def _repr_keys(self):\n keys = super()._repr_keys()\n # Include options manually, as it isn't marked as synced:\n yield from sorted(chain(keys, ('options',)))\n\n\n@register\nclass ToggleButtonsStyle(DescriptionStyle, CoreWidget):\n """Button style widget.\n\n Parameters\n ----------\n button_width: str\n The width of each button. This should be a valid CSS\n width, e.g. '10px' or '5em'.\n\n font_weight: str\n The text font weight of each button, This should be a valid CSS font\n weight unit, for example 'bold' or '600'\n """\n _model_name = Unicode('ToggleButtonsStyleModel').tag(sync=True)\n button_width = Unicode(help="The width of each button.").tag(sync=True)\n font_weight = Unicode(help="Text font weight of each button.").tag(sync=True)\n\n\n@register\n@doc_subst(_doc_snippets)\nclass ToggleButtons(_Selection):\n """Group of toggle buttons that represent an enumeration.\n\n Only one toggle button can be toggled at any point in time.\n\n Parameters\n ----------\n {selection_params}\n\n tooltips: list\n Tooltip for each button. If specified, must be the\n same length as `options`.\n\n icons: list\n Icons to show on the buttons. This must be the name\n of a font-awesome icon. See `http://fontawesome.io/icons/`\n for a list of icons.\n\n button_style: str\n One of 'primary', 'success', 'info', 'warning' or\n 'danger'. Applies a predefined style to every button.\n\n style: ToggleButtonsStyle\n Style parameters for the buttons.\n """\n _view_name = Unicode('ToggleButtonsView').tag(sync=True)\n _model_name = Unicode('ToggleButtonsModel').tag(sync=True)\n\n tooltips = TypedTuple(Unicode(), help="Tooltips for each button.").tag(sync=True)\n icons = TypedTuple(Unicode(), help="Icons names for each button (FontAwesome names without the fa- prefix).").tag(sync=True)\n style = InstanceDict(ToggleButtonsStyle).tag(sync=True, **widget_serialization)\n\n button_style = CaselessStrEnum(\n values=['primary', 'success', 'info', 'warning', 'danger', ''],\n default_value='', allow_none=True, help="""Use a predefined styling for the buttons.""").tag(sync=True)\n\n\n@register\n@doc_subst(_doc_snippets)\nclass Dropdown(_Selection):\n """Allows you to select a single item from a dropdown.\n\n Parameters\n ----------\n {selection_params}\n """\n _view_name = Unicode('DropdownView').tag(sync=True)\n _model_name = Unicode('DropdownModel').tag(sync=True)\n\n\n@register\n@doc_subst(_doc_snippets)\nclass RadioButtons(_Selection):\n """Group of radio buttons that represent an enumeration.\n\n Only one radio button can be toggled at any point in time.\n\n Parameters\n ----------\n {selection_params}\n """\n _view_name = Unicode('RadioButtonsView').tag(sync=True)\n _model_name = Unicode('RadioButtonsModel').tag(sync=True)\n\n orientation = CaselessStrEnum(\n values=['horizontal', 'vertical'], default_value='vertical',\n help="Vertical or horizontal.").tag(sync=True)\n\n\n@register\n@doc_subst(_doc_snippets)\nclass Select(_Selection):\n """\n Listbox that only allows one item to be selected at any given time.\n\n Parameters\n ----------\n {selection_params}\n\n rows: int\n The number of rows to display in the widget.\n """\n _view_name = Unicode('SelectView').tag(sync=True)\n _model_name = Unicode('SelectModel').tag(sync=True)\n rows = Int(5, help="The number of rows to display.").tag(sync=True)\n\n@register\n@doc_subst(_doc_snippets)\nclass SelectMultiple(_MultipleSelection):\n """\n Listbox that allows many items to be selected at any given time.\n\n The ``value``, ``label`` and ``index`` attributes are all iterables.\n\n Parameters\n ----------\n {multiple_selection_params}\n\n rows: int\n The number of rows to display in the widget.\n """\n _view_name = Unicode('SelectMultipleView').tag(sync=True)\n _model_name = Unicode('SelectMultipleModel').tag(sync=True)\n rows = Int(5, help="The number of rows to display.").tag(sync=True)\n\n\nclass _SelectionNonempty(_Selection):\n """Selection that is guaranteed to have a value selected."""\n # don't allow None to be an option.\n value = Any(help="Selected value")\n label = Unicode(help="Selected label")\n index = Int(help="Selected index").tag(sync=True)\n\n def __init__(self, *args, **kwargs):\n if len(kwargs.get('options', ())) == 0:\n raise TraitError('options must be nonempty')\n super().__init__(*args, **kwargs)\n\n @validate('options')\n def _validate_options(self, proposal):\n proposal.value = _exhaust_iterable(proposal.value)\n self._options_full = _make_options(proposal.value)\n if len(self._options_full) == 0:\n raise TraitError("Option list must be nonempty")\n return proposal.value\n\n @validate('index')\n def _validate_index(self, proposal):\n if 0 <= proposal.value < len(self._options_labels):\n return proposal.value\n else:\n raise TraitError('Invalid selection: index out of bounds')\n\nclass _MultipleSelectionNonempty(_MultipleSelection):\n """Selection that is guaranteed to have an option available."""\n\n def __init__(self, *args, **kwargs):\n if len(kwargs.get('options', ())) == 0:\n raise TraitError('options must be nonempty')\n super().__init__(*args, **kwargs)\n\n @validate('options')\n def _validate_options(self, proposal):\n proposal.value = _exhaust_iterable(proposal.value)\n # throws an error if there is a problem converting to full form\n self._options_full = _make_options(proposal.value)\n if len(self._options_full) == 0:\n raise TraitError("Option list must be nonempty")\n return proposal.value\n\n@register\n@doc_subst(_doc_snippets)\nclass SelectionSlider(_SelectionNonempty):\n """\n Slider to select a single item from a list or dictionary.\n\n Parameters\n ----------\n {selection_params}\n\n {slider_params}\n """\n _view_name = Unicode('SelectionSliderView').tag(sync=True)\n _model_name = Unicode('SelectionSliderModel').tag(sync=True)\n\n orientation = CaselessStrEnum(\n values=['horizontal', 'vertical'], default_value='horizontal',\n help="Vertical or horizontal.").tag(sync=True)\n readout = Bool(True,\n help="Display the current selected label next to the slider").tag(sync=True)\n continuous_update = Bool(True,\n help="Update the value of the widget as the user is holding the slider.").tag(sync=True)\n behavior = CaselessStrEnum(values=['drag-tap', 'drag-snap', 'tap', 'drag', 'snap'],\n default_value='drag-tap', help="Slider dragging behavior.").tag(sync=True)\n\n style = InstanceDict(SliderStyle).tag(sync=True, **widget_serialization)\n\n\n@register\n@doc_subst(_doc_snippets)\nclass SelectionRangeSlider(_MultipleSelectionNonempty):\n """\n Slider to select multiple contiguous items from a list.\n\n The index, value, and label attributes contain the start and end of\n the selection range, not all items in the range.\n\n Parameters\n ----------\n {multiple_selection_params}\n\n {slider_params}\n """\n _view_name = Unicode('SelectionRangeSliderView').tag(sync=True)\n _model_name = Unicode('SelectionRangeSliderModel').tag(sync=True)\n\n value = Tuple(help="Min and max selected values")\n label = Tuple(help="Min and max selected labels")\n index = Tuple((0,0), help="Min and max selected indices").tag(sync=True)\n\n @observe('options')\n def _propagate_options(self, change):\n "Select the first range"\n options = self._options_full\n self.set_trait('_options_labels', tuple(i[0] for i in options))\n self._options_values = tuple(i[1] for i in options)\n if self._initializing_traits_ is not True:\n self.index = (0, 0)\n\n @validate('index')\n def _validate_index(self, proposal):\n "Make sure we have two indices and check the range of each proposed index."\n if len(proposal.value) != 2:\n raise TraitError('Invalid selection: index must have two values, but is %r'%(proposal.value,))\n if all(0 <= i < len(self._options_labels) for i in proposal.value):\n return proposal.value\n else:\n raise TraitError('Invalid selection: index out of bounds: %s'%(proposal.value,))\n\n orientation = CaselessStrEnum(\n values=['horizontal', 'vertical'], default_value='horizontal',\n help="Vertical or horizontal.").tag(sync=True)\n readout = Bool(True,\n help="Display the current selected label next to the slider").tag(sync=True)\n continuous_update = Bool(True,\n help="Update the value of the widget as the user is holding the slider.").tag(sync=True)\n\n style = InstanceDict(SliderStyle).tag(sync=True, **widget_serialization)\n behavior = CaselessStrEnum(values=['drag-tap', 'drag-snap', 'tap', 'drag', 'snap'],\n default_value='drag-tap', help="Slider dragging behavior.").tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_selection.py
|
widget_selection.py
|
Python
| 24,617 | 0.95 | 0.201238 | 0.055769 |
python-kit
| 413 |
2023-07-13T22:35:01.147584
|
Apache-2.0
| false |
0c419b43033084d3c4ce6642d2f69d25
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""SelectionContainer class.\n\nRepresents a multipage container that can be used to group other widgets into\npages.\n"""\n\nfrom .widget_box import Box\nfrom .widget import register\nfrom .widget_core import CoreWidget\nfrom traitlets import Unicode, Dict, CInt, TraitError, validate, observe\nfrom .trait_types import TypedTuple\nfrom itertools import chain, repeat, islice\n\n# Inspired by an itertools recipe: https://docs.python.org/3/library/itertools.html#itertools-recipes\ndef pad(iterable, padding=None, length=None):\n """Returns the sequence elements and then returns None up to the given size (or indefinitely if size is None)."""\n return islice(chain(iterable, repeat(padding)), length)\n\nclass _SelectionContainer(Box, CoreWidget):\n """Base class used to display multiple child widgets."""\n titles = TypedTuple(trait=Unicode(), help="Titles of the pages").tag(sync=True)\n selected_index = CInt(\n help="""The index of the selected page. This is either an integer selecting a particular sub-widget, or None to have no widgets selected.""",\n allow_none=True,\n default_value=None\n ).tag(sync=True)\n\n @validate('selected_index')\n def _validated_index(self, proposal):\n if proposal.value is None or 0 <= proposal.value < len(self.children):\n return proposal.value\n else:\n raise TraitError('Invalid selection: index out of bounds')\n\n @validate('titles')\n def _validate_titles(self, proposal):\n return tuple(pad(proposal.value, '', len(self.children)))\n\n @observe('children')\n def _observe_children(self, change):\n self._reset_selected_index()\n self._reset_titles()\n\n def _reset_selected_index(self):\n if self.selected_index is not None and len(self.children) < self.selected_index:\n self.selected_index = None\n\n def _reset_titles(self):\n if len(self.titles) != len(self.children):\n # Run validation function\n self.titles = tuple(self.titles)\n\n def set_title(self, index, title):\n """Sets the title of a container page.\n Parameters\n ----------\n index : int\n Index of the container page\n title : unicode\n New title\n """\n titles = list(self.titles)\n # for backwards compatibility with ipywidgets 7.x\n if title is None:\n title = ''\n titles[index]=title\n self.titles = tuple(titles)\n\n def get_title(self, index):\n """Gets the title of a container page.\n Parameters\n ----------\n index : int\n Index of the container page\n """\n return self.titles[index]\n\n@register\nclass Accordion(_SelectionContainer):\n """Displays children each on a separate accordion page."""\n _view_name = Unicode('AccordionView').tag(sync=True)\n _model_name = Unicode('AccordionModel').tag(sync=True)\n\n\n@register\nclass Tab(_SelectionContainer):\n """Displays children each on a separate accordion tab."""\n _view_name = Unicode('TabView').tag(sync=True)\n _model_name = Unicode('TabModel').tag(sync=True)\n\n def __init__(self, children=(), **kwargs):\n if len(children) > 0 and 'selected_index' not in kwargs:\n kwargs['selected_index'] = 0\n super().__init__(children=children, **kwargs)\n\n def _reset_selected_index(self):\n # if there are no tabs, then none should be selected\n num_children = len(self.children)\n if num_children == 0:\n self.selected_index = None\n\n # if there are tabs, but none is selected, select the first one\n elif self.selected_index == None:\n self.selected_index = 0\n\n # if there are tabs and a selection, but the selection is no longer\n # valid, select the last tab.\n elif num_children < self.selected_index:\n self.selected_index = num_children - 1\n\n\n\n@register\nclass Stack(_SelectionContainer):\n """Displays only the selected child."""\n _view_name = Unicode('StackView').tag(sync=True)\n _model_name = Unicode('StackModel').tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_selectioncontainer.py
|
widget_selectioncontainer.py
|
Python
| 4,198 | 0.95 | 0.233333 | 0.091837 |
awesome-app
| 724 |
2024-01-22T01:21:05.406793
|
Apache-2.0
| false |
c41eafcba1de3d594b7d47eccddaeab3
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""String class.\n\nRepresents a unicode string using a widget.\n"""\n\nfrom .widget_description import DescriptionStyle, DescriptionWidget\nfrom .valuewidget import ValueWidget\nfrom .widget import CallbackDispatcher, register, widget_serialization\nfrom .widget_core import CoreWidget\nfrom .trait_types import Color, InstanceDict, TypedTuple\nfrom .utils import deprecation\nfrom traitlets import Unicode, Bool, Int\n\n\nclass _StringStyle(DescriptionStyle, CoreWidget):\n """Text input style widget."""\n _model_name = Unicode('StringStyleModel').tag(sync=True)\n background = Unicode(None, allow_none=True, help="Background specifications.").tag(sync=True)\n font_size = Unicode(None, allow_none=True, help="Text font size.").tag(sync=True)\n text_color = Color(None, allow_none=True, help="Text color").tag(sync=True)\n\n\n@register\nclass LabelStyle(_StringStyle):\n """Label style widget."""\n _model_name = Unicode('LabelStyleModel').tag(sync=True)\n font_family = Unicode(None, allow_none=True, help="Label text font family.").tag(sync=True)\n font_style = Unicode(None, allow_none=True, help="Label text font style.").tag(sync=True)\n font_variant = Unicode(None, allow_none=True, help="Label text font variant.").tag(sync=True)\n font_weight = Unicode(None, allow_none=True, help="Label text font weight.").tag(sync=True)\n text_decoration = Unicode(None, allow_none=True, help="Label text decoration.").tag(sync=True)\n\n\n@register\nclass TextStyle(_StringStyle):\n """Text input style widget."""\n _model_name = Unicode('TextStyleModel').tag(sync=True)\n\n@register\nclass HTMLStyle(_StringStyle):\n """HTML style widget."""\n _model_name = Unicode('HTMLStyleModel').tag(sync=True)\n\n@register\nclass HTMLMathStyle(_StringStyle):\n """HTML with math style widget."""\n _model_name = Unicode('HTMLMathStyleModel').tag(sync=True)\n\n\nclass _String(DescriptionWidget, ValueWidget, CoreWidget):\n """Base class used to create widgets that represent a string."""\n\n value = Unicode(help="String value").tag(sync=True)\n\n # We set a zero-width space as a default placeholder to make sure the baseline matches\n # the text, not the bottom margin. See the last paragraph of\n # https://www.w3.org/TR/CSS2/visudet.html#leading\n placeholder = Unicode('\u200b', help="Placeholder text to display when nothing has been typed").tag(sync=True)\n style = InstanceDict(_StringStyle).tag(sync=True, **widget_serialization)\n\n def __init__(self, value=None, **kwargs):\n if value is not None:\n kwargs['value'] = value\n super().__init__(**kwargs)\n\n _model_name = Unicode('StringModel').tag(sync=True)\n\n@register\nclass HTML(_String):\n """Renders the string `value` as HTML."""\n _view_name = Unicode('HTMLView').tag(sync=True)\n _model_name = Unicode('HTMLModel').tag(sync=True)\n style = InstanceDict(HTMLStyle).tag(sync=True, **widget_serialization)\n\n@register\nclass HTMLMath(_String):\n """Renders the string `value` as HTML, and render mathematics."""\n _view_name = Unicode('HTMLMathView').tag(sync=True)\n _model_name = Unicode('HTMLMathModel').tag(sync=True)\n style = InstanceDict(HTMLMathStyle).tag(sync=True, **widget_serialization)\n\n\n@register\nclass Label(_String):\n """Label widget.\n\n It also renders math inside the string `value` as Latex (requires $ $ or\n $$ $$ and similar latex tags).\n """\n _view_name = Unicode('LabelView').tag(sync=True)\n _model_name = Unicode('LabelModel').tag(sync=True)\n style = InstanceDict(LabelStyle).tag(sync=True, **widget_serialization)\n\n\n@register\nclass Textarea(_String):\n """Multiline text area widget."""\n _view_name = Unicode('TextareaView').tag(sync=True)\n _model_name = Unicode('TextareaModel').tag(sync=True)\n rows = Int(None, allow_none=True, help="The number of rows to display.").tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n continuous_update = Bool(True, help="Update the value as the user types. If False, update on submission, e.g., pressing Enter or navigating away.").tag(sync=True)\n style = InstanceDict(TextStyle).tag(sync=True, **widget_serialization)\n\n@register\nclass Text(_String):\n """Single line textbox widget."""\n _view_name = Unicode('TextView').tag(sync=True)\n _model_name = Unicode('TextModel').tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n continuous_update = Bool(True, help="Update the value as the user types. If False, update on submission, e.g., pressing Enter or navigating away.").tag(sync=True)\n style = InstanceDict(TextStyle).tag(sync=True, **widget_serialization)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._submission_callbacks = CallbackDispatcher()\n self.on_msg(self._handle_string_msg)\n\n def _handle_string_msg(self, _, content, buffers):\n """Handle a msg from the front-end.\n\n Parameters\n ----------\n content: dict\n Content of the msg.\n """\n if content.get('event', '') == 'submit':\n self._submission_callbacks(self)\n\n def on_submit(self, callback, remove=False):\n """(Un)Register a callback to handle text submission.\n\n Triggered when the user clicks enter.\n\n Parameters\n ----------\n callback: callable\n Will be called with exactly one argument: the Widget instance\n remove: bool (optional)\n Whether to unregister the callback\n """\n deprecation("on_submit is deprecated. Instead, set the .continuous_update attribute to False and observe the value changing with: mywidget.observe(callback, 'value').")\n self._submission_callbacks.register_callback(callback, remove=remove)\n\n\n@register\nclass Password(Text):\n """Single line textbox widget."""\n _view_name = Unicode('PasswordView').tag(sync=True)\n _model_name = Unicode('PasswordModel').tag(sync=True)\n disabled = Bool(False, help="Enable or disable user changes").tag(sync=True)\n\n def _repr_keys(self):\n # Don't include password value in repr!\n super_keys = super()._repr_keys()\n for key in super_keys:\n if key != 'value':\n yield key\n\n\n@register\nclass Combobox(Text):\n """Single line textbox widget with a dropdown and autocompletion.\n """\n _model_name = Unicode('ComboboxModel').tag(sync=True)\n _view_name = Unicode('ComboboxView').tag(sync=True)\n\n options = TypedTuple(\n trait=Unicode(),\n help="Dropdown options for the combobox"\n ).tag(sync=True)\n\n ensure_option = Bool(\n False,\n help='If set, ensure value is in options. Implies continuous_update=False.'\n ).tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_string.py
|
widget_string.py
|
Python
| 6,869 | 0.95 | 0.139665 | 0.042553 |
awesome-app
| 162 |
2023-09-18T04:25:37.131705
|
GPL-3.0
| false |
e2019db113bb9f3ad0f070247bc76d02
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Contains the Style class"""\n\nfrom traitlets import Unicode\nfrom .widget import Widget\nfrom .._version import __jupyter_widgets_base_version__\n\nclass Style(Widget):\n """Style specification"""\n\n _model_name = Unicode('StyleModel').tag(sync=True)\n _view_name = Unicode('StyleView').tag(sync=True)\n _view_module = Unicode('@jupyter-widgets/base').tag(sync=True)\n _view_module_version = Unicode(__jupyter_widgets_base_version__).tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_style.py
|
widget_style.py
|
Python
| 559 | 0.95 | 0.125 | 0.166667 |
python-kit
| 334 |
2023-09-18T20:03:05.866001
|
Apache-2.0
| false |
9f80fa4c948840bc42fd275a6ef66787
|
# Copyright(c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""TagsInput class.\n\nRepresents a list of tags.\n"""\n\nfrom traitlets import (\n CaselessStrEnum, CInt, CFloat, Bool, Unicode, List, TraitError, validate\n)\n\nfrom .widget_description import DescriptionWidget\nfrom .valuewidget import ValueWidget\nfrom .widget_core import CoreWidget\nfrom .widget import register\nfrom .trait_types import Color, NumberFormat\n\n\nclass TagsInputBase(DescriptionWidget, ValueWidget, CoreWidget):\n _model_name = Unicode('TagsInputBaseModel').tag(sync=True)\n value = List().tag(sync=True)\n placeholder = Unicode('\u200b').tag(sync=True)\n allowed_tags = List().tag(sync=True)\n allow_duplicates = Bool(True).tag(sync=True)\n\n @validate('value')\n def _validate_value(self, proposal):\n if ('' in proposal['value']):\n raise TraitError('The value of a TagsInput widget cannot contain blank strings')\n\n if len(self.allowed_tags) == 0:\n return proposal['value']\n\n for tag_value in proposal['value']:\n if tag_value not in self.allowed_tags:\n raise TraitError('Tag value {} is not allowed, allowed tags are {}'.format(tag_value, self.allowed_tags))\n\n return proposal['value']\n\n\n@register\nclass TagsInput(TagsInputBase):\n """\n List of string tags\n """\n _model_name = Unicode('TagsInputModel').tag(sync=True)\n _view_name = Unicode('TagsInputView').tag(sync=True)\n\n value = List(Unicode(), help='List of string tags').tag(sync=True)\n tag_style = CaselessStrEnum(\n values=['primary', 'success', 'info', 'warning', 'danger', ''], default_value='',\n help="""Use a predefined styling for the tags.""").tag(sync=True)\n\n\n@register\nclass ColorsInput(TagsInputBase):\n """\n List of color tags\n """\n _model_name = Unicode('ColorsInputModel').tag(sync=True)\n _view_name = Unicode('ColorsInputView').tag(sync=True)\n\n value = List(Color(), help='List of string tags').tag(sync=True)\n\n\nclass NumbersInputBase(TagsInput):\n _model_name = Unicode('NumbersInputBaseModel').tag(sync=True)\n min = CFloat(default_value=None, allow_none=True).tag(sync=True)\n max = CFloat(default_value=None, allow_none=True).tag(sync=True)\n\n @validate('value')\n def _validate_numbers(self, proposal):\n for tag_value in proposal['value']:\n if self.min is not None and tag_value < self.min:\n raise TraitError('Tag value {} should be >= {}'.format(tag_value, self.min))\n if self.max is not None and tag_value > self.max:\n raise TraitError('Tag value {} should be <= {}'.format(tag_value, self.max))\n\n return proposal['value']\n\n\n@register\nclass FloatsInput(NumbersInputBase):\n """\n List of float tags\n """\n _model_name = Unicode('FloatsInputModel').tag(sync=True)\n _view_name = Unicode('FloatsInputView').tag(sync=True)\n\n value = List(CFloat(), help='List of float tags').tag(sync=True)\n format = NumberFormat('.1f').tag(sync=True)\n\n\n@register\nclass IntsInput(NumbersInputBase):\n """\n List of int tags\n """\n _model_name = Unicode('IntsInputModel').tag(sync=True)\n _view_name = Unicode('IntsInputView').tag(sync=True)\n\n value = List(CInt(), help='List of int tags').tag(sync=True)\n format = NumberFormat('d').tag(sync=True)\n min = CInt(default_value=None, allow_none=True).tag(sync=True)\n max = CInt(default_value=None, allow_none=True).tag(sync=True)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_tagsinput.py
|
widget_tagsinput.py
|
Python
| 3,498 | 0.95 | 0.160377 | 0.025 |
awesome-app
| 699 |
2024-11-25T13:41:13.071476
|
Apache-2.0
| false |
b344b9b3c1fd4ba734ae5984425b1a61
|
"""Implement common widgets layouts as reusable components"""\n\nimport re\nfrom collections import defaultdict\n\nfrom traitlets import Instance, Bool, Unicode, CUnicode, CaselessStrEnum, Tuple\nfrom traitlets import Integer\nfrom traitlets import HasTraits, TraitError\nfrom traitlets import observe, validate\n\nfrom .widget import Widget\nfrom .widget_box import GridBox\n\nfrom .docutils import doc_subst\n\n\n_doc_snippets = {\n 'style_params' : """\n\n grid_gap : str\n CSS attribute used to set the gap between the grid cells\n\n justify_content : str, in ['flex-start', 'flex-end', 'center', 'space-between', 'space-around']\n CSS attribute used to align widgets vertically\n\n align_items : str, in ['top', 'bottom', 'center', 'flex-start', 'flex-end', 'baseline', 'stretch']\n CSS attribute used to align widgets horizontally\n\n width : str\n height : str\n width and height"""\n }\n\n@doc_subst(_doc_snippets)\nclass LayoutProperties(HasTraits):\n """Mixin class for layout templates\n\n This class handles mainly style attributes (height, grid_gap etc.)\n\n Parameters\n ----------\n\n {style_params}\n\n\n Note\n ----\n\n This class is only meant to be used in inheritance as mixin with other\n classes. It will not work, unless `self.layout` attribute is defined.\n\n """\n\n # style attributes (passed to Layout)\n grid_gap = Unicode(\n None,\n allow_none=True,\n help="The grid-gap CSS attribute.")\n justify_content = CaselessStrEnum(\n ['flex-start', 'flex-end', 'center',\n 'space-between', 'space-around'],\n allow_none=True,\n help="The justify-content CSS attribute.")\n align_items = CaselessStrEnum(\n ['top', 'bottom',\n 'flex-start', 'flex-end', 'center',\n 'baseline', 'stretch'],\n allow_none=True, help="The align-items CSS attribute.")\n width = Unicode(\n None,\n allow_none=True,\n help="The width CSS attribute.")\n height = Unicode(\n None,\n allow_none=True,\n help="The width CSS attribute.")\n\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._property_rewrite = defaultdict(dict)\n self._property_rewrite['align_items'] = {'top': 'flex-start',\n 'bottom': 'flex-end'}\n self._copy_layout_props()\n self._set_observers()\n\n def _delegate_to_layout(self, change):\n "delegate the trait types to their counterparts in self.layout"\n value, name = change['new'], change['name']\n value = self._property_rewrite[name].get(value, value)\n setattr(self.layout, name, value) # pylint: disable=no-member\n\n def _set_observers(self):\n "set observers on all layout properties defined in this class"\n _props = LayoutProperties.class_trait_names()\n self.observe(self._delegate_to_layout, _props)\n\n def _copy_layout_props(self):\n\n _props = LayoutProperties.class_trait_names()\n\n for prop in _props:\n value = getattr(self, prop)\n if value:\n value = self._property_rewrite[prop].get(value, value)\n setattr(self.layout, prop, value) #pylint: disable=no-member\n\n@doc_subst(_doc_snippets)\nclass AppLayout(GridBox, LayoutProperties):\n """ Define an application like layout of widgets.\n\n Parameters\n ----------\n\n header: instance of Widget\n left_sidebar: instance of Widget\n center: instance of Widget\n right_sidebar: instance of Widget\n footer: instance of Widget\n widgets to fill the positions in the layout\n\n merge: bool\n flag to say whether the empty positions should be automatically merged\n\n pane_widths: list of numbers/strings\n the fraction of the total layout width each of the central panes should occupy\n (left_sidebar,\n center, right_sidebar)\n\n pane_heights: list of numbers/strings\n the fraction of the width the vertical space that the panes should occupy\n (left_sidebar, center, right_sidebar)\n\n {style_params}\n\n Examples\n --------\n\n """\n\n # widget positions\n header = Instance(Widget, allow_none=True)\n footer = Instance(Widget, allow_none=True)\n left_sidebar = Instance(Widget, allow_none=True)\n right_sidebar = Instance(Widget, allow_none=True)\n center = Instance(Widget, allow_none=True)\n\n # extra args\n pane_widths = Tuple(CUnicode(), CUnicode(), CUnicode(),\n default_value=['1fr', '2fr', '1fr'])\n pane_heights = Tuple(CUnicode(), CUnicode(), CUnicode(),\n default_value=['1fr', '3fr', '1fr'])\n\n merge = Bool(default_value=True)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._update_layout()\n\n @staticmethod\n def _size_to_css(size):\n if re.match(r'\d+\.?\d*(px|fr|%)$', size):\n return size\n if re.match(r'\d+\.?\d*$', size):\n return size + 'fr'\n\n raise TypeError("the pane sizes must be in one of the following formats: "\n "'10px', '10fr', 10 (will be converted to '10fr')."\n "Got '{}'".format(size))\n\n def _convert_sizes(self, size_list):\n return list(map(self._size_to_css, size_list))\n\n def _update_layout(self):\n\n grid_template_areas = [["header", "header", "header"],\n ["left-sidebar", "center", "right-sidebar"],\n ["footer", "footer", "footer"]]\n\n grid_template_columns = self._convert_sizes(self.pane_widths)\n grid_template_rows = self._convert_sizes(self.pane_heights)\n\n all_children = {'header': self.header,\n 'footer': self.footer,\n 'left-sidebar': self.left_sidebar,\n 'right-sidebar': self.right_sidebar,\n 'center': self.center}\n\n children = {position : child\n for position, child in all_children.items()\n if child is not None}\n\n if not children:\n return\n\n for position, child in children.items():\n child.layout.grid_area = position\n\n if self.merge:\n\n if len(children) == 1:\n position = list(children.keys())[0]\n grid_template_areas = [[position, position, position],\n [position, position, position],\n [position, position, position]]\n\n else:\n if self.center is None:\n for row in grid_template_areas:\n del row[1]\n del grid_template_columns[1]\n\n if self.left_sidebar is None:\n grid_template_areas[1][0] = grid_template_areas[1][1]\n\n if self.right_sidebar is None:\n grid_template_areas[1][-1] = grid_template_areas[1][-2]\n\n if (self.left_sidebar is None and\n self.right_sidebar is None and\n self.center is None):\n grid_template_areas = [['header'], ['footer']]\n grid_template_columns = ['1fr']\n grid_template_rows = ['1fr', '1fr']\n\n if self.header is None:\n del grid_template_areas[0]\n del grid_template_rows[0]\n\n if self.footer is None:\n del grid_template_areas[-1]\n del grid_template_rows[-1]\n\n\n grid_template_areas_css = "\n".join('"{}"'.format(" ".join(line))\n for line in grid_template_areas)\n\n self.layout.grid_template_columns = " ".join(grid_template_columns)\n self.layout.grid_template_rows = " ".join(grid_template_rows)\n self.layout.grid_template_areas = grid_template_areas_css\n\n self.children = tuple(children.values())\n\n @observe("footer", "header", "center", "left_sidebar", "right_sidebar", "merge",\n "pane_widths", "pane_heights")\n def _child_changed(self, change): #pylint: disable=unused-argument\n self._update_layout()\n\n\n@doc_subst(_doc_snippets)\nclass GridspecLayout(GridBox, LayoutProperties):\n """ Define a N by M grid layout\n\n Parameters\n ----------\n\n n_rows : int\n number of rows in the grid\n\n n_columns : int\n number of columns in the grid\n\n {style_params}\n\n Examples\n --------\n\n >>> from ipywidgets import GridspecLayout, Button, Layout\n >>> layout = GridspecLayout(n_rows=4, n_columns=2, height='200px')\n >>> layout[:3, 0] = Button(layout=Layout(height='auto', width='auto'))\n >>> layout[1:, 1] = Button(layout=Layout(height='auto', width='auto'))\n >>> layout[-1, 0] = Button(layout=Layout(height='auto', width='auto'))\n >>> layout[0, 1] = Button(layout=Layout(height='auto', width='auto'))\n >>> layout\n """\n\n n_rows = Integer()\n n_columns = Integer()\n\n def __init__(self, n_rows=None, n_columns=None, **kwargs):\n super().__init__(**kwargs)\n self.n_rows = n_rows\n self.n_columns = n_columns\n self._grid_template_areas = [['.'] * self.n_columns for i in range(self.n_rows)]\n\n self._grid_template_rows = 'repeat(%d, 1fr)' % (self.n_rows,)\n self._grid_template_columns = 'repeat(%d, 1fr)' % (self.n_columns,)\n self._children = {}\n self._id_count = 0\n\n @validate('n_rows', 'n_columns')\n def _validate_integer(self, proposal):\n if proposal['value'] > 0:\n return proposal['value']\n raise TraitError('n_rows and n_columns must be positive integer')\n\n def _get_indices_from_slice(self, row, column):\n "convert a two-dimensional slice to a list of rows and column indices"\n\n if isinstance(row, slice):\n start, stop, stride = row.indices(self.n_rows)\n rows = range(start, stop, stride)\n else:\n rows = [row]\n\n if isinstance(column, slice):\n start, stop, stride = column.indices(self.n_columns)\n columns = range(start, stop, stride)\n else:\n columns = [column]\n\n return rows, columns\n\n def __setitem__(self, key, value):\n row, column = key\n self._id_count += 1\n obj_id = 'widget%03d' % self._id_count\n value.layout.grid_area = obj_id\n\n rows, columns = self._get_indices_from_slice(row, column)\n\n for row in rows:\n for column in columns:\n current_value = self._grid_template_areas[row][column]\n if current_value != '.' and current_value in self._children:\n del self._children[current_value]\n self._grid_template_areas[row][column] = obj_id\n\n self._children[obj_id] = value\n self._update_layout()\n\n def __getitem__(self, key):\n rows, columns = self._get_indices_from_slice(*key)\n\n obj_id = None\n for row in rows:\n for column in columns:\n new_obj_id = self._grid_template_areas[row][column]\n obj_id = obj_id or new_obj_id\n if obj_id != new_obj_id:\n raise TypeError('The slice spans several widgets, but '\n 'only a single widget can be retrieved '\n 'at a time')\n\n return self._children[obj_id]\n\n def _update_layout(self):\n\n grid_template_areas_css = "\n".join('"{}"'.format(" ".join(line))\n for line in self._grid_template_areas)\n\n self.layout.grid_template_columns = self._grid_template_columns\n self.layout.grid_template_rows = self._grid_template_rows\n self.layout.grid_template_areas = grid_template_areas_css\n self.children = tuple(self._children.values())\n\n\n@doc_subst(_doc_snippets)\nclass TwoByTwoLayout(GridBox, LayoutProperties):\n """ Define a layout with 2x2 regular grid.\n\n Parameters\n ----------\n\n top_left: instance of Widget\n top_right: instance of Widget\n bottom_left: instance of Widget\n bottom_right: instance of Widget\n widgets to fill the positions in the layout\n\n merge: bool\n flag to say whether the empty positions should be automatically merged\n\n {style_params}\n\n Examples\n --------\n\n >>> from ipywidgets import TwoByTwoLayout, Button\n >>> TwoByTwoLayout(top_left=Button(description="Top left"),\n ... top_right=Button(description="Top right"),\n ... bottom_left=Button(description="Bottom left"),\n ... bottom_right=Button(description="Bottom right"))\n\n """\n\n # widget positions\n top_left = Instance(Widget, allow_none=True)\n top_right = Instance(Widget, allow_none=True)\n bottom_left = Instance(Widget, allow_none=True)\n bottom_right = Instance(Widget, allow_none=True)\n\n # extra args\n merge = Bool(default_value=True)\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._update_layout()\n\n def _update_layout(self):\n\n\n grid_template_areas = [["top-left", "top-right"],\n ["bottom-left", "bottom-right"]]\n\n all_children = {'top-left' : self.top_left,\n 'top-right' : self.top_right,\n 'bottom-left' : self.bottom_left,\n 'bottom-right' : self.bottom_right}\n\n children = {position : child\n for position, child in all_children.items()\n if child is not None}\n\n if not children:\n return\n\n for position, child in children.items():\n child.layout.grid_area = position\n\n if self.merge:\n\n if len(children) == 1:\n position = list(children.keys())[0]\n grid_template_areas = [[position, position],\n [position, position]]\n else:\n columns = ['left', 'right']\n for i, column in enumerate(columns):\n top, bottom = children.get('top-' + column), children.get('bottom-' + column)\n i_neighbour = (i + 1) % 2\n if top is None and bottom is None:\n # merge each cell in this column with the neighbour on the same row\n grid_template_areas[0][i] = grid_template_areas[0][i_neighbour]\n grid_template_areas[1][i] = grid_template_areas[1][i_neighbour]\n elif top is None:\n # merge with the cell below\n grid_template_areas[0][i] = grid_template_areas[1][i]\n elif bottom is None:\n # merge with the cell above\n grid_template_areas[1][i] = grid_template_areas[0][i]\n\n grid_template_areas_css = "\n".join('"{}"'.format(" ".join(line))\n for line in grid_template_areas)\n\n self.layout.grid_template_columns = '1fr 1fr'\n self.layout.grid_template_rows = '1fr 1fr'\n self.layout.grid_template_areas = grid_template_areas_css\n\n self.children = tuple(children.values())\n\n @observe("top_left", "bottom_left", "top_right", "bottom_right", "merge")\n def _child_changed(self, change): #pylint: disable=unused-argument\n self._update_layout()\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_templates.py
|
widget_templates.py
|
Python
| 15,507 | 0.95 | 0.143172 | 0.02346 |
awesome-app
| 420 |
2025-01-02T14:02:57.866477
|
GPL-3.0
| false |
93f183e92dd2a19a723e8d398258e736
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""\nTime picker widget\n"""\n\nfrom traitlets import Unicode, Bool, Union, CaselessStrEnum, CFloat, validate, TraitError\n\nfrom .trait_types import Time, time_serialization\nfrom .valuewidget import ValueWidget\nfrom .widget import register\nfrom .widget_core import CoreWidget\nfrom .widget_description import DescriptionWidget\n\n\n@register\nclass TimePicker(DescriptionWidget, ValueWidget, CoreWidget):\n """\n Display a widget for picking times.\n\n Parameters\n ----------\n\n value: datetime.time\n The current value of the widget.\n\n disabled: bool\n Whether to disable user changes.\n\n min: datetime.time\n The lower allowed time bound\n\n max: datetime.time\n The upper allowed time bound\n\n step: float | 'any'\n The time step to use for the picker, in seconds, or "any"\n\n Examples\n --------\n\n >>> import datetime\n >>> import ipydatetime\n >>> time_pick = ipydatetime.TimePicker()\n >>> time_pick.value = datetime.time(12, 34, 3)\n """\n\n _view_name = Unicode("TimeView").tag(sync=True)\n _model_name = Unicode("TimeModel").tag(sync=True)\n\n value = Time(None, allow_none=True).tag(sync=True, **time_serialization)\n disabled = Bool(False, help="Enable or disable user changes.").tag(sync=True)\n\n min = Time(None, allow_none=True).tag(sync=True, **time_serialization)\n max = Time(None, allow_none=True).tag(sync=True, **time_serialization)\n step = Union(\n (CFloat(60), CaselessStrEnum(["any"])),\n help='The time step to use for the picker, in seconds, or "any".',\n ).tag(sync=True)\n\n @validate("value")\n def _validate_value(self, proposal):\n """Cap and floor value"""\n value = proposal["value"]\n if value is None:\n return value\n if self.min and self.min > value:\n value = max(value, self.min)\n if self.max and self.max < value:\n value = min(value, self.max)\n return value\n\n @validate("min")\n def _validate_min(self, proposal):\n """Enforce min <= value <= max"""\n min = proposal["value"]\n if min is None:\n return min\n if self.max and min > self.max:\n raise TraitError("Setting min > max")\n if self.value and min > self.value:\n self.value = min\n return min\n\n @validate("max")\n def _validate_max(self, proposal):\n """Enforce min <= value <= max"""\n max = proposal["value"]\n if max is None:\n return max\n if self.min and max < self.min:\n raise TraitError("setting max < min")\n if self.value and max < self.value:\n self.value = max\n return max\n
|
.venv\Lib\site-packages\ipywidgets\widgets\widget_time.py
|
widget_time.py
|
Python
| 2,779 | 0.95 | 0.166667 | 0.025974 |
vue-tools
| 129 |
2023-08-21T21:04:30.000205
|
Apache-2.0
| false |
85cfddf8105162a99a407b08ad571260
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom .widget import Widget, CallbackDispatcher, register, widget_serialization\nfrom .domwidget import DOMWidget\nfrom .valuewidget import ValueWidget\n\nfrom .trait_types import Color, Datetime, NumberFormat, TypedTuple\n\nfrom .widget_core import CoreWidget\nfrom .widget_bool import Checkbox, ToggleButton, Valid\nfrom .widget_button import Button, ButtonStyle\nfrom .widget_box import Box, HBox, VBox, GridBox\nfrom .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider, FloatLogSlider\nfrom .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider, Play, SliderStyle\nfrom .widget_color import ColorPicker\nfrom .widget_date import DatePicker\nfrom .widget_datetime import DatetimePicker, NaiveDatetimePicker\nfrom .widget_time import TimePicker\nfrom .widget_output import Output\nfrom .widget_selection import RadioButtons, ToggleButtons, ToggleButtonsStyle, Dropdown, Select, SelectionSlider, SelectMultiple, SelectionRangeSlider\nfrom .widget_selectioncontainer import Tab, Accordion, Stack\nfrom .widget_string import HTML, HTMLMath, Label, Text, Textarea, Password, Combobox\nfrom .widget_controller import Controller\nfrom .interaction import interact, interactive, fixed, interact_manual, interactive_output\nfrom .widget_link import jslink, jsdlink\nfrom .widget_layout import Layout\nfrom .widget_media import Image, Video, Audio\nfrom .widget_tagsinput import TagsInput, ColorsInput, FloatsInput, IntsInput\nfrom .widget_style import Style\nfrom .widget_templates import TwoByTwoLayout, AppLayout, GridspecLayout\nfrom .widget_upload import FileUpload\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__init__.py
|
__init__.py
|
Python
| 1,709 | 0.95 | 0 | 0.068966 |
awesome-app
| 557 |
2024-05-13T02:52:55.085530
|
BSD-3-Clause
| false |
46626cd5c03d83433aeb89d320558827
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom unittest import TestCase\n\nfrom ipywidgets.widgets.docutils import doc_subst\n\n\nclass TestDocSubst(TestCase):\n\n def test_substitution(self):\n snippets = {'key': '62'}\n\n @doc_subst(snippets)\n def f():\n """ Docstring with value {key} """\n\n assert "Docstring with value 62" in f.__doc__\n\n def test_unused_keys(self):\n snippets = {'key': '62', 'other-key': 'unused'}\n\n @doc_subst(snippets)\n def f():\n """ Docstring with value {key} """\n\n assert "Docstring with value 62" in f.__doc__\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_docutils.py
|
test_docutils.py
|
Python
| 669 | 0.95 | 0.185185 | 0.117647 |
react-lib
| 677 |
2023-10-15T09:35:43.642214
|
MIT
| true |
36268f71d88d28cfb76a3d85ca347344
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Test interact and interactive."""\n\nfrom unittest.mock import patch\n\nimport os\nfrom enum import Enum\nfrom collections import OrderedDict\nimport pytest\n\nimport ipywidgets as widgets\n\nfrom traitlets import TraitError, Float\nfrom ipywidgets import (interact, interact_manual, interactive,\n interaction, Output, Widget)\n\n#-----------------------------------------------------------------------------\n# Utility stuff\n#-----------------------------------------------------------------------------\n\ndef f(**kwargs):\n pass\n\n\nclass Color(Enum):\n red = 0\n green = 1\n blue = 2\n\n\ndef g(a: str, b: bool, c: int, d: float, e: Color) -> None:\n pass\n\n\ndisplayed = []\n@pytest.fixture()\ndef clear_display():\n global displayed\n displayed = []\n\ndef record_display(*args):\n displayed.extend(args)\n\n#-----------------------------------------------------------------------------\n# Actual tests\n#-----------------------------------------------------------------------------\n\ndef check_widget(w, **d):\n """Check a single widget against a dict"""\n for attr, expected in d.items():\n if attr == 'cls':\n assert w.__class__ is expected\n else:\n value = getattr(w, attr)\n assert value == expected, "{}.{} = {!r} != {!r}".format(w.__class__.__name__, attr, value, expected)\n\n # For numeric values, the types should match too\n if isinstance(value, (int, float)):\n tv = type(value)\n te = type(expected)\n assert tv is te, "type({}.{}) = {!r} != {!r}".format(w.__class__.__name__, attr, tv, te)\n\ndef check_widget_children(container, **to_check):\n """Check that widgets are created as expected"""\n # build a widget dictionary, so it matches\n widgets = {}\n for w in container.children:\n if not isinstance(w, Output):\n widgets[w.description] = w\n\n for key, d in to_check.items():\n assert key in widgets\n check_widget(widgets[key], **d)\n\n\ndef test_single_value_string():\n a = 'hello'\n c = interactive(f, a=a)\n w = c.children[0]\n check_widget(w,\n cls=widgets.Text,\n description='a',\n value=a,\n )\n\ndef test_single_value_bool():\n for a in (True, False):\n c = interactive(f, a=a)\n w = c.children[0]\n check_widget(w,\n cls=widgets.Checkbox,\n description='a',\n value=a,\n )\n\ndef test_single_value_float():\n for a in (2.25, 1.0, -3.5, 0.0):\n if not a:\n expected_min = 0.0\n expected_max = 1.0\n elif a > 0:\n expected_min = -a\n expected_max = 3*a\n else:\n expected_min = 3*a\n expected_max = -a\n c = interactive(f, a=a)\n w = c.children[0]\n check_widget(w,\n cls=widgets.FloatSlider,\n description='a',\n value=a,\n min=expected_min,\n max=expected_max,\n step=0.1,\n readout=True,\n )\n\ndef test_single_value_int():\n for a in (1, 5, -3, 0):\n if not a:\n expected_min = 0\n expected_max = 1\n elif a > 0:\n expected_min = -a\n expected_max = 3*a\n else:\n expected_min = 3*a\n expected_max = -a\n c = interactive(f, a=a)\n assert len(c.children) == 2\n w = c.children[0]\n check_widget(w,\n cls=widgets.IntSlider,\n description='a',\n value=a,\n min=expected_min,\n max=expected_max,\n step=1,\n readout=True,\n )\n\ndef test_list_str():\n values = ['hello', 'there', 'guy']\n first = values[0]\n c = interactive(f, lis=values)\n assert len(c.children) == 2\n d = dict(\n cls=widgets.Dropdown,\n value=first,\n options=tuple(values),\n _options_labels=tuple(values),\n _options_values=tuple(values),\n )\n check_widget_children(c, lis=d)\n\ndef test_list_int():\n values = [3, 1, 2]\n first = values[0]\n c = interactive(f, lis=values)\n assert len(c.children) == 2\n d = dict(\n cls=widgets.Dropdown,\n value=first,\n options=tuple(values),\n _options_labels=tuple(str(v) for v in values),\n _options_values=tuple(values),\n )\n check_widget_children(c, lis=d)\n\ndef test_list_tuple():\n values = [(3, 300), (1, 100), (2, 200)]\n first = values[0][1]\n c = interactive(f, lis=values)\n assert len(c.children) == 2\n d = dict(\n cls=widgets.Dropdown,\n value=first,\n options=tuple(values),\n _options_labels=("3", "1", "2"),\n _options_values=(300, 100, 200),\n )\n check_widget_children(c, lis=d)\n\ndef test_list_tuple_invalid():\n for bad in [\n (),\n ]:\n with pytest.raises(ValueError):\n print(bad) # because there is no custom message in assert_raises\n c = interactive(f, tup=bad)\n\ndef test_dict():\n for d in [\n dict(a=5),\n dict(a=5, b='b', c=dict),\n ]:\n c = interactive(f, d=d)\n w = c.children[0]\n check = dict(\n cls=widgets.Dropdown,\n description='d',\n value=next(iter(d.values())),\n options=d,\n _options_labels=tuple(d.keys()),\n _options_values=tuple(d.values()),\n )\n check_widget(w, **check)\n\ndef test_ordereddict():\n from collections import OrderedDict\n items = [(3, 300), (1, 100), (2, 200)]\n first = items[0][1]\n values = OrderedDict(items)\n c = interactive(f, lis=values)\n assert len(c.children) == 2\n d = dict(\n cls=widgets.Dropdown,\n value=first,\n options=values,\n _options_labels=("3", "1", "2"),\n _options_values=(300, 100, 200),\n )\n check_widget_children(c, lis=d)\n\ndef test_iterable():\n def yield_values():\n yield 3\n yield 1\n yield 2\n first = next(yield_values())\n c = interactive(f, lis=yield_values())\n assert len(c.children) == 2\n d = dict(\n cls=widgets.Dropdown,\n value=first,\n options=(3, 1, 2),\n _options_labels=("3", "1", "2"),\n _options_values=(3, 1, 2),\n )\n check_widget_children(c, lis=d)\n\ndef test_iterable_tuple():\n values = [(3, 300), (1, 100), (2, 200)]\n first = values[0][1]\n c = interactive(f, lis=iter(values))\n assert len(c.children) == 2\n d = dict(\n cls=widgets.Dropdown,\n value=first,\n options=tuple(values),\n _options_labels=("3", "1", "2"),\n _options_values=(300, 100, 200),\n )\n check_widget_children(c, lis=d)\n\ndef test_mapping():\n from collections.abc import Mapping\n from collections import OrderedDict\n class TestMapping(Mapping):\n def __init__(self, values):\n self.values = values\n def __getitem__(self):\n raise NotImplementedError\n def __len__(self):\n raise NotImplementedError\n def __iter__(self):\n raise NotImplementedError\n def items(self):\n return self.values\n\n items = [(3, 300), (1, 100), (2, 200)]\n first = items[0][1]\n values = TestMapping(items)\n c = interactive(f, lis=values)\n assert len(c.children) == 2\n d = dict(\n cls=widgets.Dropdown,\n value=first,\n options=tuple(items),\n _options_labels=("3", "1", "2"),\n _options_values=(300, 100, 200),\n )\n check_widget_children(c, lis=d)\n\ndef test_decorator_kwarg(clear_display):\n with patch.object(interaction, 'display', record_display):\n @interact(a=5)\n def foo(a):\n pass\n assert len(displayed) == 1\n w = displayed[0].children[0]\n check_widget(w,\n cls=widgets.IntSlider,\n value=5,\n )\n\ndef test_interact_instancemethod(clear_display):\n class Foo:\n def show(self, x):\n print(x)\n\n f = Foo()\n\n with patch.object(interaction, 'display', record_display):\n g = interact(f.show, x=(1,10))\n assert len(displayed) == 1\n w = displayed[0].children[0]\n check_widget(w,\n cls=widgets.IntSlider,\n value=5,\n )\n\ndef test_decorator_no_call(clear_display):\n with patch.object(interaction, 'display', record_display):\n @interact\n def foo(a='default'):\n pass\n assert len(displayed) == 1\n w = displayed[0].children[0]\n check_widget(w,\n cls=widgets.Text,\n value='default',\n )\n\ndef test_call_interact(clear_display):\n def foo(a='default'):\n pass\n with patch.object(interaction, 'display', record_display):\n ifoo = interact(foo)\n assert len(displayed) == 1\n w = displayed[0].children[0]\n check_widget(w,\n cls=widgets.Text,\n value='default',\n )\n\ndef test_call_interact_on_trait_changed_none_return(clear_display):\n def foo(a='default'):\n pass\n with patch.object(interaction, 'display', record_display):\n ifoo = interact(foo)\n assert len(displayed) == 1\n w = displayed[0].children[0]\n check_widget(w,\n cls=widgets.Text,\n value='default',\n )\n with patch.object(interaction, 'display', record_display):\n w.value = 'called'\n assert len(displayed) == 1\n\ndef test_call_interact_kwargs(clear_display):\n def foo(a='default'):\n pass\n with patch.object(interaction, 'display', record_display):\n ifoo = interact(foo, a=10)\n assert len(displayed) == 1\n w = displayed[0].children[0]\n check_widget(w,\n cls=widgets.IntSlider,\n value=10,\n )\n\ndef test_call_decorated_on_trait_change(clear_display):\n """test calling @interact decorated functions"""\n d = {}\n with patch.object(interaction, 'display', record_display):\n @interact\n def foo(a='default'):\n d['a'] = a\n return a\n assert len(displayed) == 2 # display the result and the interact\n w = displayed[1].children[0]\n check_widget(w,\n cls=widgets.Text,\n value='default',\n )\n # test calling the function directly\n a = foo('hello')\n assert a == 'hello'\n assert d['a'] == 'hello'\n\n # test that setting trait values calls the function\n with patch.object(interaction, 'display', record_display):\n w.value = 'called'\n assert d['a'] == 'called'\n assert len(displayed) == 3\n assert w.value == displayed[-1]\n\ndef test_call_decorated_kwargs_on_trait_change(clear_display):\n """test calling @interact(foo=bar) decorated functions"""\n d = {}\n with patch.object(interaction, 'display', record_display):\n @interact(a='kwarg')\n def foo(a='default'):\n d['a'] = a\n return a\n assert len(displayed) == 2 # display the result and the interact\n w = displayed[1].children[0]\n check_widget(w,\n cls=widgets.Text,\n value='kwarg',\n )\n # test calling the function directly\n a = foo('hello')\n assert a == 'hello'\n assert d['a'] == 'hello'\n\n # test that setting trait values calls the function\n with patch.object(interaction, 'display', record_display):\n w.value = 'called'\n assert d['a'] == 'called'\n assert len(displayed) == 3\n assert w.value == displayed[-1]\n\n\n\ndef test_fixed():\n c = interactive(f, a=widgets.fixed(5), b='text')\n assert len(c.children) == 2\n w = c.children[0]\n check_widget(w,\n cls=widgets.Text,\n value='text',\n description='b',\n )\n\ndef test_default_description():\n c = interactive(f, b='text')\n w = c.children[0]\n check_widget(w,\n cls=widgets.Text,\n value='text',\n description='b',\n )\n\ndef test_custom_description():\n d = {}\n def record_kwargs(**kwargs):\n d.clear()\n d.update(kwargs)\n\n c = interactive(record_kwargs, b=widgets.Text(value='text', description='foo'))\n w = c.children[0]\n check_widget(w,\n cls=widgets.Text,\n value='text',\n description='foo',\n )\n w.value = 'different text'\n assert d == {'b': 'different text'}\n\ndef test_raises_on_non_value_widget():\n """ Test that passing in a non-value widget raises an error """\n\n class BadWidget(Widget):\n """ A widget that contains a `value` traitlet """\n value = Float()\n\n with pytest.raises(TypeError, match=".* not a ValueWidget.*"):\n interactive(f, b=BadWidget())\n\ndef test_interact_manual_button():\n c = interact.options(manual=True).widget(f)\n w = c.children[0]\n check_widget(w, cls=widgets.Button)\n\ndef test_interact_manual_nocall():\n callcount = 0\n def calltest(testarg):\n callcount += 1\n c = interact.options(manual=True)(calltest, testarg=5).widget\n c.children[0].value = 10\n assert callcount == 0\n\ndef test_interact_call():\n w = interact.widget(f)\n w.update()\n\n w = interact_manual.widget(f)\n w.update()\n\ndef test_interact_options():\n def f(x):\n return x\n w = interact.options(manual=False).options(manual=True)(f, x=21).widget\n assert w.manual == True\n\n w = interact_manual.options(manual=False).options()(x=21).widget(f)\n assert w.manual == False\n\n w = interact(x=21)().options(manual=True)(f).widget\n assert w.manual == True\n\ndef test_interact_options_bad():\n with pytest.raises(ValueError):\n interact.options(bad="foo")\n\ndef test_int_range_logic():\n irsw = widgets.IntRangeSlider\n w = irsw(value=(2, 4), min=0, max=6)\n check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)\n w.upper = 3\n w.max = 3\n check_widget(w, cls=irsw, value=(2, 3), min=0, max=3)\n\n w.min = 0\n w.max = 6\n w.lower = 2\n w.upper = 4\n check_widget(w, cls=irsw, value=(2, 4), min=0, max=6)\n w.value = (0, 1) #lower non-overlapping range\n check_widget(w, cls=irsw, value=(0, 1), min=0, max=6)\n w.value = (5, 6) #upper non-overlapping range\n check_widget(w, cls=irsw, value=(5, 6), min=0, max=6)\n w.lower = 2\n check_widget(w, cls=irsw, value=(2, 6), min=0, max=6)\n\n with pytest.raises(TraitError):\n w.min = 7\n with pytest.raises(TraitError):\n w.max = -1\n\n w = irsw(min=2, max=3, value=(2, 3))\n check_widget(w, min=2, max=3, value=(2, 3))\n w = irsw(min=100, max=200, value=(125, 175))\n check_widget(w, value=(125, 175))\n\n with pytest.raises(TraitError):\n irsw(min=2, max=1)\n\n\ndef test_float_range_logic():\n frsw = widgets.FloatRangeSlider\n w = frsw(value=(.2, .4), min=0., max=.6)\n check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)\n\n w.min = 0.\n w.max = .6\n w.lower = .2\n w.upper = .4\n check_widget(w, cls=frsw, value=(.2, .4), min=0., max=.6)\n w.value = (0., .1) #lower non-overlapping range\n check_widget(w, cls=frsw, value=(0., .1), min=0., max=.6)\n w.value = (.5, .6) #upper non-overlapping range\n check_widget(w, cls=frsw, value=(.5, .6), min=0., max=.6)\n w.lower = .2\n check_widget(w, cls=frsw, value=(.2, .6), min=0., max=.6)\n\n with pytest.raises(TraitError):\n w.min = .7\n with pytest.raises(TraitError):\n w.max = -.1\n\n w = frsw(min=2, max=3, value=(2.2, 2.5))\n check_widget(w, min=2., max=3.)\n\n with pytest.raises(TraitError):\n frsw(min=.2, max=.1)\n\n\ndef test_multiple_selection():\n smw = widgets.SelectMultiple\n\n # degenerate multiple select\n w = smw()\n check_widget(w, value=tuple())\n\n # don't accept random other value when no options\n with pytest.raises(TraitError):\n w.value = (2,)\n check_widget(w, value=tuple())\n\n # basic multiple select\n w = smw(options=[(1, 1)], value=[1])\n check_widget(w, cls=smw, value=(1,), options=((1, 1),))\n\n # don't accept random other value\n with pytest.raises(TraitError):\n w.value = w.value + (2,)\n check_widget(w, value=(1,))\n\n # change options, which resets value\n w.options = w.options + ((2, 2),)\n check_widget(w, options=((1, 1), (2,2)), value=())\n\n # change value\n w.value = (1,2)\n check_widget(w, value=(1, 2))\n\n # dict style\n w.options = {1: 1}\n check_widget(w, options={1:1})\n\n # updating\n w.options = (1,)\n with pytest.raises(TraitError):\n w.value = (2,)\n check_widget(w, options=(1,) )\n\ndef test_interact_noinspect():\n a = 'hello'\n c = interactive(dict, a=a)\n w = c.children[0]\n check_widget(w,\n cls=widgets.Text,\n description='a',\n value=a,\n )\n\n\ndef test_get_interact_value():\n from ipywidgets.widgets import ValueWidget\n from traitlets import Unicode\n class TheAnswer(ValueWidget):\n _model_name = Unicode('TheAnswer')\n description = Unicode()\n def get_interact_value(self):\n return 42\n w = TheAnswer()\n c = interactive(lambda v: v, v=w)\n c.update()\n assert c.result == 42\n\ndef test_state_schema():\n from ipywidgets.widgets import IntSlider, Widget\n import json\n import jsonschema\n s = IntSlider()\n state = Widget.get_manager_state(drop_defaults=True)\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../', 'state.schema.json')) as f:\n schema = json.load(f)\n jsonschema.validate(state, schema)\n\ndef test_type_hints():\n c = interactive(g)\n \n assert len(c.children) == 6\n\n check_widget_children(\n c,\n a={'cls': widgets.Text},\n b={'cls': widgets.Checkbox},\n c={'cls': widgets.IntText},\n d={'cls': widgets.FloatText},\n e={\n 'cls': widgets.Dropdown,\n 'options': {\n 'red': Color.red,\n 'green': Color.green,\n 'blue': Color.blue,\n },\n '_options_labels': ("red", "green", "blue"),\n '_options_values': (Color.red, Color.green, Color.blue),\n },\n )\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_interaction.py
|
test_interaction.py
|
Python
| 17,849 | 0.95 | 0.127273 | 0.038732 |
node-utils
| 44 |
2023-12-25T11:31:21.401571
|
Apache-2.0
| true |
4ff64cf405f56ba3d2213cf9e2dafd87
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport pytest\n\nfrom .. import jslink, jsdlink, ToggleButton\n\ndef test_jslink_args():\n with pytest.raises(TypeError):\n jslink()\n w1 = ToggleButton()\n with pytest.raises(TypeError):\n jslink((w1, 'value'))\n\n w2 = ToggleButton()\n jslink((w1, 'value'), (w2, 'value'))\n\n with pytest.raises(TypeError):\n jslink((w1, 'value'), (w2, 'nosuchtrait'))\n\n with pytest.raises(TypeError):\n jslink((w1, 'value'), (w2, 'traits'))\n\ndef test_jsdlink_args():\n with pytest.raises(TypeError):\n jsdlink()\n w1 = ToggleButton()\n with pytest.raises(TypeError):\n jsdlink((w1, 'value'))\n\n w2 = ToggleButton()\n jsdlink((w1, 'value'), (w2, 'value'))\n\n with pytest.raises(TypeError):\n jsdlink((w1, 'value'), (w2, 'nosuchtrait'))\n\n with pytest.raises(TypeError):\n jsdlink((w1, 'value'), (w2, 'traits'))\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_link.py
|
test_link.py
|
Python
| 970 | 0.95 | 0.052632 | 0.071429 |
node-utils
| 972 |
2024-10-26T20:30:13.441957
|
GPL-3.0
| true |
34d8e53b6b5396c8f2394099654f26a9
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom unittest import TestCase\n\nfrom traitlets import TraitError\n\nfrom ipywidgets.widgets import Accordion, Tab, Stack, HTML\n\nclass TestTab(TestCase):\n\n def setUp(self):\n self.children = [HTML('0'), HTML('1')]\n self.widget = Tab\n\n def test_selected_index_none(self):\n widget = self.widget(self.children, selected_index=None)\n state = widget.get_state()\n assert state['selected_index'] == 0\n\n def test_selected_index_default(self):\n widget = self.widget(self.children)\n state = widget.get_state()\n assert state['selected_index'] == 0\n\n def test_selected_index(self):\n widget = self.widget(self.children, selected_index=1)\n state = widget.get_state()\n assert state['selected_index'] == 1\n\n def test_selected_index_out_of_bounds(self):\n with self.assertRaises(TraitError):\n self.widget(self.children, selected_index=-1)\n\n def test_children_position_argument(self):\n self.widget(self.children)\n\n def test_titles(self):\n widget = self.widget(self.children, selected_index=None)\n assert widget.get_state()['titles'] == ('', '')\n assert widget.titles == ('', '')\n\n widget.set_title(1, 'Title 1')\n assert widget.get_state()['titles'] == ('', 'Title 1')\n assert widget.titles[1] == 'Title 1'\n assert widget.get_title(1) == 'Title 1'\n\n # Backwards compatible with 7.x api\n widget.set_title(1, None)\n assert widget.get_state()['titles'] == ('', '')\n assert widget.titles[1] == ''\n assert widget.get_title(1) == ''\n\n with self.assertRaises(IndexError):\n widget.set_title(2, 'out of bounds')\n with self.assertRaises(IndexError):\n widget.get_title(2)\n\n widget.children = tuple(widget.children[:1])\n assert len(widget.children) == 1\n assert widget.titles == ('',)\n\nclass TestAccordion(TestCase):\n\n def setUp(self):\n self.children = [HTML('0'), HTML('1')]\n self.widget = Accordion\n\n def test_selected_index_none(self):\n widget = self.widget(self.children, selected_index=None)\n state = widget.get_state()\n assert state['selected_index'] is None\n\n def test_selected_index_default(self):\n widget = self.widget(self.children)\n state = widget.get_state()\n assert state['selected_index'] is None\n\n def test_selected_index(self):\n widget = self.widget(self.children, selected_index=1)\n state = widget.get_state()\n assert state['selected_index'] == 1\n\n def test_selected_index_out_of_bounds(self):\n with self.assertRaises(TraitError):\n self.widget(self.children, selected_index=-1)\n\n def test_children_position_argument(self):\n self.widget(self.children)\n\n def test_titles(self):\n widget = self.widget(self.children, selected_index=None)\n assert widget.get_state()['titles'] == ('', '')\n assert widget.titles == ('', '')\n\n widget.set_title(1, 'Title 1')\n assert widget.get_state()['titles'] == ('', 'Title 1')\n assert widget.titles[1] == 'Title 1'\n assert widget.get_title(1) == 'Title 1'\n\n # Backwards compatible with 7.x api\n widget.set_title(1, None)\n assert widget.get_state()['titles'] == ('', '')\n assert widget.titles[1] == ''\n assert widget.get_title(1) == ''\n\n with self.assertRaises(IndexError):\n widget.set_title(2, 'out of bounds')\n with self.assertRaises(IndexError):\n widget.get_title(2)\n\n widget.children = tuple(widget.children[:1])\n assert len(widget.children) == 1\n assert widget.titles == ('',)\n\nclass TestStack(TestCase):\n\n def setUp(self):\n self.children = [HTML('0'), HTML('1')]\n self.widget = Stack\n\n def test_selected_index_none(self):\n widget = self.widget(self.children, selected_index=None)\n state = widget.get_state()\n assert state['selected_index'] is None\n\n def test_selected_index_default(self):\n widget = self.widget(self.children)\n state = widget.get_state()\n assert state['selected_index'] is None\n\n def test_selected_index(self):\n widget = self.widget(self.children, selected_index=1)\n state = widget.get_state()\n assert state['selected_index'] == 1\n\n def test_selected_index_out_of_bounds(self):\n with self.assertRaises(TraitError):\n self.widget(self.children, selected_index=-1)\n\n def test_children_position_argument(self):\n self.widget(self.children)\n\n def test_titles(self):\n widget = self.widget(self.children, selected_index=None)\n assert widget.get_state()['titles'] == ('', '')\n assert widget.titles == ('', '')\n\n widget.set_title(1, 'Title 1')\n assert widget.get_state()['titles'] == ('', 'Title 1')\n assert widget.titles[1] == 'Title 1'\n assert widget.get_title(1) == 'Title 1'\n\n # Backwards compatible with 7.x api\n widget.set_title(1, None)\n assert widget.get_state()['titles'] == ('', '')\n assert widget.titles[1] == ''\n assert widget.get_title(1) == ''\n\n with self.assertRaises(IndexError):\n widget.set_title(2, 'out of bounds')\n with self.assertRaises(IndexError):\n widget.get_title(2)\n\n widget.children = tuple(widget.children[:1])\n assert len(widget.children) == 1\n assert widget.titles == ('',)\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_selectioncontainer.py
|
test_selectioncontainer.py
|
Python
| 5,619 | 0.95 | 0.142857 | 0.039063 |
react-lib
| 513 |
2024-01-19T22:12:54.350231
|
GPL-3.0
| true |
ede0730d920a4711286b07d1e58c3321
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import Bool, Tuple, List\n\nfrom .utils import setup\n\nfrom ..widget import Widget\n\nfrom ..._version import __control_protocol_version__\n\n# A widget with simple traits\nclass SimpleWidget(Widget):\n a = Bool().tag(sync=True)\n b = Tuple(Bool(), Bool(), Bool(), default_value=(False, False, False)).tag(\n sync=True\n )\n c = List(Bool()).tag(sync=True)\n\n\ndef test_empty_send_state():\n w = SimpleWidget()\n w.send_state([])\n assert w.comm.messages == []\n\n\ndef test_empty_hold_sync():\n w = SimpleWidget()\n with w.hold_sync():\n pass\n assert w.comm.messages == []\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_send_state.py
|
test_send_state.py
|
Python
| 711 | 0.95 | 0.096774 | 0.136364 |
vue-tools
| 515 |
2024-12-03T18:09:17.513454
|
BSD-3-Clause
| true |
e11e57e927dd05ad588629a38f567fb1
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport inspect\nimport pytest\n\nfrom ..utils import deprecation\nfrom .utils import call_method\n\nCALL_PATH = inspect.getfile(call_method)\n\ndef test_deprecation():\n caller_path = inspect.stack(context=0)[1].filename\n with pytest.deprecated_call() as record:\n deprecation('Deprecated call')\n # Make sure the deprecation pointed to the external function calling this test function\n assert len(record) == 1\n assert record[0].filename == caller_path\n\n with pytest.deprecated_call() as record:\n deprecation('Deprecated call', ['ipywidgets/widgets/tests'])\n # Make sure the deprecation pointed to the external function calling this test function\n assert len(record) == 1\n assert record[0].filename == caller_path\n\n with pytest.deprecated_call() as record:\n deprecation('Deprecated call', 'ipywidgets/widgets/tests')\n # Make sure the deprecation pointed to the external function calling this test function\n assert len(record) == 1\n assert record[0].filename == caller_path\n\n with pytest.deprecated_call() as record:\n deprecation('Deprecated call', [])\n # Make sure the deprecation pointed to *this* file\n assert len(record) == 1\n assert record[0].filename == __file__\n\ndef test_deprecation_indirect():\n # If the line that calls "deprecation" is not internal, it is considered the source:\n with pytest.warns(DeprecationWarning) as record:\n call_method(deprecation, "test message", [])\n assert len(record) == 1\n assert record[0].filename == CALL_PATH\n\ndef test_deprecation_indirect_internal():\n # If the line that calls "deprecation" is internal, it is not considered the source:\n with pytest.warns(DeprecationWarning) as record:\n call_method(deprecation, "test message", [CALL_PATH])\n assert len(record) == 1\n assert record[0].filename == __file__\n\ndef test_deprecation_nested1():\n def level1():\n deprecation("test message", [])\n\n with pytest.warns(DeprecationWarning) as record:\n call_method(level1)\n\n assert len(record) == 1\n assert record[0].filename == __file__\n\ndef test_deprecation_nested2():\n def level2():\n deprecation("test message", [])\n def level1():\n level2()\n\n with pytest.warns(DeprecationWarning) as record:\n call_method(level1)\n\n assert len(record) == 1\n assert record[0].filename == __file__\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_utils.py
|
test_utils.py
|
Python
| 2,478 | 0.95 | 0.194444 | 0.140351 |
react-lib
| 405 |
2024-12-05T20:15:53.698656
|
GPL-3.0
| true |
87d8730de10847674254c6ffafd80530
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Test Widget."""\n\nimport inspect\n\nimport pytest\nfrom IPython.core.interactiveshell import InteractiveShell\nfrom IPython.display import display\nfrom IPython.utils.capture import capture_output\n\nfrom .. import widget\nfrom ..widget import Widget\nfrom ..widget_button import Button\nimport copy\n\n\ndef test_no_widget_view():\n # ensure IPython shell is instantiated\n # otherwise display() just calls print\n shell = InteractiveShell.instance()\n\n with capture_output() as cap:\n w = Widget()\n display(w)\n\n assert len(cap.outputs) == 1, "expect 1 output"\n mime_bundle = cap.outputs[0].data\n assert mime_bundle["text/plain"] == repr(w), "expected plain text output"\n assert (\n "application/vnd.jupyter.widget-view+json" not in mime_bundle\n ), "widget has no view"\n assert cap.stdout == "", repr(cap.stdout)\n assert cap.stderr == "", repr(cap.stderr)\n\n\ndef test_widget_view():\n # ensure IPython shell is instantiated\n # otherwise display() just calls print\n shell = InteractiveShell.instance()\n\n with capture_output() as cap:\n w = Button()\n display(w)\n\n assert len(cap.outputs) == 1, "expect 1 output"\n mime_bundle = cap.outputs[0].data\n assert mime_bundle["text/plain"] == repr(w), "expected plain text output"\n assert (\n "application/vnd.jupyter.widget-view+json" in mime_bundle\n ), "widget should have have a view"\n assert cap.stdout == "", repr(cap.stdout)\n assert cap.stderr == "", repr(cap.stderr)\n\n\ndef test_close_all():\n # create a couple of widgets\n widgets = [Button() for i in range(10)]\n\n assert len(widget._instances) > 0, "expect active widgets"\n assert widget._instances[widgets[0].model_id] is widgets[0]\n # close all the widgets\n Widget.close_all()\n\n assert len(widget._instances) == 0, "active widgets should be cleared"\n\n\ndef test_compatibility():\n button = Button()\n assert widget._instances[button.model_id] is button\n with pytest.deprecated_call() as record:\n assert widget._instances is widget.Widget.widgets\n assert widget._instances is widget.Widget._active_widgets\n assert widget._registry is widget.Widget.widget_types\n assert widget._registry is widget.Widget._widget_types\n\n Widget.close_all()\n assert not widget.Widget.widgets\n assert not widget.Widget._active_widgets\n caller_path = inspect.stack(context=0)[1].filename\n assert all(x.filename == caller_path for x in record)\n assert len(record) == 6\n\n\ndef test_widget_copy():\n button = Button()\n with pytest.raises(NotImplementedError):\n copy.copy(button)\n with pytest.raises(NotImplementedError):\n copy.deepcopy(button)
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget.py
|
test_widget.py
|
Python
| 2,811 | 0.95 | 0.077778 | 0.114286 |
python-kit
| 250 |
2024-11-11T05:05:24.293168
|
BSD-3-Clause
| true |
df821541183026f25b023e20ba4f67f5
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom unittest import TestCase\n\nfrom traitlets import TraitError\n\nimport ipywidgets as widgets\n\n\nclass TestBox(TestCase):\n\n def test_construction(self):\n box = widgets.Box()\n assert box.get_state()['children'] == []\n\n def test_construction_with_children(self):\n html = widgets.HTML('some html')\n slider = widgets.IntSlider()\n box = widgets.Box([html, slider])\n children_state = box.get_state()['children']\n assert children_state == [\n widgets.widget._widget_to_json(html, None),\n widgets.widget._widget_to_json(slider, None),\n ]\n\n def test_construction_style(self):\n box = widgets.Box(box_style='warning')\n assert box.get_state()['box_style'] == 'warning'\n\n def test_construction_invalid_style(self):\n with self.assertRaises(TraitError):\n widgets.Box(box_style='invalid')\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_box.py
|
test_widget_box.py
|
Python
| 995 | 0.95 | 0.151515 | 0.083333 |
vue-tools
| 704 |
2025-02-28T08:34:23.918042
|
GPL-3.0
| true |
9701c6e94f025a635bca9753d84e1b30
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport inspect\nimport pytest\nfrom ipywidgets import Button\n\ndef test_deprecation_fa_icons():\n with pytest.deprecated_call() as record:\n Button(icon='fa-home')\n assert len(record) == 1\n assert record[0].filename == inspect.stack(context=0)[1].filename\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_button.py
|
test_widget_button.py
|
Python
| 369 | 0.95 | 0.083333 | 0.2 |
awesome-app
| 645 |
2023-12-20T04:12:06.382568
|
Apache-2.0
| true |
5d43bceb1cb65da14713d72e5a4d2f17
|
# coding: utf-8\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport pytest\n\nfrom contextlib import nullcontext\nimport datetime\nimport itertools\n\nimport pytz\nfrom traitlets import TraitError\n\nfrom ..widget_datetime import DatetimePicker\n\n\ndt_1442 = datetime.datetime(1442, 1, 1, tzinfo=pytz.utc)\ndt_1664 = datetime.datetime(1664, 1, 1, tzinfo=pytz.utc)\ndt_1994 = datetime.datetime(1994, 1, 1, tzinfo=pytz.utc)\ndt_2002 = datetime.datetime(2002, 2, 20, 13, 37, 42, 7, tzinfo=pytz.utc)\ndt_2056 = datetime.datetime(2056, 1, 1, tzinfo=pytz.utc)\n\ndef test_time_creation_blank():\n w = DatetimePicker()\n assert w.value is None\n\n\ndef test_time_creation_value():\n dt = datetime.datetime.now(pytz.utc)\n w = DatetimePicker(value=dt)\n assert w.value is dt\n\n\ndef test_datetime_validate_value_none():\n dt = dt_2002\n dt_min = dt_1442\n dt_max = dt_2056\n w = DatetimePicker(value=dt, min=dt_min, max=dt_max)\n w.value = None\n assert w.value is None\n\n\ndef _permuted_dts():\n ret = []\n combos = list(itertools.product([None, dt_1442, dt_2002, dt_2056], repeat=3))\n for vals in combos:\n expected = vals[0]\n if vals[1] and vals[2] and vals[1] > vals[2]:\n expected = TraitError\n elif vals[0] is None:\n pass\n elif vals[1] and vals[1] > vals[0]:\n expected = vals[1]\n elif vals[2] and vals[2] < vals[0]:\n expected = vals[2]\n ret.append(vals + (expected,))\n return ret\n\n\n@pytest.mark.parametrize(\n "input_value,input_min,input_max,expected",\n _permuted_dts()\n)\ndef test_datetime_cross_validate_value_min_max(\n input_value,\n input_min,\n input_max,\n expected,\n):\n w = DatetimePicker(value=dt_2002, min=dt_2002, max=dt_2002)\n should_raise = expected is TraitError\n with pytest.raises(expected) if should_raise else nullcontext():\n with w.hold_trait_notifications():\n w.value = input_value\n w.min = input_min\n w.max = input_max\n if not should_raise:\n assert w.value is expected\n\n\ndef test_datetime_validate_value_vs_min():\n dt = dt_2002\n dt_min = datetime.datetime(2019, 1, 1, tzinfo=pytz.utc)\n dt_max = dt_2056\n w = DatetimePicker(min=dt_min, max=dt_max)\n w.value = dt\n assert w.value.year == 2019\n\n\ndef test_datetime_validate_value_vs_max():\n dt = dt_2002\n dt_min = dt_1664\n dt_max = dt_1994\n w = DatetimePicker(min=dt_min, max=dt_max)\n w.value = dt\n assert w.value.year == 1994\n\n\ndef test_datetime_validate_min_vs_value():\n dt = dt_2002\n dt_min = datetime.datetime(2019, 1, 1, tzinfo=pytz.utc)\n dt_max = dt_2056\n w = DatetimePicker(value=dt, max=dt_max)\n w.min = dt_min\n assert w.value.year == 2019\n\n\ndef test_datetime_validate_min_vs_max():\n dt = dt_2002\n dt_min = datetime.datetime(2112, 1, 1, tzinfo=pytz.utc)\n dt_max = dt_2056\n w = DatetimePicker(value=dt, max=dt_max)\n with pytest.raises(TraitError):\n w.min = dt_min\n\n\ndef test_datetime_validate_max_vs_value():\n dt = dt_2002\n dt_min = dt_1664\n dt_max = dt_1994\n w = DatetimePicker(value=dt, min=dt_min)\n w.max = dt_max\n assert w.value.year == 1994\n\n\ndef test_datetime_validate_max_vs_min():\n dt = dt_2002\n dt_min = dt_1664\n dt_max = datetime.datetime(1337, 1, 1, tzinfo=pytz.utc)\n w = DatetimePicker(value=dt, min=dt_min)\n with pytest.raises(TraitError):\n w.max = dt_max\n\n\ndef test_datetime_validate_naive():\n dt = dt_2002\n dt_min = dt_1442\n dt_max = dt_2056\n\n w = DatetimePicker(value=dt, min=dt_min, max=dt_max)\n with pytest.raises(TraitError):\n w.max = dt_max.replace(tzinfo=None)\n with pytest.raises(TraitError):\n w.min = dt_min.replace(tzinfo=None)\n with pytest.raises(TraitError):\n w.value = dt.replace(tzinfo=None)\n\n\ndef test_datetime_tzinfo():\n tz = pytz.timezone('Australia/Sydney')\n dt = datetime.datetime(2002, 2, 20, 13, 37, 42, 7, tzinfo=tz)\n w = DatetimePicker(value=dt)\n assert w.value == dt\n # tzinfo only changes upon input from user\n assert w.value.tzinfo == tz\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_datetime.py
|
test_widget_datetime.py
|
Python
| 4,147 | 0.95 | 0.108974 | 0.03252 |
awesome-app
| 564 |
2025-05-30T14:43:09.756589
|
MIT
| true |
b1358d5427252824d8b65d372b235f88
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom unittest import TestCase\n\nfrom traitlets import TraitError\n\nfrom ipywidgets import FloatSlider\n\n\nclass TestFloatSlider(TestCase):\n\n def test_construction(self):\n FloatSlider()\n\n def test_construction_readout_format(self):\n slider = FloatSlider(readout_format='$.1f')\n assert slider.get_state()['readout_format'] == '$.1f'\n\n def test_construction_invalid_readout_format(self):\n with self.assertRaises(TraitError):\n FloatSlider(readout_format='broken')\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_float.py
|
test_widget_float.py
|
Python
| 606 | 0.95 | 0.181818 | 0.142857 |
node-utils
| 959 |
2024-09-12T02:47:53.077858
|
BSD-3-Clause
| true |
6734fb6633cdeb55c50eb70ce598c760
|
# coding: utf-8\n\n# Copyright (c) Vidar Tonaas Fauske.\n# Distributed under the terms of the Modified BSD License.\n\nimport pytest\n\nimport datetime\n\nimport pytz\nfrom traitlets import TraitError\n\nfrom ..widget_datetime import NaiveDatetimePicker\n\n\ndef test_time_creation_blank():\n w = NaiveDatetimePicker()\n assert w.value is None\n\n\ndef test_time_creation_value():\n t = datetime.datetime.today()\n w = NaiveDatetimePicker(value=t)\n assert w.value is t\n\n\ndef test_time_validate_value_none():\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7)\n t_min = datetime.datetime(1442, 1, 1)\n t_max = datetime.datetime(2056, 1, 1)\n w = NaiveDatetimePicker(value=t, min=t_min, max=t_max)\n w.value = None\n assert w.value is None\n\n\ndef test_time_validate_value_vs_min():\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7)\n t_min = datetime.datetime(2019, 1, 1)\n t_max = datetime.datetime(2056, 1, 1)\n w = NaiveDatetimePicker(min=t_min, max=t_max)\n w.value = t\n assert w.value.year == 2019\n\n\ndef test_time_validate_value_vs_max():\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7)\n t_min = datetime.datetime(1664, 1, 1)\n t_max = datetime.datetime(1994, 1, 1)\n w = NaiveDatetimePicker(min=t_min, max=t_max)\n w.value = t\n assert w.value.year == 1994\n\n\ndef test_time_validate_min_vs_value():\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7)\n t_min = datetime.datetime(2019, 1, 1)\n t_max = datetime.datetime(2056, 1, 1)\n w = NaiveDatetimePicker(value=t, max=t_max)\n w.min = t_min\n assert w.value.year == 2019\n\n\ndef test_time_validate_min_vs_max():\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7)\n t_min = datetime.datetime(2112, 1, 1)\n t_max = datetime.datetime(2056, 1, 1)\n w = NaiveDatetimePicker(value=t, max=t_max)\n with pytest.raises(TraitError):\n w.min = t_min\n\n\ndef test_time_validate_max_vs_value():\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7)\n t_min = datetime.datetime(1664, 1, 1)\n t_max = datetime.datetime(1994, 1, 1)\n w = NaiveDatetimePicker(value=t, min=t_min)\n w.max = t_max\n assert w.value.year == 1994\n\n\ndef test_time_validate_max_vs_min():\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7)\n t_min = datetime.datetime(1664, 1, 1)\n t_max = datetime.datetime(1337, 1, 1)\n w = NaiveDatetimePicker(value=t, min=t_min)\n with pytest.raises(TraitError):\n w.max = t_max\n\n\ndef test_datetime_tzinfo():\n tz = pytz.timezone('Australia/Sydney')\n t = datetime.datetime(2002, 2, 20, 13, 37, 42, 7, tzinfo=tz)\n with pytest.raises(TraitError):\n w = NaiveDatetimePicker(value=t)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_naive_datetime.py
|
test_widget_naive_datetime.py
|
Python
| 2,633 | 0.95 | 0.106383 | 0.043478 |
vue-tools
| 975 |
2024-04-22T17:58:41.667535
|
BSD-3-Clause
| true |
5a1df853fd744739733ac96ea42abc72
|
import sys\nfrom unittest import TestCase\nfrom contextlib import contextmanager\n\nfrom IPython.display import Markdown, Image\nfrom ipywidgets import widget_output\n\n\nclass TestOutputWidget(TestCase):\n\n @contextmanager\n def _mocked_ipython(self, get_ipython, clear_output):\n """ Context manager that monkeypatches get_ipython and clear_output """\n original_clear_output = widget_output.clear_output\n original_get_ipython = widget_output.get_ipython\n widget_output.get_ipython = get_ipython\n widget_output.clear_output = clear_output\n try:\n yield\n finally:\n widget_output.clear_output = original_clear_output\n widget_output.get_ipython = original_get_ipython\n\n def _mock_get_ipython(self, msg_id):\n """ Returns a mock IPython application with a mocked kernel """\n kernel = type(\n 'mock_kernel',\n (object, ),\n {'_parent_header': {'header': {'msg_id': msg_id}}}\n )\n\n # Specifically override this so the traceback\n # is still printed to screen\n def showtraceback(self_, exc_tuple, *args, **kwargs):\n etype, evalue, tb = exc_tuple\n raise etype(evalue)\n\n ipython = type(\n 'mock_ipython',\n (object, ),\n {'kernel': kernel, 'showtraceback': showtraceback}\n )\n return ipython\n\n def _mock_clear_output(self):\n """ Mock function that records calls to it """\n calls = []\n\n def clear_output(*args, **kwargs):\n calls.append((args, kwargs))\n clear_output.calls = calls\n\n return clear_output\n\n def test_set_msg_id_when_capturing(self):\n msg_id = 'msg-id'\n get_ipython = self._mock_get_ipython(msg_id)\n clear_output = self._mock_clear_output()\n\n with self._mocked_ipython(get_ipython, clear_output):\n widget = widget_output.Output()\n assert widget.msg_id == ''\n with widget:\n assert widget.msg_id == msg_id\n assert widget.msg_id == ''\n\n def test_clear_output(self):\n msg_id = 'msg-id'\n get_ipython = self._mock_get_ipython(msg_id)\n clear_output = self._mock_clear_output()\n\n with self._mocked_ipython(get_ipython, clear_output):\n widget = widget_output.Output()\n widget.clear_output(wait=True)\n\n assert len(clear_output.calls) == 1\n assert clear_output.calls[0] == ((), {'wait': True})\n\n def test_capture_decorator(self):\n msg_id = 'msg-id'\n get_ipython = self._mock_get_ipython(msg_id)\n clear_output = self._mock_clear_output()\n expected_argument = 'arg'\n expected_keyword_argument = True\n captee_calls = []\n\n with self._mocked_ipython(get_ipython, clear_output):\n widget = widget_output.Output()\n assert widget.msg_id == ''\n\n @widget.capture()\n def captee(*args, **kwargs):\n # Check that we are capturing output\n assert widget.msg_id == msg_id\n\n # Check that arguments are passed correctly\n captee_calls.append((args, kwargs))\n\n captee(\n expected_argument, keyword_argument=expected_keyword_argument)\n assert widget.msg_id == ''\n captee()\n\n assert len(captee_calls) == 2\n assert captee_calls[0] == (\n (expected_argument, ),\n {'keyword_argument': expected_keyword_argument}\n )\n assert captee_calls[1] == ((), {})\n\n def test_capture_decorator_clear_output(self):\n msg_id = 'msg-id'\n get_ipython = self._mock_get_ipython(msg_id)\n clear_output = self._mock_clear_output()\n\n with self._mocked_ipython(get_ipython, clear_output):\n widget = widget_output.Output()\n\n @widget.capture(clear_output=True, wait=True)\n def captee(*args, **kwargs):\n # Check that we are capturing output\n assert widget.msg_id == msg_id\n\n captee()\n captee()\n\n assert len(clear_output.calls) == 2\n assert clear_output.calls[0] == clear_output.calls[1] == \\n ((), {'wait': True})\n\n def test_capture_decorator_no_clear_output(self):\n msg_id = 'msg-id'\n get_ipython = self._mock_get_ipython(msg_id)\n clear_output = self._mock_clear_output()\n\n with self._mocked_ipython(get_ipython, clear_output):\n widget = widget_output.Output()\n\n @widget.capture(clear_output=False)\n def captee(*args, **kwargs):\n # Check that we are capturing output\n assert widget.msg_id == msg_id\n\n captee()\n captee()\n\n assert len(clear_output.calls) == 0\n\n\ndef _make_stream_output(text, name):\n return {\n 'output_type': 'stream',\n 'name': name,\n 'text': text\n }\n\n\ndef test_append_stdout():\n widget = widget_output.Output()\n\n # Try appending a message to stdout.\n widget.append_stdout("snakes!")\n expected = (_make_stream_output("snakes!", "stdout"),)\n assert widget.outputs == expected, repr(widget.outputs)\n\n # Try appending a second message.\n widget.append_stdout("more snakes!")\n expected += (_make_stream_output("more snakes!", "stdout"),)\n assert widget.outputs == expected, repr(widget.outputs)\n\n\ndef test_append_stderr():\n widget = widget_output.Output()\n\n # Try appending a message to stderr.\n widget.append_stderr("snakes!")\n expected = (_make_stream_output("snakes!", "stderr"),)\n assert widget.outputs == expected, repr(widget.outputs)\n\n # Try appending a second message.\n widget.append_stderr("more snakes!")\n expected += (_make_stream_output("more snakes!", "stderr"),)\n assert widget.outputs == expected, repr(widget.outputs)\n\n\ndef test_append_display_data():\n widget = widget_output.Output()\n\n # Try appending a Markdown object.\n widget.append_display_data(Markdown("# snakes!"))\n expected = (\n {\n 'output_type': 'display_data',\n 'data': {\n 'text/plain': '<IPython.core.display.Markdown object>',\n 'text/markdown': '# snakes!'\n },\n 'metadata': {}\n },\n )\n assert widget.outputs == expected, repr(widget.outputs)\n\n # Now try appending an Image.\n image_data = b"foobar"\n\n widget.append_display_data(Image(image_data, width=123, height=456))\n # Old ipykernel/IPython\n expected1 = expected + (\n {\n 'output_type': 'display_data',\n 'data': {\n 'image/png': 'Zm9vYmFy\n',\n 'text/plain': '<IPython.core.display.Image object>'\n },\n 'metadata': {\n 'image/png': {\n 'width': 123,\n 'height': 456\n }\n }\n },\n )\n # Latest ipykernel/IPython\n expected2 = expected + (\n {\n 'output_type': 'display_data',\n 'data': {\n 'image/png': 'Zm9vYmFy',\n 'text/plain': '<IPython.core.display.Image object>'\n },\n 'metadata': {\n 'image/png': {\n 'width': 123,\n 'height': 456\n }\n }\n },\n )\n assert widget.outputs == expected1 or widget.outputs == expected2\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_output.py
|
test_widget_output.py
|
Python
| 7,466 | 0.95 | 0.087866 | 0.072539 |
react-lib
| 851 |
2024-04-30T13:09:45.584562
|
GPL-3.0
| true |
aec80ae4711a6b00d11f1c712734dacc
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport inspect\nfrom unittest import TestCase\n\nfrom traitlets import TraitError\n\nfrom ipywidgets import Dropdown, SelectionSlider, Select\n\n\nclass TestDropdown(TestCase):\n\n def test_construction(self):\n Dropdown()\n\n def test_dict_mapping_options(self):\n d = Dropdown(options={'One': 1, 'Two': 2, 'Three': 3})\n assert d.get_state('_options_labels') == {'_options_labels': ('One', 'Two', 'Three')}\n\n def test_setting_options_from_list(self):\n d = Dropdown()\n assert d.options == ()\n d.options = ['One', 'Two', 'Three']\n assert d.get_state('_options_labels') == {'_options_labels': ('One', 'Two', 'Three')}\n\n def test_setting_options_from_list_tuples(self):\n d = Dropdown()\n assert d.options == ()\n d.options = [('One', 1), ('Two', 2), ('Three', 3)]\n assert d.get_state('_options_labels') == {'_options_labels': ('One', 'Two', 'Three')}\n d.value = 2\n assert d.get_state('index') == {'index': 1}\n\n def test_setting_options_from_dict(self):\n d = Dropdown()\n assert d.options == ()\n d.options = {'One': 1, 'Two': 2, 'Three': 3}\n assert d.get_state('_options_labels') == {'_options_labels': ('One', 'Two', 'Three')}\n\n\n\n\nclass TestSelectionSlider(TestCase):\n\n def test_construction(self):\n SelectionSlider(options=['a', 'b', 'c'])\n\n def test_index_trigger(self):\n slider = SelectionSlider(options=['a', 'b', 'c'])\n observations = []\n def f(change):\n observations.append(change.new)\n slider.observe(f, 'index')\n assert slider.index == 0\n slider.options = [4, 5, 6]\n assert slider.index == 0\n assert slider.value == 4\n assert slider.label == '4'\n assert observations == [0]\n\nclass TestSelection(TestCase):\n\n def test_construction(self):\n select = Select(options=['a', 'b', 'c'])\n\n def test_index_trigger(self):\n select = Select(options=[1, 2, 3])\n observations = []\n def f(change):\n observations.append(change.new)\n select.observe(f, 'index')\n assert select.index == 0\n select.options = [4, 5, 6]\n assert select.index == 0\n assert select.value == 4\n assert select.label == '4'\n assert observations == [0]\n\n def test_duplicate(self):\n select = Select(options=['first', 1, 'dup', 'dup'])\n observations = []\n def f(change):\n observations.append(change.new)\n select.observe(f, 'index')\n select.index = 3\n assert select.index == 3\n assert select.value == 'dup'\n assert select.label == 'dup'\n assert observations == [3]\n select.index = 2\n assert select.index == 2\n assert select.value == 'dup'\n assert select.label == 'dup'\n assert observations == [3, 2]\n select.index = 0\n assert select.index == 0\n assert select.value == 'first'\n assert select.label == 'first'\n assert observations == [3, 2, 0]\n\n # picks the first matching value\n select.value = 'dup'\n assert select.index == 2\n assert select.value == 'dup'\n assert select.label == 'dup'\n assert observations == [3, 2, 0, 2]\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_selection.py
|
test_widget_selection.py
|
Python
| 3,372 | 0.95 | 0.149533 | 0.034884 |
awesome-app
| 203 |
2024-03-04T23:26:51.273339
|
MIT
| true |
5b0b667c87fa3da8ce3faf17362bb910
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport inspect\nimport pytest\n\nfrom ..widget_string import Combobox, Text\n\ndef test_combobox_creation_blank():\n w = Combobox()\n assert w.value == ''\n assert w.options == ()\n assert w.ensure_option == False\n\n\ndef test_combobox_creation_kwargs():\n w = Combobox(\n value='Chocolate',\n options=[\n "Chocolate",\n "Coconut",\n "Mint",\n "Strawberry",\n "Vanilla",\n ],\n ensure_option=True\n )\n assert w.value == 'Chocolate'\n assert w.options == (\n "Chocolate",\n "Coconut",\n "Mint",\n "Strawberry",\n "Vanilla",\n )\n assert w.ensure_option == True\n\ndef test_tooltip_deprecation():\n caller_path = inspect.stack(context=0)[1].filename\n with pytest.deprecated_call() as record:\n w = Text(description_tooltip="testing")\n assert len(record) == 1\n assert record[0].filename == caller_path\n\n with pytest.deprecated_call() as record:\n w.description_tooltip\n assert len(record) == 1\n assert record[0].filename == caller_path\n\n with pytest.deprecated_call() as record:\n w.description_tooltip == "testing"\n assert len(record) == 1\n assert record[0].filename == caller_path\n\n with pytest.deprecated_call() as record:\n w.description_tooltip = "second value"\n assert len(record) == 1\n assert record[0].filename == caller_path\n assert w.tooltip == "second value"\n\ndef test_on_submit_deprecation():\n with pytest.deprecated_call() as record:\n Text().on_submit(lambda *args: ...)\n assert len(record) == 1\n assert record[0].filename == inspect.stack(context=0)[1].filename\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_string.py
|
test_widget_string.py
|
Python
| 1,796 | 0.95 | 0.061538 | 0.036364 |
python-kit
| 183 |
2025-05-19T05:29:44.869284
|
BSD-3-Clause
| true |
de9dd2206083ca45e54d214ca8784f49
|
"Testing widget layout templates"\n\nfrom unittest import TestCase\nfrom unittest import mock\n\nimport pytest\n\nimport traitlets\nimport ipywidgets as widgets\nfrom ipywidgets.widgets.widget_templates import LayoutProperties\n\nclass TestTwoByTwoLayout(TestCase):\n """test layout templates"""\n\n def test_merge_cells(self): #pylint: disable=no-self-use\n """test merging cells with missing widgets"""\n\n button1 = widgets.Button()\n button2 = widgets.Button()\n button3 = widgets.Button()\n button4 = widgets.Button()\n\n box = widgets.TwoByTwoLayout(top_left=button1,\n top_right=button2,\n bottom_left=button3,\n bottom_right=button4)\n\n assert box.layout.grid_template_areas == ('"top-left top-right"\n' +\n '"bottom-left bottom-right"')\n assert box.top_left.layout.grid_area == 'top-left'\n assert box.top_right.layout.grid_area == 'top-right'\n assert box.bottom_left.layout.grid_area == 'bottom-left'\n assert box.bottom_right.layout.grid_area == 'bottom-right'\n assert len(box.get_state()['children']) == 4\n\n box = widgets.TwoByTwoLayout(top_left=button1,\n top_right=button2,\n bottom_left=None,\n bottom_right=button4)\n\n assert box.layout.grid_template_areas == ('"top-left top-right"\n' +\n '"top-left bottom-right"')\n assert box.top_left.layout.grid_area == 'top-left'\n assert box.top_right.layout.grid_area == 'top-right'\n assert box.bottom_left is None\n assert box.bottom_right.layout.grid_area == 'bottom-right'\n assert len(box.get_state()['children']) == 3\n\n box = widgets.TwoByTwoLayout(top_left=None,\n top_right=button2,\n bottom_left=button3,\n bottom_right=button4)\n\n assert box.layout.grid_template_areas == ('"bottom-left top-right"\n' +\n '"bottom-left bottom-right"')\n assert box.top_left is None\n assert box.top_right.layout.grid_area == 'top-right'\n assert box.bottom_left.layout.grid_area == 'bottom-left'\n assert box.bottom_right.layout.grid_area == 'bottom-right'\n assert len(box.get_state()['children']) == 3\n\n box = widgets.TwoByTwoLayout(top_left=None,\n top_right=button2,\n bottom_left=None,\n bottom_right=button4)\n\n assert box.layout.grid_template_areas == ('"top-right top-right"\n' +\n '"bottom-right bottom-right"')\n assert box.top_left is None\n assert box.top_right.layout.grid_area == 'top-right'\n assert box.bottom_left is None\n assert box.bottom_right.layout.grid_area == 'bottom-right'\n assert len(box.get_state()['children']) == 2\n\n box = widgets.TwoByTwoLayout(top_left=button1,\n top_right=None,\n bottom_left=button3,\n bottom_right=button4)\n\n assert box.layout.grid_template_areas == ('"top-left bottom-right"\n' +\n '"bottom-left bottom-right"')\n assert box.top_left.layout.grid_area == 'top-left'\n assert box.top_right is None\n assert box.bottom_left.layout.grid_area == 'bottom-left'\n assert box.bottom_right.layout.grid_area == 'bottom-right'\n assert len(box.get_state()['children']) == 3\n\n\n box = widgets.TwoByTwoLayout(top_left=button1,\n top_right=None,\n bottom_left=None,\n bottom_right=None)\n\n assert box.layout.grid_template_areas == ('"top-left top-left"\n' +\n '"top-left top-left"')\n\n assert box.top_left is button1\n assert box.top_left.layout.grid_area == 'top-left'\n assert box.top_right is None\n assert box.bottom_left is None\n assert box.bottom_right is None\n assert len(box.get_state()['children']) == 1\n\n box = widgets.TwoByTwoLayout(top_left=None,\n top_right=button1,\n bottom_left=None,\n bottom_right=None)\n\n assert box.layout.grid_template_areas == ('"top-right top-right"\n' +\n '"top-right top-right"')\n\n assert box.top_right is button1\n assert box.top_right.layout.grid_area == 'top-right'\n assert box.top_left is None\n assert box.bottom_left is None\n assert box.bottom_right is None\n assert len(box.get_state()['children']) == 1\n\n box = widgets.TwoByTwoLayout(top_left=None,\n top_right=None,\n bottom_left=None,\n bottom_right=None)\n\n assert box.layout.grid_template_areas is None\n assert box.top_left is None\n assert box.top_right is None\n assert box.bottom_left is None\n assert box.bottom_right is None\n assert not box.get_state()['children']\n\n box = widgets.TwoByTwoLayout(top_left=None,\n top_right=button1,\n bottom_left=None,\n bottom_right=None,\n merge=False)\n\n assert box.layout.grid_template_areas == ('"top-left top-right"\n' +\n '"bottom-left bottom-right"')\n\n assert box.top_right is button1\n assert box.top_right.layout.grid_area == 'top-right'\n assert box.top_left is None\n assert box.bottom_left is None\n assert box.bottom_right is None\n assert len(box.get_state()['children']) == 1\n\n def test_keep_layout_options(self): #pylint: disable=no-self-use\n """test whether layout options are passed down to GridBox"""\n\n layout = widgets.Layout(align_items="center")\n button1 = widgets.Button()\n button2 = widgets.Button()\n button3 = widgets.Button()\n button4 = widgets.Button()\n\n box = widgets.TwoByTwoLayout(top_left=button1, top_right=button2,\n bottom_left=button3, bottom_right=button4,\n layout=layout)\n\n assert box.layout.align_items == 'center'\n\n def test_pass_layout_options(self): #pylint: disable=no-self-use\n """test whether the extra layout options of the template class are\n passed down to Layout object"""\n\n button1 = widgets.Button()\n button2 = widgets.Button()\n button3 = widgets.Button()\n button4 = widgets.Button()\n\n box = widgets.TwoByTwoLayout(top_left=button1, top_right=button2,\n bottom_left=button3, bottom_right=button4,\n grid_gap="10px", justify_content="center",\n align_items="center")\n\n assert box.layout.grid_gap == "10px"\n assert box.layout.justify_content == "center"\n assert box.layout.align_items == "center"\n\n # we still should be able to pass them through layout\n layout = widgets.Layout(grid_gap="10px", justify_content="center",\n align_items="center")\n box = widgets.TwoByTwoLayout(top_left=button1, top_right=button2,\n bottom_left=button3, bottom_right=button4,\n layout=layout\n )\n\n assert box.layout.grid_gap == "10px"\n assert box.layout.justify_content == "center"\n assert box.layout.align_items == "center"\n\n # values passed directly in the constructor should overwrite layout options\n layout = widgets.Layout(grid_gap="10px", justify_content="center",\n align_items="center")\n box = widgets.TwoByTwoLayout(top_left=button1, top_right=button2,\n bottom_left=button3, bottom_right=button4,\n layout=layout, grid_gap="30px"\n )\n\n assert box.layout.grid_gap == "30px"\n assert box.layout.justify_content == "center"\n assert box.layout.align_items == "center"\n\n\n @mock.patch("ipywidgets.Layout.send_state")\n def test_update_dynamically(self, send_state): #pylint: disable=no-self-use\n """test whether it's possible to add widget outside __init__"""\n\n button1 = widgets.Button()\n button2 = widgets.Button()\n button3 = widgets.Button()\n button4 = widgets.Button()\n\n box = widgets.TwoByTwoLayout(top_left=button1, top_right=button3,\n bottom_left=None, bottom_right=button4)\n from ipykernel.kernelbase import Kernel\n\n state = box.get_state()\n assert len(state['children']) == 3\n assert box.layout.grid_template_areas == ('"top-left top-right"\n' +\n '"top-left bottom-right"')\n\n box.layout.comm.kernel = mock.MagicMock(spec=Kernel) #for mocking purposes\n send_state.reset_mock()\n box.bottom_left = button2\n\n state = box.get_state()\n assert len(state['children']) == 4\n assert box.layout.grid_template_areas == ('"top-left top-right"\n' +\n '"bottom-left bottom-right"')\n # check whether frontend was informed\n send_state.assert_called_with(key="grid_template_areas")\n\n box = widgets.TwoByTwoLayout(top_left=button1, top_right=button3,\n bottom_left=None, bottom_right=button4)\n assert box.layout.grid_template_areas == ('"top-left top-right"\n' +\n '"top-left bottom-right"')\n box.layout.comm.kernel = mock.MagicMock(spec=Kernel) #for mocking purposes\n send_state.reset_mock()\n box.merge = False\n assert box.layout.grid_template_areas == ('"top-left top-right"\n' +\n '"bottom-left bottom-right"')\n send_state.assert_called_with(key="grid_template_areas")\n\n\nclass TestAppLayout(TestCase):\n """test layout templates"""\n\n def test_create_with_defaults(self):\n "test creating with default values"\n\n footer = widgets.Button()\n header = widgets.Button()\n center = widgets.Button()\n left_sidebar = widgets.Button()\n right_sidebar = widgets.Button()\n\n box = widgets.AppLayout(\n footer=footer,\n header=header,\n center=center,\n left_sidebar=left_sidebar,\n right_sidebar=right_sidebar\n )\n\n assert box.layout.grid_template_areas == ('"header header header"\n' +\n '"left-sidebar center right-sidebar"\n' +\n '"footer footer footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.center.layout.grid_area == 'center'\n assert box.left_sidebar.layout.grid_area == 'left-sidebar'\n assert box.right_sidebar.layout.grid_area == 'right-sidebar'\n\n assert len(box.get_state()['children']) == 5\n\n # empty layout should produce no effects\n\n box = widgets.AppLayout()\n assert box.layout.grid_template_areas is None\n assert box.layout.grid_template_columns is None\n assert box.layout.grid_template_rows is None\n assert len(box.get_state()['children']) == 0\n\n\n def test_merge_empty_cells(self):\n "test if cells are correctly merged"\n\n footer = widgets.Button()\n header = widgets.Button()\n center = widgets.Button()\n left_sidebar = widgets.Button()\n right_sidebar = widgets.Button()\n\n # merge all if only one widget\n box = widgets.AppLayout(\n center=center\n )\n\n assert box.layout.grid_template_areas == ('"center center center"\n' +\n '"center center center"\n' +\n '"center center center"')\n assert box.center.layout.grid_area == 'center'\n\n assert len(box.get_state()['children']) == 1\n\n box = widgets.AppLayout(\n left_sidebar=left_sidebar\n )\n\n assert box.layout.grid_template_areas == ('"left-sidebar left-sidebar left-sidebar"\n' +\n '"left-sidebar left-sidebar left-sidebar"\n' +\n '"left-sidebar left-sidebar left-sidebar"')\n assert box.left_sidebar.layout.grid_area == 'left-sidebar'\n\n assert len(box.get_state()['children']) == 1\n\n # merge left and right sidebars with center\n\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n left_sidebar=left_sidebar,\n center=center\n )\n\n assert box.layout.grid_template_areas == ('"header header header"\n' +\n '"left-sidebar center center"\n' +\n '"footer footer footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.center.layout.grid_area == 'center'\n assert box.left_sidebar.layout.grid_area == 'left-sidebar'\n assert len(box.get_state()['children']) == 4\n\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n right_sidebar=right_sidebar,\n center=center\n )\n\n assert box.layout.grid_template_areas == ('"header header header"\n' +\n '"center center right-sidebar"\n' +\n '"footer footer footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.center.layout.grid_area == 'center'\n assert box.right_sidebar.layout.grid_area == 'right-sidebar'\n assert len(box.get_state()['children']) == 4\n\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n center=center\n )\n\n assert box.layout.grid_template_areas == ('"header header header"\n' +\n '"center center center"\n' +\n '"footer footer footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.center.layout.grid_area == 'center'\n assert len(box.get_state()['children']) == 3\n\n # if only center missing, remove it from view\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n center=None,\n left_sidebar=left_sidebar,\n right_sidebar=right_sidebar\n )\n\n assert box.layout.grid_template_areas == ('"header header"\n' +\n '"left-sidebar right-sidebar"\n' +\n '"footer footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.left_sidebar.layout.grid_area == 'left-sidebar'\n assert box.right_sidebar.layout.grid_area == 'right-sidebar'\n assert box.center is None\n assert len(box.get_state()['children']) == 4\n\n # center and one sidebar missing -> 3 row arrangement\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n center=None,\n left_sidebar=None,\n right_sidebar=right_sidebar\n )\n\n assert box.layout.grid_template_areas == ('"header header"\n' +\n '"right-sidebar right-sidebar"\n' +\n '"footer footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.left_sidebar is None\n assert box.right_sidebar.layout.grid_area == 'right-sidebar'\n assert box.center is None\n assert len(box.get_state()['children']) == 3\n\n\n # remove middle row is both sidebars and center missing\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n center=None,\n left_sidebar=None,\n right_sidebar=None\n )\n\n assert box.layout.grid_template_areas == ('"header"\n' +\n '"footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.center is None\n assert box.left_sidebar is None\n assert box.right_sidebar is None\n assert len(box.get_state()['children']) == 2\n\n\n\n # do not merge if merge=False\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n center=center,\n merge=False\n )\n\n assert box.layout.grid_template_areas == ('"header header header"\n' +\n '"left-sidebar center right-sidebar"\n' +\n '"footer footer footer"')\n assert box.footer.layout.grid_area == 'footer'\n assert box.header.layout.grid_area == 'header'\n assert box.center.layout.grid_area == 'center'\n assert box.left_sidebar is None\n assert box.right_sidebar is None\n assert len(box.get_state()['children']) == 3\n\n # merge header and footer simply removes it from view\n box = widgets.AppLayout(\n footer=footer,\n center=center,\n left_sidebar=left_sidebar,\n right_sidebar=right_sidebar\n )\n\n assert box.layout.grid_template_areas == ('"left-sidebar center right-sidebar"\n' +\n '"footer footer footer"')\n assert box.center.layout.grid_area == 'center'\n assert box.left_sidebar.layout.grid_area == 'left-sidebar'\n assert box.right_sidebar.layout.grid_area == 'right-sidebar'\n assert box.footer.layout.grid_area == 'footer'\n assert box.header is None\n assert len(box.get_state()['children']) == 4\n\n box = widgets.AppLayout(\n header=header,\n center=center,\n left_sidebar=left_sidebar,\n right_sidebar=right_sidebar\n )\n\n assert box.layout.grid_template_areas == ('"header header header"\n' +\n '"left-sidebar center right-sidebar"')\n assert box.center.layout.grid_area == 'center'\n assert box.left_sidebar.layout.grid_area == 'left-sidebar'\n assert box.right_sidebar.layout.grid_area == 'right-sidebar'\n assert box.header.layout.grid_area == 'header'\n assert box.footer is None\n assert len(box.get_state()['children']) == 4\n\n box = widgets.AppLayout(\n center=center,\n left_sidebar=left_sidebar,\n right_sidebar=right_sidebar\n )\n\n assert box.layout.grid_template_areas == '"left-sidebar center right-sidebar"'\n assert box.center.layout.grid_area == 'center'\n assert box.left_sidebar.layout.grid_area == 'left-sidebar'\n assert box.right_sidebar.layout.grid_area == 'right-sidebar'\n assert box.footer is None\n assert box.header is None\n assert len(box.get_state()['children']) == 3\n\n # merge all if only one widget\n box = widgets.AppLayout(\n center=center\n )\n\n assert box.layout.grid_template_areas == ('"center center center"\n' +\n '"center center center"\n' +\n '"center center center"')\n assert box.center.layout.grid_area == 'center'\n\n assert len(box.get_state()['children']) == 1\n\n def test_size_to_css(self):\n\n box = widgets.AppLayout()\n assert box._size_to_css("100px") == '100px'\n assert box._size_to_css("1fr") == '1fr'\n assert box._size_to_css("2.5fr") == '2.5fr'\n assert box._size_to_css('2.5') == '2.5fr'\n assert box._size_to_css('25%') == '25%'\n\n with pytest.raises(TypeError):\n box._size_to_css('this is not correct size')\n\n\n def test_set_pane_widths_heights(self):\n\n footer = widgets.Button()\n header = widgets.Button()\n center = widgets.Button()\n left_sidebar = widgets.Button()\n right_sidebar = widgets.Button()\n\n box = widgets.AppLayout(\n header=header,\n footer=footer,\n left_sidebar=left_sidebar,\n right_sidebar=left_sidebar,\n center=center\n )\n\n with pytest.raises(traitlets.TraitError):\n box.pane_widths = ['1fx', '1fx', '1fx', '1fx']\n with pytest.raises(traitlets.TraitError):\n box.pane_widths = ['1fx', '1fx']\n\n with pytest.raises(traitlets.TraitError):\n box.pane_heights = ['1fx', '1fx', '1fx', '1fx']\n with pytest.raises(traitlets.TraitError):\n box.pane_heights = ['1fx', '1fx']\n\n assert box.layout.grid_template_rows == "1fr 3fr 1fr"\n assert box.layout.grid_template_columns == "1fr 2fr 1fr"\n\n box.pane_heights = ['3fr', '100px', 20]\n assert box.layout.grid_template_rows == "3fr 100px 20fr"\n assert box.layout.grid_template_columns == "1fr 2fr 1fr"\n\n box.pane_widths = [3, 3, 1]\n assert box.layout.grid_template_rows == "3fr 100px 20fr"\n assert box.layout.grid_template_columns == "3fr 3fr 1fr"\n\nclass TestGridspecLayout(TestCase):\n "test GridspecLayout"\n\n def test_init(self):\n with pytest.raises(traitlets.TraitError):\n box = widgets.GridspecLayout()\n\n with pytest.raises(traitlets.TraitError):\n box = widgets.GridspecLayout(n_rows=-1, n_columns=1)\n\n box = widgets.GridspecLayout(n_rows=5, n_columns=3)\n assert box.n_rows == 5\n assert box.n_columns == 3\n assert len(box._grid_template_areas) == 5\n assert len(box._grid_template_areas[0]) == 3\n\n box = widgets.GridspecLayout(1, 2)\n assert box.n_rows == 1\n assert box.n_columns == 2\n\n with pytest.raises(traitlets.TraitError):\n box = widgets.GridspecLayout(0, 0)\n\n def test_setitem_index(self):\n\n box = widgets.GridspecLayout(2, 3)\n button1 = widgets.Button()\n button2 = widgets.Button()\n button3 = widgets.Button()\n button4 = widgets.Button()\n\n box[0, 0] = button1\n button1_label = button1.layout.grid_area\n assert button1 in box.children\n assert box.layout.grid_template_areas == '''"{} . ."\n". . ."'''.format(button1_label)\n\n box[-1, -1] = button2\n button2_label = button2.layout.grid_area\n assert button1_label != button2_label\n assert button2 in box.children\n assert box.layout.grid_template_areas == '''"{} . ."\n". . {}"'''.format(button1_label,\n button2_label)\n\n box[1, 0] = button3\n button3_label = button3.layout.grid_area\n assert button1_label != button3_label\n assert button2_label != button3_label\n assert button3 in box.children\n assert box.layout.grid_template_areas == '''"{b1} . ."\n"{b3} . {b2}"'''.format(b1=button1_label,\n b2=button2_label,\n b3=button3_label)\n\n #replace widget\n box[1, 0] = button4\n button4_label = button4.layout.grid_area\n assert button1_label != button4_label\n assert button2_label != button4_label\n assert button4 in box.children\n assert button3 not in box.children\n\n assert box.layout.grid_template_areas == '''"{b1} . ."\n"{b4} . {b2}"'''.format(b1=button1_label,\n b2=button2_label,\n b4=button4_label)\n\n def test_setitem_slices(self):\n\n box = widgets.GridspecLayout(2, 3)\n button1 = widgets.Button()\n\n box[:2, 0] = button1\n assert len(box.children) == 1\n assert button1 in box.children\n button1_label = button1.layout.grid_area\n\n assert box.layout.grid_template_areas == '''"{b1} . ."\n"{b1} . ."'''.format(b1=button1_label)\n\n box = widgets.GridspecLayout(2, 3)\n button1 = widgets.Button()\n button2 = widgets.Button()\n\n box[:2, 1:] = button1\n assert len(box.children) == 1\n assert button1 in box.children\n button1_label = button1.layout.grid_area\n\n assert box.layout.grid_template_areas == '''". {b1} {b1}"\n". {b1} {b1}"'''.format(b1=button1_label)\n\n # replace button\n box[:2, 1:] = button2\n assert len(box.children) == 1\n assert button2 in box.children\n button2_label = button2.layout.grid_area\n\n assert box.layout.grid_template_areas == '''". {b1} {b1}"\n". {b1} {b1}"'''.format(b1=button2_label)\n\n def test_getitem_index(self):\n "test retrieving widget"\n\n box = widgets.GridspecLayout(2, 3)\n button1 = widgets.Button()\n\n box[0, 0] = button1\n\n assert box[0, 0] is button1\n\n def test_getitem_slices(self):\n "test retrieving widgets with slices"\n\n box = widgets.GridspecLayout(2, 3)\n button1 = widgets.Button()\n\n box[:2, 0] = button1\n assert box[:2, 0] is button1\n\n box = widgets.GridspecLayout(2, 3)\n button1 = widgets.Button()\n button2 = widgets.Button()\n\n box[0, 0] = button1\n box[1, 0] = button2\n assert box[0, 0] is button1\n assert box[1, 0] is button2\n\n with pytest.raises(TypeError, match="The slice spans"):\n button = box[:2, 0]\n\n\nclass TestLayoutProperties(TestCase):\n """test mixin with layout properties"""\n\n class DummyTemplate(widgets.GridBox, LayoutProperties):\n location = traitlets.Instance(widgets.Widget, allow_none=True)\n\n def test_layout_updated_on_trait_change(self):\n "test whether respective layout traits are updated when traits change"\n\n template = self.DummyTemplate(width="100%")\n assert template.width == '100%'\n assert template.layout.width == '100%'\n\n template.width = 'auto'\n assert template.width == 'auto'\n assert template.layout.width == 'auto'\n\n def test_align_items_extra_options(self):\n\n template = self.DummyTemplate(align_items='top')\n assert template.align_items == 'top'\n assert template.layout.align_items == 'flex-start'\n\n template.align_items = 'bottom'\n assert template.align_items == 'bottom'\n assert template.layout.align_items == 'flex-end'\n\n def test_validate_properties(self):\n\n prop_obj = self.DummyTemplate()\n for prop in LayoutProperties.align_items.values:\n prop_obj.align_items = prop\n assert prop_obj.align_items == prop\n\n with pytest.raises(traitlets.TraitError):\n prop_obj.align_items = 'any default position'\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_templates.py
|
test_widget_templates.py
|
Python
| 28,435 | 0.95 | 0.042017 | 0.024779 |
awesome-app
| 398 |
2025-04-06T14:35:05.824458
|
Apache-2.0
| true |
3d0fc1944d8f1b82957aceb1b8e33e51
|
# coding: utf-8\n\n# Copyright (c) Vidar Tonaas Fauske.\n# Distributed under the terms of the Modified BSD License.\n\nimport pytest\n\nimport datetime\n\nfrom traitlets import TraitError\n\nfrom ..widget_time import TimePicker\n\n\ndef test_time_creation_blank():\n w = TimePicker()\n assert w.value is None\n\n\ndef test_time_creation_value():\n t = datetime.time()\n w = TimePicker(value=t)\n assert w.value is t\n\n\ndef test_time_cross_validate_value_min_max():\n w = TimePicker(value=datetime.time(2), min=datetime.time(2), max=datetime.time(2))\n with w.hold_trait_notifications():\n w.value = None\n w.min = datetime.time(4)\n w.max = datetime.time(6)\n assert w.value is None\n with w.hold_trait_notifications():\n w.value = datetime.time(4)\n w.min = None\n w.max = None\n assert w.value == datetime.time(4)\n\n\ndef test_time_validate_value_none():\n t = datetime.time(13, 37, 42, 7)\n t_min = datetime.time(2)\n t_max = datetime.time(22)\n w = TimePicker(value=t, min=t_min, max=t_max)\n w.value = None\n assert w.value is None\n\n\ndef test_time_validate_value_vs_min():\n t = datetime.time(13, 37, 42, 7)\n t_min = datetime.time(14)\n t_max = datetime.time(22)\n w = TimePicker(min=t_min, max=t_max)\n w.value = t\n assert w.value.hour == 14\n\n\ndef test_time_validate_value_vs_max():\n t = datetime.time(13, 37, 42, 7)\n t_min = datetime.time(2)\n t_max = datetime.time(12)\n w = TimePicker(min=t_min, max=t_max)\n w.value = t\n assert w.value.hour == 12\n\n\ndef test_time_validate_min_vs_value():\n t = datetime.time(13, 37, 42, 7)\n t_min = datetime.time(14)\n t_max = datetime.time(22)\n w = TimePicker(value=t, max=t_max)\n w.min = t_min\n assert w.value.hour == 14\n\n\ndef test_time_validate_min_vs_max():\n t = datetime.time(13, 37, 42, 7)\n t_min = datetime.time(14)\n t_max = datetime.time(12)\n w = TimePicker(value=t, max=t_max)\n with pytest.raises(TraitError):\n w.min = t_min\n\n\ndef test_time_validate_max_vs_value():\n t = datetime.time(13, 37, 42, 7)\n t_min = datetime.time(2)\n t_max = datetime.time(12)\n w = TimePicker(value=t, min=t_min)\n w.max = t_max\n assert w.value.hour == 12\n\n\ndef test_time_validate_max_vs_min():\n t = datetime.time(13, 37, 42, 7)\n t_min = datetime.time(2)\n t_max = datetime.time(1)\n w = TimePicker(value=t, min=t_min)\n with pytest.raises(TraitError):\n w.max = t_max\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_time.py
|
test_widget_time.py
|
Python
| 2,447 | 0.95 | 0.1 | 0.04 |
react-lib
| 746 |
2025-02-27T11:12:20.997813
|
BSD-3-Clause
| true |
b5a29ad3577b67f74abfa77db709ef24
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport datetime as dt\nfrom unittest import TestCase\nfrom unittest.mock import MagicMock\n\nfrom traitlets import TraitError\n\nfrom ipywidgets import FileUpload\n\n\nFILE_UPLOAD_FRONTEND_CONTENT = {\n 'name': 'file-name.txt',\n 'type': 'text/plain',\n 'size': 20760,\n 'last_modified': 1578578296434,\n 'content': memoryview(b'file content'),\n}\n\n\nclass TestFileUpload(TestCase):\n\n def test_construction(self):\n uploader = FileUpload()\n # Default\n assert uploader.accept == ''\n assert not uploader.multiple\n assert not uploader.disabled\n\n def test_construction_with_params(self):\n uploader = FileUpload(\n accept='.txt', multiple=True, disabled=True)\n assert uploader.accept == '.txt'\n assert uploader.multiple\n assert uploader.disabled\n\n def test_empty_initial_value(self):\n uploader = FileUpload()\n assert uploader.value == ()\n\n def test_receive_single_file(self):\n uploader = FileUpload()\n message = {'value': [FILE_UPLOAD_FRONTEND_CONTENT]}\n uploader.set_state(message)\n assert len(uploader.value) == 1\n (uploaded_file,) = uploader.value\n assert uploaded_file.name == 'file-name.txt'\n assert uploaded_file.type == 'text/plain'\n assert uploaded_file.size == 20760\n assert uploaded_file.content.tobytes() == b'file content'\n assert (\n uploaded_file.last_modified ==\n dt.datetime(2020, 1, 9, 13, 58, 16, 434000, tzinfo=dt.timezone.utc)\n )\n\n def test_receive_multiple_files(self):\n uploader = FileUpload(multiple=True)\n message = {\n 'value': [\n FILE_UPLOAD_FRONTEND_CONTENT,\n {**FILE_UPLOAD_FRONTEND_CONTENT, **{'name': 'other-file-name.txt'}}\n ]\n }\n uploader.set_state(message)\n assert len(uploader.value) == 2\n assert uploader.value[0].name == 'file-name.txt'\n assert uploader.value[1].name == 'other-file-name.txt'\n\n def test_serialization_deserialization_integrity(self):\n # The value traitlet needs to remain unchanged following\n # a serialization / deserialization roundtrip, otherwise\n # the kernel dispatches it back to the frontend following\n # a state change, because it doesn't recognize that the\n # property_lock entry is the same as the new value.\n from ipykernel.comm import Comm\n uploader = FileUpload()\n mock_comm = MagicMock(spec=Comm)\n mock_comm.send = MagicMock()\n mock_comm.kernel = 'does not matter'\n uploader.comm = mock_comm\n message = {'value': [FILE_UPLOAD_FRONTEND_CONTENT]}\n uploader.set_state(message)\n\n # Check that no message is sent back to the frontend\n # as a result of setting the state.\n mock_comm.send.assert_not_called()\n\n def test_resetting_value(self):\n # Simulate an upload, then resetting the value from the\n # kernel.\n uploader = FileUpload()\n message = {'value': [FILE_UPLOAD_FRONTEND_CONTENT]}\n uploader.set_state(message)\n\n uploader.value = [] # reset value to an empty file list\n\n assert uploader.get_state(key='value') == {'value': []}\n\n def test_setting_non_empty_value(self):\n # Simulate user setting a value for the upload from the kernel.\n uploader = FileUpload()\n content = memoryview(b'some content')\n uploader.value = [{\n 'name': 'some-name.txt',\n 'type': 'text/plain',\n 'size': 561,\n 'last_modified': dt.datetime(2020, 1, 9, 13, 58, 16, 434000, tzinfo=dt.timezone.utc),\n 'content': content\n }]\n state = uploader.get_state(key='value')\n assert len(state['value']) == 1\n [entry] = state['value']\n assert entry['name'] == 'some-name.txt'\n assert entry['type'] == 'text/plain'\n assert entry['size'] == 561\n assert entry['last_modified'] == 1578578296434\n assert entry['content'] == content\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\test_widget_upload.py
|
test_widget_upload.py
|
Python
| 4,164 | 0.95 | 0.084746 | 0.13 |
awesome-app
| 458 |
2023-11-11T22:42:37.814692
|
GPL-3.0
| true |
a269b07028b17f5946945e39d4f8bd32
|
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom ipywidgets import Widget\nimport ipywidgets.widgets.widget\n\n# The new comm package is not available in our Python 3.7 CI (older ipykernel version)\ntry:\n import comm\n NEW_COMM_PACKAGE = True\nexcept ImportError:\n NEW_COMM_PACKAGE = False\n\nimport ipykernel.comm\nimport pytest\n\nclass DummyComm():\n comm_id = 'a-b-c-d'\n kernel = 'Truthy'\n\n def __init__(self, *args, **kwargs):\n super().__init__()\n self.messages = []\n\n def open(self, *args, **kwargs):\n pass\n\n def on_msg(self, *args, **kwargs):\n pass\n\n def send(self, *args, **kwargs):\n self.messages.append((args, kwargs))\n\n def close(self, *args, **kwargs):\n pass\n\n\ndef dummy_create_comm(**kwargs):\n return DummyComm()\n\n\ndef dummy_get_comm_manager(**kwargs):\n return {}\n\n\n_widget_attrs = {}\nundefined = object()\n\nif NEW_COMM_PACKAGE:\n orig_comm = ipykernel.comm.comm.BaseComm\nelse:\n orig_comm = ipykernel.comm.Comm\norig_create_comm = None\norig_get_comm_manager = None\n\nif NEW_COMM_PACKAGE:\n orig_create_comm = comm.create_comm\n orig_get_comm_manager = comm.get_comm_manager\n\ndef setup_test_comm():\n if NEW_COMM_PACKAGE:\n comm.create_comm = dummy_create_comm\n comm.get_comm_manager = dummy_get_comm_manager\n ipykernel.comm.comm.BaseComm = DummyComm\n else:\n ipykernel.comm.Comm = DummyComm\n Widget.comm.klass = DummyComm\n ipywidgets.widgets.widget.Comm = DummyComm\n _widget_attrs['_repr_mimebundle_'] = Widget._repr_mimebundle_\n def raise_not_implemented(*args, **kwargs):\n raise NotImplementedError()\n Widget._repr_mimebundle_ = raise_not_implemented\n\ndef teardown_test_comm():\n if NEW_COMM_PACKAGE:\n comm.create_comm = orig_create_comm\n comm.get_comm_manager = orig_get_comm_manager\n ipykernel.comm.comm.BaseComm = orig_comm\n else:\n ipykernel.comm.Comm = orig_comm\n Widget.comm.klass = orig_comm\n ipywidgets.widgets.widget.Comm = orig_comm\n for attr, value in _widget_attrs.items():\n if value is undefined:\n delattr(Widget, attr)\n else:\n setattr(Widget, attr, value)\n _widget_attrs.clear()\n\n@pytest.fixture(autouse=True)\ndef setup():\n setup_test_comm()\n yield\n teardown_test_comm()\n\ndef call_method(method, *args, **kwargs):\n method(*args, **kwargs)\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\utils.py
|
utils.py
|
Python
| 2,443 | 0.95 | 0.206186 | 0.039474 |
react-lib
| 119 |
2024-10-28T11:50:57.817491
|
Apache-2.0
| true |
73296d6c75db5e0b26b92c686512767b
|
PNG\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\data\jupyter-logo-transparent.png
|
jupyter-logo-transparent.png
|
Other
| 36,297 | 0.8 | 0.003584 | 0.017986 |
node-utils
| 35 |
2023-07-23T21:17:52.187361
|
GPL-3.0
| true |
233734ccf0c974fcb8f01ae01cf8ec8d
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_datetime_serializers.cpython-313.pyc
|
test_datetime_serializers.cpython-313.pyc
|
Other
| 3,309 | 0.8 | 0 | 0 |
python-kit
| 646 |
2024-05-11T01:39:46.821563
|
Apache-2.0
| true |
fa9436c0dc88cef32d7ff174e9c300e3
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_docutils.cpython-313.pyc
|
test_docutils.cpython-313.pyc
|
Other
| 1,446 | 0.7 | 0 | 0 |
react-lib
| 333 |
2023-10-17T16:20:33.623412
|
GPL-3.0
| true |
0fa6f68e14065fa9fde5903f9b80e6a5
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_interaction.cpython-313.pyc
|
test_interaction.cpython-313.pyc
|
Other
| 31,014 | 0.95 | 0 | 0.07037 |
node-utils
| 210 |
2024-08-26T19:37:16.684158
|
GPL-3.0
| true |
acec914a029e638cbaae9c24625fee1e
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_link.cpython-313.pyc
|
test_link.cpython-313.pyc
|
Other
| 2,250 | 0.7 | 0 | 0 |
awesome-app
| 532 |
2023-12-05T00:14:47.101709
|
BSD-3-Clause
| true |
a1a2096dad752a1107185424e06ec2e5
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_selectioncontainer.cpython-313.pyc
|
test_selectioncontainer.cpython-313.pyc
|
Other
| 9,335 | 0.8 | 0 | 0.126984 |
vue-tools
| 700 |
2024-09-01T19:24:27.496772
|
BSD-3-Clause
| true |
d29b8c8b350683b5fb85ff9341d2f76f
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_send_state.cpython-313.pyc
|
test_send_state.cpython-313.pyc
|
Other
| 1,644 | 0.8 | 0 | 0 |
awesome-app
| 925 |
2024-12-15T01:01:27.912166
|
BSD-3-Clause
| true |
ccc5a6d544a332d64887cd9419db4792
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_set_state.cpython-313.pyc
|
test_set_state.cpython-313.pyc
|
Other
| 16,766 | 0.8 | 0 | 0.007092 |
awesome-app
| 609 |
2023-12-19T05:00:47.006822
|
Apache-2.0
| true |
e067fc0146b16b8a99f8dd146717e5dd
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_traits.cpython-313.pyc
|
test_traits.cpython-313.pyc
|
Other
| 12,464 | 0.8 | 0 | 0.054795 |
python-kit
| 781 |
2024-02-04T23:19:38.601964
|
Apache-2.0
| true |
e0ac08abbffbde6dd3a269119117a9ad
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_utils.cpython-313.pyc
|
test_utils.cpython-313.pyc
|
Other
| 4,326 | 0.8 | 0 | 0.166667 |
awesome-app
| 450 |
2023-08-23T15:05:16.003245
|
MIT
| true |
095269b2bd001d7682b8f1f97f583788
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget.cpython-313.pyc
|
test_widget.cpython-313.pyc
|
Other
| 5,683 | 0.8 | 0 | 0 |
react-lib
| 961 |
2024-03-25T19:09:57.529087
|
Apache-2.0
| true |
8b131f09b142d457c7177dbdb6b86660
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_box.cpython-313.pyc
|
test_widget_box.cpython-313.pyc
|
Other
| 2,245 | 0.8 | 0 | 0.136364 |
node-utils
| 149 |
2024-04-15T18:36:02.845416
|
Apache-2.0
| true |
43b493af895a5b04cecce81fc47f7c0a
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_button.cpython-313.pyc
|
test_widget_button.cpython-313.pyc
|
Other
| 866 | 0.7 | 0 | 0 |
node-utils
| 170 |
2025-04-20T02:36:45.869543
|
MIT
| true |
2810652933c8e13c0aa87de84e74f554
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_datetime.cpython-313.pyc
|
test_widget_datetime.cpython-313.pyc
|
Other
| 7,640 | 0.8 | 0 | 0.061856 |
react-lib
| 791 |
2024-05-12T08:23:20.425816
|
GPL-3.0
| true |
89f1433918ab7817d34f63cb09f7b1d1
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_float.cpython-313.pyc
|
test_widget_float.cpython-313.pyc
|
Other
| 1,457 | 0.7 | 0 | 0.176471 |
vue-tools
| 841 |
2023-09-23T08:41:01.779905
|
GPL-3.0
| true |
dd87a1fdba71dc119b02efa68a7056b8
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_image.cpython-313.pyc
|
test_widget_image.cpython-313.pyc
|
Other
| 8,126 | 0.8 | 0 | 0 |
python-kit
| 325 |
2023-10-12T10:23:18.575515
|
MIT
| true |
b0022bbe6ddc97d40e9bfb79cb9a66b0
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_naive_datetime.cpython-313.pyc
|
test_widget_naive_datetime.cpython-313.pyc
|
Other
| 5,052 | 0.8 | 0 | 0.066667 |
vue-tools
| 126 |
2023-08-16T13:59:51.918354
|
BSD-3-Clause
| true |
716bc852cc252feffc53c44628dc3fd2
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_output.cpython-313.pyc
|
test_widget_output.cpython-313.pyc
|
Other
| 9,948 | 0.95 | 0.008 | 0.016393 |
python-kit
| 170 |
2024-11-19T00:33:47.535749
|
GPL-3.0
| true |
4c1a0257e804430b08c90aa83faf9d68
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_selection.cpython-313.pyc
|
test_widget_selection.cpython-313.pyc
|
Other
| 6,283 | 0.8 | 0 | 0 |
vue-tools
| 758 |
2025-01-24T22:24:04.634312
|
GPL-3.0
| true |
556391e80baf2268d5e4d459e3110d98
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_string.cpython-313.pyc
|
test_widget_string.cpython-313.pyc
|
Other
| 3,353 | 0.8 | 0 | 0 |
react-lib
| 23 |
2023-07-29T13:10:40.033326
|
MIT
| true |
1627a89f6efac0a9c0a815e289e90f4b
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_templates.cpython-313.pyc
|
test_widget_templates.cpython-313.pyc
|
Other
| 35,195 | 0.95 | 0.008097 | 0 |
python-kit
| 968 |
2025-07-03T09:10:23.448959
|
Apache-2.0
| true |
da5ec9911492d13da2fa43e415bf1f1d
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_time.cpython-313.pyc
|
test_widget_time.cpython-313.pyc
|
Other
| 5,455 | 0.8 | 0 | 0.085106 |
vue-tools
| 836 |
2025-01-18T02:31:26.905140
|
GPL-3.0
| true |
45942a391abaff8998c1ffb643fd5586
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\test_widget_upload.cpython-313.pyc
|
test_widget_upload.cpython-313.pyc
|
Other
| 5,564 | 0.8 | 0 | 0 |
react-lib
| 250 |
2024-10-03T21:57:44.850054
|
Apache-2.0
| true |
d2047ac5a4169f4c20195c81b8079743
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\utils.cpython-313.pyc
|
utils.cpython-313.pyc
|
Other
| 4,517 | 0.8 | 0 | 0.033333 |
vue-tools
| 652 |
2024-07-27T16:00:54.238986
|
BSD-3-Clause
| true |
e163979988c39818dd5f16d0f8ecaeee
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\tests\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 199 | 0.7 | 0 | 0 |
awesome-app
| 857 |
2023-07-19T21:03:28.498864
|
MIT
| true |
cca99ef988e546d09658ead0d50fd205
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\docutils.cpython-313.pyc
|
docutils.cpython-313.pyc
|
Other
| 893 | 0.95 | 0.285714 | 0 |
vue-tools
| 178 |
2024-05-21T16:27:11.464566
|
Apache-2.0
| false |
1ae5f2bf847e454d6e9787005002967a
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\domwidget.cpython-313.pyc
|
domwidget.cpython-313.pyc
|
Other
| 3,342 | 0.95 | 0.111111 | 0 |
awesome-app
| 612 |
2025-03-23T01:44:20.887320
|
GPL-3.0
| false |
9db99b6ef8cf52aa753ff10b8d37f06f
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\interaction.cpython-313.pyc
|
interaction.cpython-313.pyc
|
Other
| 24,605 | 0.95 | 0.18543 | 0.040441 |
python-kit
| 290 |
2025-04-20T16:31:41.683291
|
BSD-3-Clause
| false |
c7cd52dfa8d4fda5d66c7538b7cceacb
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\trait_types.cpython-313.pyc
|
trait_types.cpython-313.pyc
|
Other
| 17,279 | 0.8 | 0.026786 | 0 |
awesome-app
| 81 |
2024-03-07T05:03:43.670077
|
MIT
| false |
13229339e3f249ca86fad44fea88c43a
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\utils.cpython-313.pyc
|
utils.cpython-313.pyc
|
Other
| 2,637 | 0.95 | 0.125 | 0 |
awesome-app
| 831 |
2024-04-11T08:33:18.220618
|
Apache-2.0
| false |
8f300c3b93a4dad973a43a1629c46049
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\valuewidget.cpython-313.pyc
|
valuewidget.cpython-313.pyc
|
Other
| 1,374 | 0.95 | 0.1875 | 0 |
vue-tools
| 276 |
2023-10-27T17:09:20.742744
|
BSD-3-Clause
| false |
7bce9d64dae7e4c1b51e9965676b6c0e
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget.cpython-313.pyc
|
widget.cpython-313.pyc
|
Other
| 38,832 | 0.95 | 0.067251 | 0.006309 |
node-utils
| 440 |
2023-09-02T17:34:33.163524
|
GPL-3.0
| false |
49278b34c7871875a25e97f4b21723d5
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_bool.cpython-313.pyc
|
widget_bool.cpython-313.pyc
|
Other
| 6,360 | 0.95 | 0.039063 | 0 |
python-kit
| 967 |
2025-05-26T05:50:39.272201
|
Apache-2.0
| false |
9bb08595df65eac989776246453e8b95
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_box.cpython-313.pyc
|
widget_box.cpython-313.pyc
|
Other
| 4,788 | 0.95 | 0.008475 | 0 |
node-utils
| 755 |
2025-04-22T22:13:10.103602
|
GPL-3.0
| false |
1694022fc2b6cdf3f732d669a155092f
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_button.cpython-313.pyc
|
widget_button.cpython-313.pyc
|
Other
| 5,818 | 0.95 | 0.07 | 0 |
vue-tools
| 400 |
2024-01-09T05:33:55.788722
|
Apache-2.0
| false |
945a2ef4a03afe69fe22392b13003f44
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_color.cpython-313.pyc
|
widget_color.cpython-313.pyc
|
Other
| 1,396 | 0.8 | 0.043478 | 0 |
python-kit
| 419 |
2025-03-06T16:56:58.548414
|
BSD-3-Clause
| false |
f3c1fec336115c82f0d15e0f1f33cbfc
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_controller.cpython-313.pyc
|
widget_controller.cpython-313.pyc
|
Other
| 3,485 | 0.8 | 0.017857 | 0 |
awesome-app
| 914 |
2024-03-25T08:51:53.746185
|
MIT
| false |
2483adef2fcb21d0b879c848f840a596
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_core.cpython-313.pyc
|
widget_core.cpython-313.pyc
|
Other
| 1,057 | 0.95 | 0.285714 | 0 |
awesome-app
| 313 |
2025-03-16T04:12:56.343630
|
MIT
| false |
0a8809c3e314dae4567273f6992e3843
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_date.cpython-313.pyc
|
widget_date.cpython-313.pyc
|
Other
| 3,637 | 0.95 | 0.039474 | 0 |
python-kit
| 387 |
2024-09-21T03:08:06.974597
|
Apache-2.0
| false |
d1bf86d1f77d77a3384a56487243ab3e
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_datetime.cpython-313.pyc
|
widget_datetime.cpython-313.pyc
|
Other
| 5,502 | 0.95 | 0.015385 | 0 |
vue-tools
| 749 |
2023-10-25T09:48:11.943236
|
GPL-3.0
| false |
a04d10803e8899198c27090577b865f0
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_description.cpython-313.pyc
|
widget_description.cpython-313.pyc
|
Other
| 3,525 | 0.8 | 0.027027 | 0 |
awesome-app
| 426 |
2023-08-19T08:49:58.978180
|
GPL-3.0
| false |
bd91588feceb6cfdde53a1f29225444f
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_float.cpython-313.pyc
|
widget_float.cpython-313.pyc
|
Other
| 19,825 | 0.95 | 0.054711 | 0 |
vue-tools
| 334 |
2024-08-12T15:25:18.966302
|
Apache-2.0
| false |
c75617b82ea32d54b261701dfe657176
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_int.cpython-313.pyc
|
widget_int.cpython-313.pyc
|
Other
| 17,595 | 0.95 | 0.063492 | 0.008097 |
react-lib
| 20 |
2025-02-04T04:03:02.645346
|
GPL-3.0
| false |
5cd8651c0aecd4870c05fc805511ebee
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_layout.cpython-313.pyc
|
widget_layout.cpython-313.pyc
|
Other
| 8,693 | 0.8 | 0.012195 | 0 |
node-utils
| 74 |
2023-07-19T08:30:17.109298
|
BSD-3-Clause
| false |
703c56822c3392fb9d105e2463995ba8
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_link.cpython-313.pyc
|
widget_link.cpython-313.pyc
|
Other
| 4,897 | 0.8 | 0.070707 | 0.023529 |
react-lib
| 859 |
2025-03-27T09:19:04.949934
|
MIT
| false |
ae8237e02a815b1de1507fd78440492b
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_media.cpython-313.pyc
|
widget_media.cpython-313.pyc
|
Other
| 10,421 | 0.95 | 0.048649 | 0.006061 |
node-utils
| 621 |
2024-01-23T22:07:37.643937
|
Apache-2.0
| false |
5a06a34ec99c75f542f52ef9a365b99f
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_output.cpython-313.pyc
|
widget_output.cpython-313.pyc
|
Other
| 8,515 | 0.95 | 0.070423 | 0 |
python-kit
| 789 |
2023-09-03T15:59:15.892595
|
MIT
| false |
c94c6bd38d1c87153617eb82bbea0a5b
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_selection.cpython-313.pyc
|
widget_selection.cpython-313.pyc
|
Other
| 34,807 | 0.95 | 0.049096 | 0.014577 |
node-utils
| 630 |
2024-08-30T07:07:34.181011
|
GPL-3.0
| false |
478bb234540e50f297e483cdf6bd4798
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_selectioncontainer.cpython-313.pyc
|
widget_selectioncontainer.cpython-313.pyc
|
Other
| 6,480 | 0.95 | 0.0375 | 0 |
vue-tools
| 662 |
2025-03-08T05:53:46.490177
|
Apache-2.0
| false |
c6b87f9af9843e7df9a924c17b01eef6
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_string.cpython-313.pyc
|
widget_string.cpython-313.pyc
|
Other
| 10,915 | 0.95 | 0.017647 | 0 |
vue-tools
| 10 |
2024-02-18T02:23:16.322229
|
Apache-2.0
| false |
bcc35a8f81266cc822e43f4a7dc077c9
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_style.cpython-313.pyc
|
widget_style.cpython-313.pyc
|
Other
| 1,061 | 0.8 | 0.066667 | 0 |
python-kit
| 471 |
2023-11-19T02:48:07.347634
|
BSD-3-Clause
| false |
18bbe4d710323e2d3212772403da1dab
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_tagsinput.cpython-313.pyc
|
widget_tagsinput.cpython-313.pyc
|
Other
| 6,022 | 0.8 | 0.015267 | 0 |
node-utils
| 404 |
2025-03-07T06:46:25.113648
|
Apache-2.0
| false |
9cc9acee921969d133a640a9c5ae1541
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_templates.cpython-313.pyc
|
widget_templates.cpython-313.pyc
|
Other
| 18,453 | 0.95 | 0.017167 | 0.005051 |
awesome-app
| 969 |
2025-02-07T02:43:20.303783
|
MIT
| false |
b845366d38b4f4ace301ee86470f990c
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_time.cpython-313.pyc
|
widget_time.cpython-313.pyc
|
Other
| 3,790 | 0.95 | 0.0375 | 0 |
react-lib
| 97 |
2024-09-04T10:34:31.544994
|
Apache-2.0
| false |
18e43f19c14b7e0b959d57b167ce1175
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\widget_upload.cpython-313.pyc
|
widget_upload.cpython-313.pyc
|
Other
| 6,086 | 0.95 | 0.055556 | 0.009174 |
react-lib
| 271 |
2025-06-08T02:20:31.680715
|
Apache-2.0
| false |
5fc2d5b3a1f43ef8f35ad85b161aea36
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\widgets\__pycache__\__init__.cpython-313.pyc
|
__init__.cpython-313.pyc
|
Other
| 2,616 | 0.8 | 0 | 0 |
vue-tools
| 205 |
2024-04-24T15:02:16.093497
|
Apache-2.0
| false |
0ca43d75a891cdde26cd3378ecaccb27
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\__pycache__\comm.cpython-313.pyc
|
comm.cpython-313.pyc
|
Other
| 1,318 | 0.85 | 0 | 0 |
python-kit
| 516 |
2024-03-24T15:46:56.786946
|
GPL-3.0
| false |
5c74ad47a838d6a6957a2be32515496f
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\__pycache__\embed.cpython-313.pyc
|
embed.cpython-313.pyc
|
Other
| 11,990 | 0.95 | 0.097938 | 0 |
react-lib
| 632 |
2024-10-09T13:12:31.080546
|
GPL-3.0
| false |
c478045c36b1401241c77df3905fc2ae
|
\n\n
|
.venv\Lib\site-packages\ipywidgets\__pycache__\_version.cpython-313.pyc
|
_version.cpython-313.pyc
|
Other
| 492 | 0.7 | 0 | 0 |
python-kit
| 638 |
2023-08-04T21:47:14.236171
|
Apache-2.0
| false |
07bb5b35d8cf44c903e2c4d77bf34b45
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.