index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
11,872
traitlets.traitlets
set
null
def set(self, obj: HasTraits, value: S) -> None: new_value = self._validate(obj, value) assert self.name is not None try: old_value = obj._trait_values[self.name] except KeyError: old_value = self.default_value obj._trait_values[self.name] = new_value try: silent = bool(old_value == new_value) except Exception: # if there is an error in comparing, default to notify silent = False if silent is not True: # we explicitly compare silent to True just in case the equality # comparison above returns something other than True/False obj._notify_trait(self.name, old_value, new_value)
(self, obj: traitlets.traitlets.HasTraits, value: ~S) -> NoneType
11,873
traitlets.traitlets
set_metadata
DEPRECATED: Set a metadata key/value. Use .metadata[key] = value instead.
def set_metadata(self, key: str, value: t.Any) -> None: """DEPRECATED: Set a metadata key/value. Use .metadata[key] = value instead. """ if key == "help": msg = "use the instance .help string directly, like x.help = value" else: msg = "use the instance .metadata dictionary directly, like x.metadata[key] = value" warn("Deprecated in traitlets 4.1, " + msg, DeprecationWarning, stacklevel=2) self.metadata[key] = value
(self, key: str, value: Any) -> NoneType
11,874
traitlets.traitlets
subclass_init
null
def subclass_init(self, cls: type[t.Any]) -> None: pass # fully opt out of instance_init
(self, cls: type[typing.Any]) -> NoneType
11,875
traitlets.traitlets
tag
Sets metadata and returns self. This allows convenient metadata tagging when initializing the trait, such as: Examples -------- >>> Int(0).tag(config=True, sync=True) <traitlets.traitlets.Int object at ...>
def tag(self, **metadata: t.Any) -> Self: """Sets metadata and returns self. This allows convenient metadata tagging when initializing the trait, such as: Examples -------- >>> Int(0).tag(config=True, sync=True) <traitlets.traitlets.Int object at ...> """ maybe_constructor_keywords = set(metadata.keys()).intersection( {"help", "allow_none", "read_only", "default_value"} ) if maybe_constructor_keywords: warn( "The following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s " % maybe_constructor_keywords, UserWarning, stacklevel=2, ) self.metadata.update(metadata) return self
(self, **metadata: 't.Any') -> 'Self'
11,876
ipyleaflet.leaflet
AttributionControl
AttributionControl class. A control which contains the layers attribution.
class AttributionControl(Control): """AttributionControl class. A control which contains the layers attribution. """ _view_name = Unicode("LeafletAttributionControlView").tag(sync=True) _model_name = Unicode("LeafletAttributionControlModel").tag(sync=True) prefix = Unicode("ipyleaflet").tag(sync=True, o=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
11,881
ipywidgets.widgets.widget
__init__
Public constructor
def __init__(self, **kwargs): """Public constructor""" self._model_id = kwargs.pop('model_id', None) super().__init__(**kwargs) Widget._call_widget_constructed(self) self.open()
(self, **kwargs)
11,933
ipyleaflet.leaflet
AwesomeIcon
AwesomeIcon class. FontAwesome icon used for markers. Attributes ---------- name : string, default "home" The name of the FontAwesome icon to use. See https://fontawesome.com/v4.7.0/icons for available icons. marker_color: string, default "blue" Color used for the icon background. icon_color: string, default "white" CSS color used for the FontAwesome icon. spin: boolean, default False Whether the icon is spinning or not.
class AwesomeIcon(UILayer): """AwesomeIcon class. FontAwesome icon used for markers. Attributes ---------- name : string, default "home" The name of the FontAwesome icon to use. See https://fontawesome.com/v4.7.0/icons for available icons. marker_color: string, default "blue" Color used for the icon background. icon_color: string, default "white" CSS color used for the FontAwesome icon. spin: boolean, default False Whether the icon is spinning or not. """ _view_name = Unicode("LeafletAwesomeIconView").tag(sync=True) _model_name = Unicode("LeafletAwesomeIconModel").tag(sync=True) name = Unicode("home").tag(sync=True) marker_color = Enum( values=[ "white", "red", "darkred", "lightred", "orange", "beige", "green", "darkgreen", "lightgreen", "blue", "darkblue", "lightblue", "purple", "darkpurple", "pink", "cadetblue", "white", "gray", "lightgray", "black", ], default_value="blue", ).tag(sync=True) icon_color = Color("white").tag(sync=True) spin = Bool(False).tag(sync=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
11,998
traitlets.traitlets
Bool
A boolean (True, False) trait.
class Bool(TraitType[G, S]): """A boolean (True, False) trait.""" default_value = False info_text = "a boolean" if t.TYPE_CHECKING: @t.overload def __init__( self: Bool[bool, bool | int], default_value: bool | Sentinel = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: Bool[bool | None, bool | int | None], default_value: bool | Sentinel | None = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any = ..., **kwargs: t.Any, ) -> None: ... def __init__( self: Bool[bool | None, bool | int | None], default_value: bool | Sentinel | None = ..., allow_none: bool = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any = ..., **kwargs: t.Any, ) -> None: ... def validate(self, obj: t.Any, value: t.Any) -> G: if isinstance(value, bool): return t.cast(G, value) elif isinstance(value, int): if value == 1: return t.cast(G, True) elif value == 0: return t.cast(G, False) self.error(obj, value) def from_string(self, s: str) -> G: if self.allow_none and s == "None": return t.cast(G, None) s = s.lower() if s in {"true", "1"}: return t.cast(G, True) elif s in {"false", "0"}: return t.cast(G, False) else: raise ValueError("%r is not 1, 0, true, or false") def subclass_init(self, cls: type[t.Any]) -> None: pass # fully opt out of instance_init def argcompleter(self, **kwargs: t.Any) -> list[str]: """Completion hints for argcomplete""" completions = ["true", "1", "false", "0"] if self.allow_none: completions.append("None") return completions
(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, config: 't.Any' = None, **kwargs: 't.Any') -> 'None'
12,005
traitlets.traitlets
argcompleter
Completion hints for argcomplete
def argcompleter(self, **kwargs: t.Any) -> list[str]: """Completion hints for argcomplete""" completions = ["true", "1", "false", "0"] if self.allow_none: completions.append("None") return completions
(self, **kwargs: Any) -> list[str]
12,010
traitlets.traitlets
from_string
null
def from_string(self, s: str) -> G: if self.allow_none and s == "None": return t.cast(G, None) s = s.lower() if s in {"true", "1"}: return t.cast(G, True) elif s in {"false", "0"}: return t.cast(G, False) else: raise ValueError("%r is not 1, 0, true, or false")
(self, s: str) -> ~G
12,021
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> G: if isinstance(value, bool): return t.cast(G, value) elif isinstance(value, int): if value == 1: return t.cast(G, True) elif value == 0: return t.cast(G, False) self.error(obj, value)
(self, obj: Any, value: Any) -> ~G
12,022
ipywidgets.widgets.widget_box
Box
Displays multiple widgets in a group. The widgets are laid out horizontally. Parameters ---------- children: iterable of Widget instances list of widgets to display box_style: str one of 'success', 'info', 'warning' or 'danger', or ''. Applies a predefined style to the box. Defaults to '', which applies no pre-defined style. Examples -------- >>> import ipywidgets as widgets >>> title_widget = widgets.HTML('<em>Box Example</em>') >>> slider = widgets.IntSlider() >>> widgets.Box([title_widget, slider])
class Box(DOMWidget, CoreWidget): """ Displays multiple widgets in a group. The widgets are laid out horizontally. Parameters ---------- {box_params} Examples -------- >>> import ipywidgets as widgets >>> title_widget = widgets.HTML('<em>Box Example</em>') >>> slider = widgets.IntSlider() >>> widgets.Box([title_widget, slider]) """ _model_name = Unicode('BoxModel').tag(sync=True) _view_name = Unicode('BoxView').tag(sync=True) # Child widgets in the container. # Using a tuple here to force reassignment to update the list. # When a proper notifying-list trait exists, use that instead. children = TypedTuple(trait=Instance(Widget), help="List of widget children").tag( sync=True, **widget_serialization) box_style = CaselessStrEnum( values=['success', 'info', 'warning', 'danger', ''], default_value='', help="""Use a predefined styling for the box.""").tag(sync=True) def __init__(self, children=(), **kwargs): kwargs['children'] = children super().__init__(**kwargs)
(children=(), **kwargs)
12,027
ipywidgets.widgets.widget_box
__init__
null
def __init__(self, children=(), **kwargs): kwargs['children'] = children super().__init__(**kwargs)
(self, children=(), **kwargs)
12,045
ipywidgets.widgets.domwidget
_repr_keys
null
def _repr_keys(self): for key in super()._repr_keys(): # Exclude layout if it had the default value if key == 'layout': value = getattr(self, key) if repr(value) == '%s()' % value.__class__.__name__: continue yield key # We also need to include _dom_classes in repr for reproducibility if self._dom_classes: yield '_dom_classes'
(self)
12,051
ipywidgets.widgets.domwidget
add_class
Adds a class to the top level element of the widget. Doesn't add the class if it already exists.
def add_class(self, className): """ Adds a class to the top level element of the widget. Doesn't add the class if it already exists. """ if className not in self._dom_classes: self._dom_classes = list(self._dom_classes) + [className] return self
(self, className)
12,053
ipywidgets.widgets.domwidget
blur
Blur the widget.
def blur(self): """ Blur the widget. """ self.send({'do':'blur'})
(self)
12,055
ipywidgets.widgets.domwidget
focus
Focus on the widget.
def focus(self): """ Focus on the widget. """ self.send({'do':'focus'})
(self)
12,069
ipywidgets.widgets.domwidget
remove_class
Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist.
def remove_class(self, className): """ Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist. """ if className in self._dom_classes: self._dom_classes = [c for c in self._dom_classes if c != className] return self
(self, className)
12,083
traitlets.traitlets
CFloat
A casting version of the float trait.
class CFloat(Float[G, S]): """A casting version of the float trait.""" if t.TYPE_CHECKING: @t.overload def __init__( self: CFloat[float, t.Any], default_value: t.Any = ..., allow_none: Literal[False] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... @t.overload def __init__( self: CFloat[float | None, t.Any], default_value: t.Any = ..., allow_none: Literal[True] = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... def __init__( self: CFloat[float | None, t.Any], default_value: t.Any = ..., allow_none: bool = ..., read_only: bool | None = ..., help: str | None = ..., config: t.Any | None = ..., **kwargs: t.Any, ) -> None: ... def validate(self, obj: t.Any, value: t.Any) -> G: try: value = float(value) except Exception: self.error(obj, value) return t.cast(G, _validate_bounds(self, obj, value))
(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool = False, help: 'str | None' = None, config: 't.Any | None' = None, **kwargs: 't.Any') -> 'None'
12,085
traitlets.traitlets
__init__
null
def __init__( self: Float[int | None, int | float | None], default_value: float | Sentinel | None = Undefined, allow_none: bool = False, read_only: bool | None = False, help: str | None = None, config: t.Any | None = None, **kwargs: t.Any, ) -> None: self.min = kwargs.pop("min", -float("inf")) self.max = kwargs.pop("max", float("inf")) super().__init__( default_value=default_value, allow_none=allow_none, read_only=read_only, help=help, config=config, **kwargs, )
(self: traitlets.traitlets.Float[int | None, int | float | None], default_value: float | traitlets.utils.sentinel.Sentinel | None = traitlets.Undefined, allow_none: bool = False, read_only: bool | None = False, help: Optional[str] = None, config: Optional[Any] = None, **kwargs: Any) -> NoneType
12,094
traitlets.traitlets
from_string
null
def from_string(self, s: str) -> G: if self.allow_none and s == "None": return t.cast(G, None) return t.cast(G, float(s))
(self, s: str) -> ~G
12,105
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> G: try: value = float(value) except Exception: self.error(obj, value) return t.cast(G, _validate_bounds(self, obj, value))
(self, obj: Any, value: Any) -> ~G
12,106
ipywidgets.widgets.widget
CallbackDispatcher
A structure for registering and running callbacks
class CallbackDispatcher(LoggingHasTraits): """A structure for registering and running callbacks""" callbacks = List() def __call__(self, *args, **kwargs): """Call all of the registered callbacks.""" value = None for callback in self.callbacks: try: local_value = callback(*args, **kwargs) except Exception as e: ip = get_ipython() if ip is None: self.log.warning("Exception in callback %s: %s", callback, e, exc_info=True) else: ip.showtraceback() else: value = local_value if local_value is not None else value return value def register_callback(self, callback, remove=False): """(Un)Register a callback Parameters ---------- callback: method handle Method to be registered or unregistered. remove=False: bool Whether to unregister the callback.""" # (Un)Register the callback. if remove and callback in self.callbacks: self.callbacks.remove(callback) elif not remove and callback not in self.callbacks: self.callbacks.append(callback)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,107
ipywidgets.widgets.widget
__call__
Call all of the registered callbacks.
def __call__(self, *args, **kwargs): """Call all of the registered callbacks.""" value = None for callback in self.callbacks: try: local_value = callback(*args, **kwargs) except Exception as e: ip = get_ipython() if ip is None: self.log.warning("Exception in callback %s: %s", callback, e, exc_info=True) else: ip.showtraceback() else: value = local_value if local_value is not None else value return value
(self, *args, **kwargs)
12,109
traitlets.traitlets
__init__
null
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: # Allow trait values to be set using keyword arguments. # We need to use setattr for this to trigger validation and # notifications. super_args = args super_kwargs = {} if kwargs: # this is a simplified (and faster) version of # the hold_trait_notifications(self) context manager def ignore(change: Bunch) -> None: pass self.notify_change = ignore # type:ignore[method-assign] self._cross_validation_lock = True changes = {} for key, value in kwargs.items(): if self.has_trait(key): setattr(self, key, value) changes[key] = Bunch( name=key, old=None, new=value, owner=self, type="change", ) else: # passthrough args that don't set traits to super super_kwargs[key] = value # notify and cross validate all trait changes that were set in kwargs changed = set(kwargs) & set(self._traits) for key in changed: value = self._traits[key]._cross_validate(self, getattr(self, key)) self.set_trait(key, value) changes[key]["new"] = value self._cross_validation_lock = False # Restore method retrieval from class del self.notify_change for key in changed: self.notify_change(changes[key]) try: super().__init__(*super_args, **super_kwargs) except TypeError as e: arg_s_list = [repr(arg) for arg in super_args] for k, v in super_kwargs.items(): arg_s_list.append(f"{k}={v!r}") arg_s = ", ".join(arg_s_list) warn( "Passing unrecognized arguments to super({classname}).__init__({arg_s}).\n" "{error}\n" "This is deprecated in traitlets 4.2." "This error will be raised in a future release of traitlets.".format( arg_s=arg_s, classname=self.__class__.__name__, error=e, ), DeprecationWarning, stacklevel=2, )
(self, *args: Any, **kwargs: Any) -> NoneType
12,118
traitlets.traitlets
add_traits
Dynamically add trait attributes to the HasTraits instance.
def add_traits(self, **traits: t.Any) -> None: """Dynamically add trait attributes to the HasTraits instance.""" cls = self.__class__ attrs = {"__module__": cls.__module__} if hasattr(cls, "__qualname__"): # __qualname__ introduced in Python 3.3 (see PEP 3155) attrs["__qualname__"] = cls.__qualname__ attrs.update(traits) self.__class__ = type(cls.__name__, (cls,), attrs) for trait in traits.values(): trait.instance_init(self)
(self, **traits: Any) -> NoneType
12,121
traitlets.traitlets
notify_change
Notify observers of a change event
def notify_change(self, change: Bunch) -> None: """Notify observers of a change event""" return self._notify_observers(change)
(self, change: traitlets.utils.bunch.Bunch) -> NoneType
12,124
ipywidgets.widgets.widget
register_callback
(Un)Register a callback Parameters ---------- callback: method handle Method to be registered or unregistered. remove=False: bool Whether to unregister the callback.
def register_callback(self, callback, remove=False): """(Un)Register a callback Parameters ---------- callback: method handle Method to be registered or unregistered. remove=False: bool Whether to unregister the callback.""" # (Un)Register the callback. if remove and callback in self.callbacks: self.callbacks.remove(callback) elif not remove and callback not in self.callbacks: self.callbacks.append(callback)
(self, callback, remove=False)
12,135
ipyleaflet.leaflet
Choropleth
Choropleth class, with GeoJSON as parent class. Layer showing a Choropleth effect on a GeoJSON structure. Attributes ---------- geo_data: dict, default None The GeoJSON structure on which to apply the Choropleth effect. choro_data: dict, default None Data used for building the Choropleth effect. value_min: float, default None Minimum data value for the color mapping. value_max: float, default None Maximum data value for the color mapping. colormap: branca.colormap.ColorMap instance, default linear.OrRd_06 The colormap used for the effect. key_on: string, default "id" The feature key to use for the colormap effect. nan_color: string, default "black" The color used for filling polygons with NaN-values data. nan_opacity : float, default 0.4 The opacity used for NaN data polygons, between 0. (fully transparent) and 1. (fully opaque). default_opacity: float, default 1.0 The opacity used for well-defined data (non-NaN values), between 0. (fully transparent) and 1. (fully opaque).
class Choropleth(GeoJSON): """Choropleth class, with GeoJSON as parent class. Layer showing a Choropleth effect on a GeoJSON structure. Attributes ---------- geo_data: dict, default None The GeoJSON structure on which to apply the Choropleth effect. choro_data: dict, default None Data used for building the Choropleth effect. value_min: float, default None Minimum data value for the color mapping. value_max: float, default None Maximum data value for the color mapping. colormap: branca.colormap.ColorMap instance, default linear.OrRd_06 The colormap used for the effect. key_on: string, default "id" The feature key to use for the colormap effect. nan_color: string, default "black" The color used for filling polygons with NaN-values data. nan_opacity : float, default 0.4 The opacity used for NaN data polygons, between 0. (fully transparent) and 1. (fully opaque). default_opacity: float, default 1.0 The opacity used for well-defined data (non-NaN values), between 0. (fully transparent) and 1. (fully opaque). """ geo_data = Dict() choro_data = Dict() value_min = CFloat(None, allow_none=True) value_max = CFloat(None, allow_none=True) colormap = Instance(ColorMap, default_value=linear.OrRd_06) key_on = Unicode("id") nan_color = Unicode("black") nan_opacity = CFloat(0.4) default_opacity = CFloat(1.0) @observe( "style", "style_callback", "value_min", "value_max", "nan_color", "nan_opacity", "default_opacity", "geo_data", "choro_data", "colormap", ) def _update_data(self, change): self.data = self._get_data() @default("style_callback") def _default_style_callback(self): def compute_style(feature, colormap, choro_data): return dict( fillColor=self.nan_color if isnan(choro_data) else colormap(choro_data), fillOpacity=self.nan_opacity if isnan(choro_data) else self.default_opacity, color="black", weight=0.9, ) return compute_style def _get_data(self): if not self.geo_data: return {} choro_data_values_list = [x for x in self.choro_data.values() if not isnan(x)] if self.value_min is None: self.value_min = min(choro_data_values_list) if self.value_max is None: self.value_max = max(choro_data_values_list) colormap = self.colormap.scale(self.value_min, self.value_max) data = copy.deepcopy(self.geo_data) for feature in data["features"]: feature["properties"]["style"] = self.style_callback( feature, colormap, self.choro_data[feature[self.key_on]] ) return data def __init__(self, **kwargs): super(Choropleth, self).__init__(**kwargs) self.data = self._get_data()
(**kwargs)
12,140
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(Choropleth, self).__init__(**kwargs) self.data = self._get_data()
(self, **kwargs)
12,145
ipyleaflet.leaflet
_apply_style
null
def _apply_style(self, feature, style_callback): if "properties" not in feature: feature["properties"] = {} properties = feature["properties"] if "style" in properties: style = properties["style"].copy() style.update(style_callback(feature)) properties["style"] = style else: properties["style"] = style_callback(feature)
(self, feature, style_callback)
12,149
ipyleaflet.leaflet
_get_data
null
def _get_data(self): if not self.geo_data: return {} choro_data_values_list = [x for x in self.choro_data.values() if not isnan(x)] if self.value_min is None: self.value_min = min(choro_data_values_list) if self.value_max is None: self.value_max = max(choro_data_values_list) colormap = self.colormap.scale(self.value_min, self.value_max) data = copy.deepcopy(self.geo_data) for feature in data["features"]: feature["properties"]["style"] = self.style_callback( feature, colormap, self.choro_data[feature[self.key_on]] ) return data
(self)
12,153
ipyleaflet.leaflet
_handle_mouse_events
null
def _handle_mouse_events(self, _, content, buffers): if content.get("event", "") == "click": self._click_callbacks(**content) if content.get("event", "") == "mouseover": self._hover_callbacks(**content)
(self, _, content, buffers)
12,167
ipyleaflet.leaflet
add
Add a new layer to the group. Parameters ---------- layer: layer instance The new layer to include in the group. This can also be an object with an ``as_leaflet_layer`` method which generates a compatible layer type.
def add(self, layer): """Add a new layer to the group. Parameters ---------- layer: layer instance The new layer to include in the group. This can also be an object with an ``as_leaflet_layer`` method which generates a compatible layer type. """ if isinstance(layer, dict): layer = basemap_to_tiles(layer) if layer.model_id in self._layer_ids: raise LayerException("layer already in layergroup: %r" % layer) self.layers = tuple([layer for layer in self.layers] + [layer])
(self, layer)
12,168
ipyleaflet.leaflet
add_layer
Add a new layer to the group. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- layer: layer instance The new layer to include in the group.
def add_layer(self, layer): """Add a new layer to the group. .. deprecated :: 0.17.0 Use add method instead. Parameters ---------- layer: layer instance The new layer to include in the group. """ warnings.warn("add_layer is deprecated, use add instead", DeprecationWarning) self.add(layer)
(self, layer)
12,170
ipyleaflet.leaflet
clear
Remove all layers from the group.
def clear(self): """Remove all layers from the group.""" self.layers = ()
(self)
12,171
ipyleaflet.leaflet
clear_layers
Remove all layers from the group. .. deprecated :: 0.17.0 Use clear method instead.
def clear_layers(self): """Remove all layers from the group. .. deprecated :: 0.17.0 Use clear method instead. """ warnings.warn( "clear_layers is deprecated, use clear instead", DeprecationWarning ) self.layers = ()
(self)
12,183
ipyleaflet.leaflet
on_click
Add a feature click event listener. Parameters ---------- callback : callable Callback function that will be called on click event on a feature, this function should take the event and the feature as inputs. remove: boolean Whether to remove this callback or not. Defaults to False.
def on_click(self, callback, remove=False): """Add a feature click event listener. Parameters ---------- callback : callable Callback function that will be called on click event on a feature, this function should take the event and the feature as inputs. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._click_callbacks.register_callback(callback, remove=remove)
(self, callback, remove=False)
12,185
ipyleaflet.leaflet
on_hover
Add a feature hover event listener. Parameters ---------- callback : callable Callback function that will be called when the mouse is over a feature, this function should take the event and the feature as inputs. remove: boolean Whether to remove this callback or not. Defaults to False.
def on_hover(self, callback, remove=False): """Add a feature hover event listener. Parameters ---------- callback : callable Callback function that will be called when the mouse is over a feature, this function should take the event and the feature as inputs. remove: boolean Whether to remove this callback or not. Defaults to False. """ self._hover_callbacks.register_callback(callback, remove=remove)
(self, callback, remove=False)
12,194
ipyleaflet.leaflet
remove
Remove a layer from the group. Parameters ---------- layer: layer instance The layer to remove from the group.
def remove(self, rm_layer): """Remove a layer from the group. Parameters ---------- layer: layer instance The layer to remove from the group. """ if rm_layer.model_id not in self._layer_ids: raise LayerException("layer not on in layergroup: %r" % rm_layer) self.layers = tuple( [layer for layer in self.layers if layer.model_id != rm_layer.model_id] )
(self, rm_layer)
12,195
ipyleaflet.leaflet
remove_layer
Remove a layer from the group. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- layer: layer instance The layer to remove from the group.
def remove_layer(self, rm_layer): """Remove a layer from the group. .. deprecated :: 0.17.0 Use remove method instead. Parameters ---------- layer: layer instance The layer to remove from the group. """ warnings.warn( "remove_layer is deprecated, use remove instead", DeprecationWarning ) self.remove(rm_layer)
(self, rm_layer)
12,201
ipyleaflet.leaflet
substitute
Substitute a layer with another one in the group. Parameters ---------- old: layer instance The layer to remove from the group. new: layer instance The new layer to include in the group.
def substitute(self, old, new): """Substitute a layer with another one in the group. Parameters ---------- old: layer instance The layer to remove from the group. new: layer instance The new layer to include in the group. """ if isinstance(new, dict): new = basemap_to_tiles(new) if old.model_id not in self._layer_ids: raise LayerException("Could not substitute layer: layer not in layergroup.") self.layers = tuple( [new if layer.model_id == old.model_id else layer for layer in self.layers] )
(self, old, new)
12,202
ipyleaflet.leaflet
substitute_layer
Substitute a layer with another one in the group. .. deprecated :: 0.17.0 Use substitute method instead. Parameters ---------- old: layer instance The layer to remove from the group. new: layer instance The new layer to include in the group.
def substitute_layer(self, old, new): """Substitute a layer with another one in the group. .. deprecated :: 0.17.0 Use substitute method instead. Parameters ---------- old: layer instance The layer to remove from the group. new: layer instance The new layer to include in the group. """ warnings.warn( "substitute_layer is deprecated, use substitute instead", DeprecationWarning ) self.substitute(old, new)
(self, old, new)
12,211
ipyleaflet.leaflet
Circle
Circle class, with CircleMarker as parent class. Circle layer.
class Circle(CircleMarker): """Circle class, with CircleMarker as parent class. Circle layer. """ _view_name = Unicode("LeafletCircleView").tag(sync=True) _model_name = Unicode("LeafletCircleModel").tag(sync=True) # Options radius = Int(1000, help="radius of circle in meters").tag(sync=True, o=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,276
ipyleaflet.leaflet
CircleMarker
CircleMarker class, with Path as parent class. CircleMarker layer. Attributes ---------- location: list, default [0, 0] Location of the marker (lat, long). radius: int, default 10 Radius of the circle marker in pixels.
class CircleMarker(Path): """CircleMarker class, with Path as parent class. CircleMarker layer. Attributes ---------- location: list, default [0, 0] Location of the marker (lat, long). radius: int, default 10 Radius of the circle marker in pixels. """ _view_name = Unicode("LeafletCircleMarkerView").tag(sync=True) _model_name = Unicode("LeafletCircleMarkerModel").tag(sync=True) location = List(def_loc).tag(sync=True) # Options radius = Int(10, help="radius of circle in pixels").tag(sync=True, o=True)
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,341
ipywidgets.widgets.trait_types
Color
A string holding a valid HTML color such as 'blue', '#060482', '#A80'
class Color(traitlets.Unicode): """A string holding a valid HTML color such as 'blue', '#060482', '#A80'""" info_text = 'a valid HTML color' default_value = traitlets.Undefined def validate(self, obj, value): if value is None and self.allow_none: return value if isinstance(value, str): if (value.lower() in _color_names or _color_hex_re.match(value) or _color_hexa_re.match(value) or _color_rgbhsl_re.match(value) or _color_var_re.match(value)): return value self.error(obj, value)
(default_value: Any = traitlets.Undefined, allow_none: bool = False, read_only: bool = None, help: 'str | None' = None, config: 't.Any' = None, **kwargs: 't.Any') -> 'None'
12,352
traitlets.traitlets
from_string
null
def from_string(self, s: str) -> G: if self.allow_none and s == "None": return t.cast(G, None) s = os.path.expanduser(s) if len(s) >= 2: # handle deprecated "1" for c in ('"', "'"): if s[0] == s[-1] == c: old_s = s s = s[1:-1] warn( "Supporting extra quotes around strings is deprecated in traitlets 5.0. " f"You can use {s!r} instead of {old_s!r} if you require traitlets >=5.", DeprecationWarning, stacklevel=2, ) return t.cast(G, s)
(self, s: str) -> ~G
12,363
ipywidgets.widgets.trait_types
validate
null
def validate(self, obj, value): if value is None and self.allow_none: return value if isinstance(value, str): if (value.lower() in _color_names or _color_hex_re.match(value) or _color_hexa_re.match(value) or _color_rgbhsl_re.match(value) or _color_var_re.match(value)): return value self.error(obj, value)
(self, obj, value)
12,364
branca.colormap
ColorMap
A generic class for creating colormaps. Parameters ---------- vmin: float The left bound of the color scale. vmax: float The right bound of the color scale. caption: str A caption to draw with the colormap. max_labels : int, default 10 Maximum number of legend tick labels
class ColorMap(MacroElement): """A generic class for creating colormaps. Parameters ---------- vmin: float The left bound of the color scale. vmax: float The right bound of the color scale. caption: str A caption to draw with the colormap. max_labels : int, default 10 Maximum number of legend tick labels """ _template = ENV.get_template("color_scale.js") def __init__(self, vmin=0.0, vmax=1.0, caption="", max_labels=10): super().__init__() self._name = "ColorMap" self.vmin = vmin self.vmax = vmax self.caption = caption self.index = [vmin, vmax] self.max_labels = max_labels self.tick_labels = None self.width = 450 self.height = 40 def render(self, **kwargs): """Renders the HTML representation of the element.""" self.color_domain = [ float(self.vmin + (self.vmax - self.vmin) * k / 499.0) for k in range(500) ] self.color_range = [self.__call__(x) for x in self.color_domain] # sanitize possible numpy floats to native python floats self.index = [float(i) for i in self.index] if self.tick_labels is None: self.tick_labels = legend_scaler(self.index, self.max_labels) super().render(**kwargs) figure = self.get_root() assert isinstance(figure, Figure), ( "You cannot render this Element " "if it is not in a Figure." ) figure.header.add_child( JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"), name="d3", ) # noqa def rgba_floats_tuple(self, x): """ This class has to be implemented for each class inheriting from Colormap. This has to be a function of the form float -> (float, float, float, float) describing for each input float x, the output color in RGBA format; Each output value being between 0 and 1. """ raise NotImplementedError def rgba_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255. """ return tuple(int(u * 255.9999) for u in self.rgba_floats_tuple(x)) def rgb_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B) with int values between 0 and 255. """ return self.rgba_bytes_tuple(x)[:3] def rgb_hex_str(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBB". """ return "#%02x%02x%02x" % self.rgb_bytes_tuple(x) def rgba_hex_str(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA". """ return "#%02x%02x%02x%02x" % self.rgba_bytes_tuple(x) def __call__(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA". """ return self.rgba_hex_str(x) def _repr_html_(self): """Display the colormap in a Jupyter Notebook. Does not support all the class arguments. """ nb_ticks = 7 delta_x = math.floor(self.width / (nb_ticks - 1)) x_ticks = [(i) * delta_x for i in range(0, nb_ticks)] delta_val = delta_x * (self.vmax - self.vmin) / self.width val_ticks = [round(self.vmin + (i) * delta_val, 1) for i in range(0, nb_ticks)] return ( f'<svg height="40" width="{self.width}">' + "".join( [ ( '<line x1="{i}" y1="15" x2="{i}" ' 'y2="27" style="stroke:{color};stroke-width:2;" />' ).format( i=i * 1, color=self.rgba_hex_str( self.vmin + (self.vmax - self.vmin) * i / (self.width - 1), ), ) for i in range(self.width) ], ) + '<text x="0" y="38" style="text-anchor:start; font-size:11px; font:Arial">{}</text>'.format( # noqa self.vmin, ) + "".join( [ ( '<text x="{}" y="38"; style="text-anchor:middle; font-size:11px; font:Arial">{}</text>' # noqa ).format(x_ticks[i], val_ticks[i]) for i in range(1, nb_ticks - 1) ], ) + '<text x="{}" y="38" style="text-anchor:end; font-size:11px; font:Arial">{}</text>'.format( self.width, self.vmax, ) + '<text x="0" y="12" style="font-size:11px; font:Arial">{}</text>'.format( self.caption, ) + "</svg>" )
(vmin=0.0, vmax=1.0, caption='', max_labels=10)
12,365
branca.colormap
__call__
Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA".
def __call__(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA". """ return self.rgba_hex_str(x)
(self, x)
12,366
branca.element
__getstate__
Modify object state when pickling the object. jinja2 Templates cannot be pickled, so remove the instance attribute if it exists. It will be added back when unpickling (see __setstate__).
def __getstate__(self): """Modify object state when pickling the object. jinja2 Templates cannot be pickled, so remove the instance attribute if it exists. It will be added back when unpickling (see __setstate__). """ state: dict = self.__dict__.copy() state.pop("_template", None) return state
(self)
12,367
branca.colormap
__init__
null
def __init__(self, vmin=0.0, vmax=1.0, caption="", max_labels=10): super().__init__() self._name = "ColorMap" self.vmin = vmin self.vmax = vmax self.caption = caption self.index = [vmin, vmax] self.max_labels = max_labels self.tick_labels = None self.width = 450 self.height = 40
(self, vmin=0.0, vmax=1.0, caption='', max_labels=10)
12,368
branca.element
__setstate__
Re-add _template instance attribute when unpickling
def __setstate__(self, state: dict): """Re-add _template instance attribute when unpickling""" if state["_template_str"] is not None: state["_template"] = Template(state["_template_str"]) elif state["_template_name"] is not None: state["_template"] = ENV.get_template(state["_template_name"]) self.__dict__.update(state)
(self, state: dict)
12,369
branca.element
_get_self_bounds
Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]]
def _get_self_bounds(self): """Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]] """ return [[None, None], [None, None]]
(self)
12,370
branca.colormap
_repr_html_
Display the colormap in a Jupyter Notebook. Does not support all the class arguments.
def _repr_html_(self): """Display the colormap in a Jupyter Notebook. Does not support all the class arguments. """ nb_ticks = 7 delta_x = math.floor(self.width / (nb_ticks - 1)) x_ticks = [(i) * delta_x for i in range(0, nb_ticks)] delta_val = delta_x * (self.vmax - self.vmin) / self.width val_ticks = [round(self.vmin + (i) * delta_val, 1) for i in range(0, nb_ticks)] return ( f'<svg height="40" width="{self.width}">' + "".join( [ ( '<line x1="{i}" y1="15" x2="{i}" ' 'y2="27" style="stroke:{color};stroke-width:2;" />' ).format( i=i * 1, color=self.rgba_hex_str( self.vmin + (self.vmax - self.vmin) * i / (self.width - 1), ), ) for i in range(self.width) ], ) + '<text x="0" y="38" style="text-anchor:start; font-size:11px; font:Arial">{}</text>'.format( # noqa self.vmin, ) + "".join( [ ( '<text x="{}" y="38"; style="text-anchor:middle; font-size:11px; font:Arial">{}</text>' # noqa ).format(x_ticks[i], val_ticks[i]) for i in range(1, nb_ticks - 1) ], ) + '<text x="{}" y="38" style="text-anchor:end; font-size:11px; font:Arial">{}</text>'.format( self.width, self.vmax, ) + '<text x="0" y="12" style="font-size:11px; font:Arial">{}</text>'.format( self.caption, ) + "</svg>" )
(self)
12,371
branca.element
add_child
Add a child.
def add_child(self, child, name=None, index=None): """Add a child.""" if name is None: name = child.get_name() if index is None: self._children[name] = child else: items = [item for item in self._children.items() if item[0] != name] items.insert(int(index), (name, child)) self._children = OrderedDict(items) child._parent = self return self
(self, child, name=None, index=None)
12,372
branca.element
add_children
Add a child.
def add_children(self, child, name=None, index=None): """Add a child.""" warnings.warn( "Method `add_children` is deprecated. Please use `add_child` instead.", FutureWarning, stacklevel=2, ) return self.add_child(child, name=name, index=index)
(self, child, name=None, index=None)
12,373
branca.element
add_to
Add element to a parent.
def add_to(self, parent, name=None, index=None): """Add element to a parent.""" parent.add_child(self, name=name, index=index) return self
(self, parent, name=None, index=None)
12,374
branca.element
get_bounds
Computes the bounds of the object and all it's children in the form [[lat_min, lon_min], [lat_max, lon_max]].
def get_bounds(self): """Computes the bounds of the object and all it's children in the form [[lat_min, lon_min], [lat_max, lon_max]]. """ bounds = self._get_self_bounds() for child in self._children.values(): child_bounds = child.get_bounds() bounds = [ [ none_min(bounds[0][0], child_bounds[0][0]), none_min(bounds[0][1], child_bounds[0][1]), ], [ none_max(bounds[1][0], child_bounds[1][0]), none_max(bounds[1][1], child_bounds[1][1]), ], ] return bounds
(self)
12,375
branca.element
get_name
Returns a string representation of the object. This string has to be unique and to be a python and javascript-compatible variable name.
def get_name(self): """Returns a string representation of the object. This string has to be unique and to be a python and javascript-compatible variable name. """ return _camelify(self._name) + "_" + self._id
(self)
12,376
branca.element
get_root
Returns the root of the elements tree.
def get_root(self): """Returns the root of the elements tree.""" if self._parent is None: return self else: return self._parent.get_root()
(self)
12,377
branca.colormap
render
Renders the HTML representation of the element.
def render(self, **kwargs): """Renders the HTML representation of the element.""" self.color_domain = [ float(self.vmin + (self.vmax - self.vmin) * k / 499.0) for k in range(500) ] self.color_range = [self.__call__(x) for x in self.color_domain] # sanitize possible numpy floats to native python floats self.index = [float(i) for i in self.index] if self.tick_labels is None: self.tick_labels = legend_scaler(self.index, self.max_labels) super().render(**kwargs) figure = self.get_root() assert isinstance(figure, Figure), ( "You cannot render this Element " "if it is not in a Figure." ) figure.header.add_child( JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"), name="d3", ) # noqa
(self, **kwargs)
12,378
branca.colormap
rgb_bytes_tuple
Provides the color corresponding to value `x` in the form of a tuple (R,G,B) with int values between 0 and 255.
def rgb_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B) with int values between 0 and 255. """ return self.rgba_bytes_tuple(x)[:3]
(self, x)
12,379
branca.colormap
rgb_hex_str
Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBB".
def rgb_hex_str(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBB". """ return "#%02x%02x%02x" % self.rgb_bytes_tuple(x)
(self, x)
12,380
branca.colormap
rgba_bytes_tuple
Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255.
def rgba_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255. """ return tuple(int(u * 255.9999) for u in self.rgba_floats_tuple(x))
(self, x)
12,381
branca.colormap
rgba_floats_tuple
This class has to be implemented for each class inheriting from Colormap. This has to be a function of the form float -> (float, float, float, float) describing for each input float x, the output color in RGBA format; Each output value being between 0 and 1.
def rgba_floats_tuple(self, x): """ This class has to be implemented for each class inheriting from Colormap. This has to be a function of the form float -> (float, float, float, float) describing for each input float x, the output color in RGBA format; Each output value being between 0 and 1. """ raise NotImplementedError
(self, x)
12,382
branca.colormap
rgba_hex_str
Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA".
def rgba_hex_str(self, x): """Provides the color corresponding to value `x` in the form of a string of hexadecimal values "#RRGGBBAA". """ return "#%02x%02x%02x%02x" % self.rgba_bytes_tuple(x)
(self, x)
12,383
branca.element
save
Saves an Element into a file. Parameters ---------- outfile : str or file object The file (or filename) where you want to output the html. close_file : bool, default True Whether the file has to be closed after write.
def save(self, outfile, close_file=True, **kwargs): """Saves an Element into a file. Parameters ---------- outfile : str or file object The file (or filename) where you want to output the html. close_file : bool, default True Whether the file has to be closed after write. """ if isinstance(outfile, (str, bytes, Path)): fid = open(outfile, "wb") else: fid = outfile root = self.get_root() html = root.render(**kwargs) fid.write(html.encode("utf8")) if close_file: fid.close()
(self, outfile, close_file=True, **kwargs)
12,384
branca.element
to_dict
Returns a dict representation of the object.
def to_dict(self, depth=-1, ordered=True, **kwargs): """Returns a dict representation of the object.""" if ordered: dict_fun = OrderedDict else: dict_fun = dict out = dict_fun() out["name"] = self._name out["id"] = self._id if depth != 0: out["children"] = dict_fun( [ (name, child.to_dict(depth=depth - 1)) for name, child in self._children.items() ], ) # noqa return out
(self, depth=-1, ordered=True, **kwargs)
12,385
branca.element
to_json
Returns a JSON representation of the object.
def to_json(self, depth=-1, **kwargs): """Returns a JSON representation of the object.""" return json.dumps(self.to_dict(depth=depth, ordered=True), **kwargs)
(self, depth=-1, **kwargs)
12,386
ipyleaflet.leaflet
ColormapControl
ColormapControl class, with WidgetControl as parent class. A control which contains a colormap. Attributes ---------- caption : str, default 'caption' The caption of the colormap. colormap: branca.colormap.ColorMap instance, default linear.OrRd_06 The colormap used for the effect. value_min : float, default 0.0 The minimal value taken by the data to be represented by the colormap. value_max : float, default 1.0 The maximal value taken by the data to be represented by the colormap.
class ColormapControl(WidgetControl): """ColormapControl class, with WidgetControl as parent class. A control which contains a colormap. Attributes ---------- caption : str, default 'caption' The caption of the colormap. colormap: branca.colormap.ColorMap instance, default linear.OrRd_06 The colormap used for the effect. value_min : float, default 0.0 The minimal value taken by the data to be represented by the colormap. value_max : float, default 1.0 The maximal value taken by the data to be represented by the colormap. """ caption = Unicode("caption") colormap = Instance(ColorMap, default_value=linear.OrRd_06) value_min = CFloat(0.0) value_max = CFloat(1.0) @default("widget") def _default_widget(self): widget = Output( layout={"height": "40px", "width": "520px", "margin": "0px -19px 0px 0px"} ) with widget: colormap = self.colormap.scale(self.value_min, self.value_max) colormap.caption = self.caption display(colormap) return widget
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,443
ipyleaflet.leaflet
Control
Control abstract class. This is the base class for all ipyleaflet controls. A control is additional UI components on top of the Map. Attributes ---------- position: str, default 'topleft' The position of the control. Possible values are 'topright', 'topleft', 'bottomright' and 'bottomleft'.
class Control(Widget): """Control abstract class. This is the base class for all ipyleaflet controls. A control is additional UI components on top of the Map. Attributes ---------- position: str, default 'topleft' The position of the control. Possible values are 'topright', 'topleft', 'bottomright' and 'bottomleft'. """ _view_name = Unicode("LeafletControlView").tag(sync=True) _model_name = Unicode("LeafletControlModel").tag(sync=True) _view_module = Unicode("jupyter-leaflet").tag(sync=True) _model_module = Unicode("jupyter-leaflet").tag(sync=True) _view_module_version = Unicode(EXTENSION_VERSION).tag(sync=True) _model_module_version = Unicode(EXTENSION_VERSION).tag(sync=True) options = List(trait=Unicode()).tag(sync=True) position = Enum( ["topright", "topleft", "bottomright", "bottomleft"], default_value="topleft", help="""Possible values are topleft, topright, bottomleft or bottomright""", ).tag(sync=True, o=True) @default("options") def _default_options(self): return [name for name in self.traits(o=True)]
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,500
ipyleaflet.leaflet
ControlException
Custom LayerException class.
class ControlException(TraitError): """Custom LayerException class.""" pass
null
12,501
ipywidgets.widgets.domwidget
DOMWidget
Widget that can be inserted into the DOM Parameters ---------- tooltip: str tooltip caption layout: InstanceDict(Layout) widget layout
class DOMWidget(Widget): """Widget that can be inserted into the DOM Parameters ---------- tooltip: str tooltip caption layout: InstanceDict(Layout) widget layout """ _model_name = Unicode('DOMWidgetModel').tag(sync=True) _dom_classes = TypedTuple(trait=Unicode(), help="CSS classes applied to widget DOM element").tag(sync=True) tabbable = Bool(help="Is widget tabbable?", allow_none=True, default_value=None).tag(sync=True) tooltip = Unicode(None, allow_none=True, help="A tooltip caption.").tag(sync=True) layout = InstanceDict(Layout).tag(sync=True, **widget_serialization) def add_class(self, className): """ Adds a class to the top level element of the widget. Doesn't add the class if it already exists. """ if className not in self._dom_classes: self._dom_classes = list(self._dom_classes) + [className] return self def remove_class(self, className): """ Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist. """ if className in self._dom_classes: self._dom_classes = [c for c in self._dom_classes if c != className] return self def focus(self): """ Focus on the widget. """ self.send({'do':'focus'}) def blur(self): """ Blur the widget. """ self.send({'do':'blur'}) def _repr_keys(self): for key in super()._repr_keys(): # Exclude layout if it had the default value if key == 'layout': value = getattr(self, key) if repr(value) == '%s()' % value.__class__.__name__: continue yield key # We also need to include _dom_classes in repr for reproducibility if self._dom_classes: yield '_dom_classes'
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,562
traitlets.traitlets
Dict
An instance of a Python dict. One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method. .. versionchanged:: 5.0 Added key_trait for validating dict keys. .. versionchanged:: 5.0 Deprecated ambiguous ``trait``, ``traits`` args in favor of ``value_trait``, ``per_key_traits``.
class Dict(Instance["dict[K, V]"]): """An instance of a Python dict. One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method. .. versionchanged:: 5.0 Added key_trait for validating dict keys. .. versionchanged:: 5.0 Deprecated ambiguous ``trait``, ``traits`` args in favor of ``value_trait``, ``per_key_traits``. """ _value_trait = None _key_trait = None def __init__( self, value_trait: TraitType[t.Any, t.Any] | dict[K, V] | Sentinel | None = None, per_key_traits: t.Any = None, key_trait: TraitType[t.Any, t.Any] | None = None, default_value: dict[K, V] | Sentinel | None = Undefined, **kwargs: t.Any, ) -> None: """Create a dict trait type from a Python dict. The default value is created by doing ``dict(default_value)``, which creates a copy of the ``default_value``. Parameters ---------- value_trait : TraitType [ optional ] The specified trait type to check and use to restrict the values of the dict. If unspecified, values are not checked. per_key_traits : Dictionary of {keys:trait types} [ optional, keyword-only ] A Python dictionary containing the types that are valid for restricting the values of the dict on a per-key basis. Each value in this dict should be a Trait for validating key_trait : TraitType [ optional, keyword-only ] The type for restricting the keys of the dict. If unspecified, the types of the keys are not checked. default_value : SequenceType [ optional, keyword-only ] The default value for the Dict. Must be dict, tuple, or None, and will be cast to a dict if not None. If any key or value traits are specified, the `default_value` must conform to the constraints. Examples -------- a dict whose values must be text >>> d = Dict(Unicode()) d2['n'] must be an integer d2['s'] must be text >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()}) d3's keys must be text d3's values must be integers >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode()) """ # handle deprecated keywords trait = kwargs.pop("trait", None) if trait is not None: if value_trait is not None: raise TypeError( "Found a value for both `value_trait` and its deprecated alias `trait`." ) value_trait = trait warn( "Keyword `trait` is deprecated in traitlets 5.0, use `value_trait` instead", DeprecationWarning, stacklevel=2, ) traits = kwargs.pop("traits", None) if traits is not None: if per_key_traits is not None: raise TypeError( "Found a value for both `per_key_traits` and its deprecated alias `traits`." ) per_key_traits = traits warn( "Keyword `traits` is deprecated in traitlets 5.0, use `per_key_traits` instead", DeprecationWarning, stacklevel=2, ) # Handling positional arguments if default_value is Undefined and value_trait is not None: if not is_trait(value_trait): assert not isinstance(value_trait, TraitType) default_value = value_trait value_trait = None if key_trait is None and per_key_traits is not None: if is_trait(per_key_traits): key_trait = per_key_traits per_key_traits = None # Handling default value if default_value is Undefined: default_value = {} if default_value is None: args: t.Any = None elif isinstance(default_value, dict): args = (default_value,) elif isinstance(default_value, SequenceTypes): args = (default_value,) else: raise TypeError("default value of Dict was %s" % default_value) # Case where a type of TraitType is provided rather than an instance if is_trait(value_trait): if isinstance(value_trait, type): warn( # type:ignore[unreachable] "Traits should be given as instances, not types (for example, `Int()`, not `Int`)" " Passing types is deprecated in traitlets 4.1.", DeprecationWarning, stacklevel=2, ) value_trait = value_trait() self._value_trait = value_trait elif value_trait is not None: raise TypeError( "`value_trait` must be a Trait or None, got %s" % repr_type(value_trait) ) if is_trait(key_trait): if isinstance(key_trait, type): warn( # type:ignore[unreachable] "Traits should be given as instances, not types (for example, `Int()`, not `Int`)" " Passing types is deprecated in traitlets 4.1.", DeprecationWarning, stacklevel=2, ) key_trait = key_trait() self._key_trait = key_trait elif key_trait is not None: raise TypeError("`key_trait` must be a Trait or None, got %s" % repr_type(key_trait)) self._per_key_traits = per_key_traits super().__init__(klass=dict, args=args, **kwargs) def element_error( self, obj: t.Any, element: t.Any, validator: t.Any, side: str = "Values" ) -> None: e = ( side + f" of the '{self.name}' trait of {class_of(obj)} instance must be {validator.info()}, but a value of {repr_type(element)} was specified." ) raise TraitError(e) def validate(self, obj: t.Any, value: t.Any) -> dict[K, V] | None: value = super().validate(obj, value) if value is None: return value return self.validate_elements(obj, value) def validate_elements(self, obj: t.Any, value: dict[t.Any, t.Any]) -> dict[K, V] | None: per_key_override = self._per_key_traits or {} key_trait = self._key_trait value_trait = self._value_trait if not (key_trait or value_trait or per_key_override): return value validated = {} for key in value: v = value[key] if key_trait: try: key = key_trait._validate(obj, key) except TraitError: self.element_error(obj, key, key_trait, "Keys") active_value_trait = per_key_override.get(key, value_trait) if active_value_trait: try: v = active_value_trait._validate(obj, v) except TraitError: self.element_error(obj, v, active_value_trait, "Values") validated[key] = v return self.klass(validated) # type:ignore[misc,operator] def class_init(self, cls: type[t.Any], name: str | None) -> None: if isinstance(self._value_trait, TraitType): self._value_trait.class_init(cls, None) if isinstance(self._key_trait, TraitType): self._key_trait.class_init(cls, None) if self._per_key_traits is not None: for trait in self._per_key_traits.values(): trait.class_init(cls, None) super().class_init(cls, name) def subclass_init(self, cls: type[t.Any]) -> None: if isinstance(self._value_trait, TraitType): self._value_trait.subclass_init(cls) if isinstance(self._key_trait, TraitType): self._key_trait.subclass_init(cls) if self._per_key_traits is not None: for trait in self._per_key_traits.values(): trait.subclass_init(cls) # explicitly not calling super().subclass_init(cls) # to opt out of instance_init def from_string(self, s: str) -> dict[K, V] | None: """Load value from a single string""" if not isinstance(s, str): raise TypeError(f"from_string expects a string, got {s!r} of type {type(s)}") try: return t.cast("dict[K, V]", self.from_string_list([s])) except Exception: test = _safe_literal_eval(s) if isinstance(test, dict): return test raise def from_string_list(self, s_list: list[str]) -> t.Any: """Return a dict from a list of config strings. This is where we parse CLI configuration. Each item should have the form ``"key=value"``. item parsing is done in :meth:`.item_from_string`. """ if len(s_list) == 1 and s_list[0] == "None" and self.allow_none: return None if len(s_list) == 1 and s_list[0].startswith("{") and s_list[0].endswith("}"): warn( f"--{self.name}={s_list[0]} for dict-traits is deprecated in traitlets 5.0. " f"You can pass --{self.name} <key=value> ... multiple times to add items to a dict.", DeprecationWarning, stacklevel=2, ) return literal_eval(s_list[0]) combined = {} for d in [self.item_from_string(s) for s in s_list]: combined.update(d) return combined def item_from_string(self, s: str) -> dict[K, V]: """Cast a single-key dict from a string. Evaluated when parsing CLI configuration from a string. Dicts expect strings of the form key=value. Returns a one-key dictionary, which will be merged in :meth:`.from_string_list`. """ if "=" not in s: raise TraitError( f"'{self.__class__.__name__}' options must have the form 'key=value', got {s!r}" ) key, value = s.split("=", 1) # cast key with key trait, if defined if self._key_trait: key = self._key_trait.from_string(key) # cast value with value trait, if defined (per-key or global) value_trait = (self._per_key_traits or {}).get(key, self._value_trait) if value_trait: value = value_trait.from_string(value) return t.cast("dict[K, V]", {key: value})
(value_trait: 'TraitType[t.Any, t.Any] | dict[K, V] | Sentinel | None' = None, per_key_traits: 't.Any' = None, key_trait: 'TraitType[t.Any, t.Any] | None' = None, default_value: Any = traitlets.Undefined, **kwargs: 't.Any') -> 'None'
12,564
traitlets.traitlets
__init__
Create a dict trait type from a Python dict. The default value is created by doing ``dict(default_value)``, which creates a copy of the ``default_value``. Parameters ---------- value_trait : TraitType [ optional ] The specified trait type to check and use to restrict the values of the dict. If unspecified, values are not checked. per_key_traits : Dictionary of {keys:trait types} [ optional, keyword-only ] A Python dictionary containing the types that are valid for restricting the values of the dict on a per-key basis. Each value in this dict should be a Trait for validating key_trait : TraitType [ optional, keyword-only ] The type for restricting the keys of the dict. If unspecified, the types of the keys are not checked. default_value : SequenceType [ optional, keyword-only ] The default value for the Dict. Must be dict, tuple, or None, and will be cast to a dict if not None. If any key or value traits are specified, the `default_value` must conform to the constraints. Examples -------- a dict whose values must be text >>> d = Dict(Unicode()) d2['n'] must be an integer d2['s'] must be text >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()}) d3's keys must be text d3's values must be integers >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode())
def __init__( self, value_trait: TraitType[t.Any, t.Any] | dict[K, V] | Sentinel | None = None, per_key_traits: t.Any = None, key_trait: TraitType[t.Any, t.Any] | None = None, default_value: dict[K, V] | Sentinel | None = Undefined, **kwargs: t.Any, ) -> None: """Create a dict trait type from a Python dict. The default value is created by doing ``dict(default_value)``, which creates a copy of the ``default_value``. Parameters ---------- value_trait : TraitType [ optional ] The specified trait type to check and use to restrict the values of the dict. If unspecified, values are not checked. per_key_traits : Dictionary of {keys:trait types} [ optional, keyword-only ] A Python dictionary containing the types that are valid for restricting the values of the dict on a per-key basis. Each value in this dict should be a Trait for validating key_trait : TraitType [ optional, keyword-only ] The type for restricting the keys of the dict. If unspecified, the types of the keys are not checked. default_value : SequenceType [ optional, keyword-only ] The default value for the Dict. Must be dict, tuple, or None, and will be cast to a dict if not None. If any key or value traits are specified, the `default_value` must conform to the constraints. Examples -------- a dict whose values must be text >>> d = Dict(Unicode()) d2['n'] must be an integer d2['s'] must be text >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()}) d3's keys must be text d3's values must be integers >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode()) """ # handle deprecated keywords trait = kwargs.pop("trait", None) if trait is not None: if value_trait is not None: raise TypeError( "Found a value for both `value_trait` and its deprecated alias `trait`." ) value_trait = trait warn( "Keyword `trait` is deprecated in traitlets 5.0, use `value_trait` instead", DeprecationWarning, stacklevel=2, ) traits = kwargs.pop("traits", None) if traits is not None: if per_key_traits is not None: raise TypeError( "Found a value for both `per_key_traits` and its deprecated alias `traits`." ) per_key_traits = traits warn( "Keyword `traits` is deprecated in traitlets 5.0, use `per_key_traits` instead", DeprecationWarning, stacklevel=2, ) # Handling positional arguments if default_value is Undefined and value_trait is not None: if not is_trait(value_trait): assert not isinstance(value_trait, TraitType) default_value = value_trait value_trait = None if key_trait is None and per_key_traits is not None: if is_trait(per_key_traits): key_trait = per_key_traits per_key_traits = None # Handling default value if default_value is Undefined: default_value = {} if default_value is None: args: t.Any = None elif isinstance(default_value, dict): args = (default_value,) elif isinstance(default_value, SequenceTypes): args = (default_value,) else: raise TypeError("default value of Dict was %s" % default_value) # Case where a type of TraitType is provided rather than an instance if is_trait(value_trait): if isinstance(value_trait, type): warn( # type:ignore[unreachable] "Traits should be given as instances, not types (for example, `Int()`, not `Int`)" " Passing types is deprecated in traitlets 4.1.", DeprecationWarning, stacklevel=2, ) value_trait = value_trait() self._value_trait = value_trait elif value_trait is not None: raise TypeError( "`value_trait` must be a Trait or None, got %s" % repr_type(value_trait) ) if is_trait(key_trait): if isinstance(key_trait, type): warn( # type:ignore[unreachable] "Traits should be given as instances, not types (for example, `Int()`, not `Int`)" " Passing types is deprecated in traitlets 4.1.", DeprecationWarning, stacklevel=2, ) key_trait = key_trait() self._key_trait = key_trait elif key_trait is not None: raise TypeError("`key_trait` must be a Trait or None, got %s" % repr_type(key_trait)) self._per_key_traits = per_key_traits super().__init__(klass=dict, args=args, **kwargs)
(self, value_trait: 'TraitType[t.Any, t.Any] | dict[K, V] | Sentinel | None' = None, per_key_traits: 't.Any' = None, key_trait: 'TraitType[t.Any, t.Any] | None' = None, default_value: 'dict[K, V] | Sentinel | None' = traitlets.Undefined, **kwargs: 't.Any') -> 'None'
12,568
traitlets.traitlets
_resolve_classes
null
def _resolve_classes(self) -> None: if isinstance(self.klass, str): self.klass = self._resolve_string(self.klass)
(self) -> NoneType
12,569
traitlets.traitlets
_resolve_string
Resolve a string supplied for a type into an actual object.
def _resolve_string(self, string: str) -> t.Any: """ Resolve a string supplied for a type into an actual object. """ return import_item(string)
(self, string: str) -> Any
12,571
traitlets.traitlets
class_init
null
def class_init(self, cls: type[t.Any], name: str | None) -> None: if isinstance(self._value_trait, TraitType): self._value_trait.class_init(cls, None) if isinstance(self._key_trait, TraitType): self._key_trait.class_init(cls, None) if self._per_key_traits is not None: for trait in self._per_key_traits.values(): trait.class_init(cls, None) super().class_init(cls, name)
(self, cls: type[typing.Any], name: str | None) -> NoneType
12,573
traitlets.traitlets
default_value_repr
null
def default_value_repr(self) -> str: return repr(self.make_dynamic_default())
(self) -> str
12,574
traitlets.traitlets
element_error
null
def element_error( self, obj: t.Any, element: t.Any, validator: t.Any, side: str = "Values" ) -> None: e = ( side + f" of the '{self.name}' trait of {class_of(obj)} instance must be {validator.info()}, but a value of {repr_type(element)} was specified." ) raise TraitError(e)
(self, obj: Any, element: Any, validator: Any, side: str = 'Values') -> NoneType
12,576
traitlets.traitlets
from_string
Load value from a single string
def from_string(self, s: str) -> dict[K, V] | None: """Load value from a single string""" if not isinstance(s, str): raise TypeError(f"from_string expects a string, got {s!r} of type {type(s)}") try: return t.cast("dict[K, V]", self.from_string_list([s])) except Exception: test = _safe_literal_eval(s) if isinstance(test, dict): return test raise
(self, s: 'str') -> 'dict[K, V] | None'
12,577
traitlets.traitlets
from_string_list
Return a dict from a list of config strings. This is where we parse CLI configuration. Each item should have the form ``"key=value"``. item parsing is done in :meth:`.item_from_string`.
def from_string_list(self, s_list: list[str]) -> t.Any: """Return a dict from a list of config strings. This is where we parse CLI configuration. Each item should have the form ``"key=value"``. item parsing is done in :meth:`.item_from_string`. """ if len(s_list) == 1 and s_list[0] == "None" and self.allow_none: return None if len(s_list) == 1 and s_list[0].startswith("{") and s_list[0].endswith("}"): warn( f"--{self.name}={s_list[0]} for dict-traits is deprecated in traitlets 5.0. " f"You can pass --{self.name} <key=value> ... multiple times to add items to a dict.", DeprecationWarning, stacklevel=2, ) return literal_eval(s_list[0]) combined = {} for d in [self.item_from_string(s) for s in s_list]: combined.update(d) return combined
(self, s_list: list[str]) -> Any
12,581
traitlets.traitlets
info
null
def info(self) -> str: if isinstance(self.klass, str): result = add_article(self.klass) else: result = describe("a", self.klass) if self.allow_none: result += " or None" return result
(self) -> str
12,583
traitlets.traitlets
instance_init
null
def instance_init(self, obj: t.Any) -> None: # we can't do this in subclass_init because that # might be called before all imports are done. self._resolve_classes()
(self, obj: Any) -> NoneType
12,584
traitlets.traitlets
item_from_string
Cast a single-key dict from a string. Evaluated when parsing CLI configuration from a string. Dicts expect strings of the form key=value. Returns a one-key dictionary, which will be merged in :meth:`.from_string_list`.
def item_from_string(self, s: str) -> dict[K, V]: """Cast a single-key dict from a string. Evaluated when parsing CLI configuration from a string. Dicts expect strings of the form key=value. Returns a one-key dictionary, which will be merged in :meth:`.from_string_list`. """ if "=" not in s: raise TraitError( f"'{self.__class__.__name__}' options must have the form 'key=value', got {s!r}" ) key, value = s.split("=", 1) # cast key with key trait, if defined if self._key_trait: key = self._key_trait.from_string(key) # cast value with value trait, if defined (per-key or global) value_trait = (self._per_key_traits or {}).get(key, self._value_trait) if value_trait: value = value_trait.from_string(value) return t.cast("dict[K, V]", {key: value})
(self, s: 'str') -> 'dict[K, V]'
12,585
traitlets.traitlets
make_dynamic_default
null
def make_dynamic_default(self) -> T | None: if (self.default_args is None) and (self.default_kwargs is None): return None assert self.klass is not None return self.klass(*(self.default_args or ()), **(self.default_kwargs or {})) # type:ignore[operator]
(self) -> Optional[~T]
12,588
traitlets.traitlets
subclass_init
null
def subclass_init(self, cls: type[t.Any]) -> None: if isinstance(self._value_trait, TraitType): self._value_trait.subclass_init(cls) if isinstance(self._key_trait, TraitType): self._key_trait.subclass_init(cls) if self._per_key_traits is not None: for trait in self._per_key_traits.values(): trait.subclass_init(cls) # explicitly not calling super().subclass_init(cls) # to opt out of instance_init
(self, cls: type[typing.Any]) -> NoneType
12,590
traitlets.traitlets
validate
null
def validate(self, obj: t.Any, value: t.Any) -> dict[K, V] | None: value = super().validate(obj, value) if value is None: return value return self.validate_elements(obj, value)
(self, obj: 't.Any', value: 't.Any') -> 'dict[K, V] | None'
12,591
traitlets.traitlets
validate_elements
null
def validate_elements(self, obj: t.Any, value: dict[t.Any, t.Any]) -> dict[K, V] | None: per_key_override = self._per_key_traits or {} key_trait = self._key_trait value_trait = self._value_trait if not (key_trait or value_trait or per_key_override): return value validated = {} for key in value: v = value[key] if key_trait: try: key = key_trait._validate(obj, key) except TraitError: self.element_error(obj, key, key_trait, "Keys") active_value_trait = per_key_override.get(key, value_trait) if active_value_trait: try: v = active_value_trait._validate(obj, v) except TraitError: self.element_error(obj, v, active_value_trait, "Values") validated[key] = v return self.klass(validated) # type:ignore[misc,operator]
(self, obj: 't.Any', value: 'dict[t.Any, t.Any]') -> 'dict[K, V] | None'
12,592
ipyleaflet.leaflet
DivIcon
DivIcon class. Custom lightweight icon for markers that uses a simple <div> element instead of an image used for markers. Attributes ---------- html : string Custom HTML code to put inside the div element, empty by default. bg_pos : tuple, default [0, 0] Optional relative position of the background, in pixels. icon_size: tuple, default None The size of the icon, in pixels. icon_anchor: tuple, default None The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if icon_size is specified. popup_anchor: tuple, default None The coordinates of the point from which popups will "open", relative to the icon anchor.
class DivIcon(UILayer): """DivIcon class. Custom lightweight icon for markers that uses a simple <div> element instead of an image used for markers. Attributes ---------- html : string Custom HTML code to put inside the div element, empty by default. bg_pos : tuple, default [0, 0] Optional relative position of the background, in pixels. icon_size: tuple, default None The size of the icon, in pixels. icon_anchor: tuple, default None The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if icon_size is specified. popup_anchor: tuple, default None The coordinates of the point from which popups will "open", relative to the icon anchor. """ _view_name = Unicode("LeafletDivIconView").tag(sync=True) _model_name = Unicode("LeafletDivIconModel").tag(sync=True) html = Unicode("").tag(sync=True, o=True) bg_pos = List([0, 0], allow_none=True).tag(sync=True, o=True) icon_size = List(default_value=None, allow_none=True).tag(sync=True, o=True) icon_anchor = List(default_value=None, allow_none=True).tag(sync=True, o=True) popup_anchor = List([0, 0], allow_none=True).tag(sync=True, o=True) @validate("icon_size", "icon_anchor", "popup_anchor") def _validate_attr(self, proposal): value = proposal["value"] # Workaround Traitlets which does not respect the None default value if value is None or len(value) == 0: return None if len(value) != 2: raise TraitError( "The value should be of size 2, but {} was given".format(value) ) return value
(*args: 't.Any', **kwargs: 't.Any') -> 't.Any'
12,657
ipyleaflet.leaflet
DrawControl
DrawControl class. Drawing tools for drawing on the map.
class DrawControl(DrawControlBase): """DrawControl class. Drawing tools for drawing on the map. """ _view_name = Unicode("LeafletDrawControlView").tag(sync=True) _model_name = Unicode("LeafletDrawControlModel").tag(sync=True) # Enable each of the following drawing by giving them a non empty dict of options # You can add Leaflet style options in the shapeOptions sub-dict # See https://github.com/Leaflet/Leaflet.draw#polylineoptions and # https://github.com/Leaflet/Leaflet.draw#polygonoptions polyline = Dict({ 'shapeOptions': {} }).tag(sync=True) polygon = Dict({ 'shapeOptions': {} }).tag(sync=True) circlemarker = Dict({ 'shapeOptions': {} }).tag(sync=True) last_draw = Dict({"type": "Feature", "geometry": None}) last_action = Unicode() def __init__(self, **kwargs): super(DrawControl, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event) def _handle_leaflet_event(self, _, content, buffers): if content.get("event", "").startswith("draw"): event, action = content.get("event").split(":") self.last_draw = content.get("geo_json") self.last_action = action self._draw_callbacks(self, action=action, geo_json=self.last_draw)
(**kwargs)
12,662
ipyleaflet.leaflet
__init__
null
def __init__(self, **kwargs): super(DrawControl, self).__init__(**kwargs) self.on_msg(self._handle_leaflet_event)
(self, **kwargs)
12,673
ipyleaflet.leaflet
_handle_leaflet_event
null
def _handle_leaflet_event(self, _, content, buffers): if content.get("event", "").startswith("draw"): event, action = content.get("event").split(":") self.last_draw = content.get("geo_json") self.last_action = action self._draw_callbacks(self, action=action, geo_json=self.last_draw)
(self, _, content, buffers)
12,688
ipyleaflet.leaflet
clear
Clear all drawings.
def clear(self): """Clear all drawings.""" self.send({"msg": "clear"})
(self)
12,689
ipyleaflet.leaflet
clear_circle_markers
Clear all circle markers.
def clear_circle_markers(self): """Clear all circle markers.""" self.send({"msg": "clear_circle_markers"})
(self)
12,690
ipyleaflet.leaflet
clear_circles
Clear all circles.
def clear_circles(self): """Clear all circles.""" self.send({"msg": "clear_circles"})
(self)
12,691
ipyleaflet.leaflet
clear_markers
Clear all markers.
def clear_markers(self): """Clear all markers.""" self.send({"msg": "clear_markers"})
(self)
12,692
ipyleaflet.leaflet
clear_polygons
Clear all polygons.
def clear_polygons(self): """Clear all polygons.""" self.send({"msg": "clear_polygons"})
(self)
12,693
ipyleaflet.leaflet
clear_polylines
Clear all polylines.
def clear_polylines(self): """Clear all polylines.""" self.send({"msg": "clear_polylines"})
(self)