INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Given a list of Option objects (such as those returned from
OptsSpec.parse_options) or an %opts or %%opts magic string,
return a list of corresponding option builder reprs. The
namespace is typically given as 'hv' if fully qualified
namespaces are desired. | def _builder_reprs(cls, options, namespace=None, ns=None):
"""
Given a list of Option objects (such as those returned from
OptsSpec.parse_options) or an %opts or %%opts magic string,
return a list of corresponding option builder reprs. The
namespace is typically given as 'hv' if ... |
Returns a dictionary of element names to allowed keywords | def _element_keywords(cls, backend, elements=None):
"Returns a dictionary of element names to allowed keywords"
if backend not in Store.loaded_backends():
return {}
mapping = {}
backend_options = Store.options(backend)
elements = elements if elements is not None else... |
Generates a list of streams to attach to the returned DynamicMap.
If the input is a DynamicMap any streams that are supplying values
for the key dimension of the input are inherited. And the list
of supplied stream classes and instances are processed and
added to the list. | def _get_streams(self, map_obj, watch=True):
"""
Generates a list of streams to attach to the returned DynamicMap.
If the input is a DynamicMap any streams that are supplying values
for the key dimension of the input are inherited. And the list
of supplied stream classes and inst... |
Evaluates any parameterized methods in the kwargs | def _eval_kwargs(self):
"""Evaluates any parameterized methods in the kwargs"""
evaled_kwargs = {}
for k, v in self.p.kwargs.items():
if util.is_param_method(v):
v = v()
evaled_kwargs[k] = v
return evaled_kwargs |
Generate function to dynamically apply the operation.
Wraps an existing HoloMap or DynamicMap. | def _dynamic_operation(self, map_obj):
"""
Generate function to dynamically apply the operation.
Wraps an existing HoloMap or DynamicMap.
"""
if not isinstance(map_obj, DynamicMap):
def dynamic_operation(*key, **kwargs):
kwargs = dict(self._eval_kwargs... |
Accepts a HoloMap and a dynamic callback function creating
an equivalent DynamicMap from the HoloMap. | def _make_dynamic(self, hmap, dynamic_fn, streams):
"""
Accepts a HoloMap and a dynamic callback function creating
an equivalent DynamicMap from the HoloMap.
"""
if isinstance(hmap, ViewableElement):
return DynamicMap(dynamic_fn, streams=streams)
dim_values = ... |
Triggers update to a plot on a refresh event | def _trigger_refresh(self, key):
"Triggers update to a plot on a refresh event"
if self.top_level:
self.update(key)
else:
self.current_key = None
self.current_frame = None |
Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
values: Array of values to be normalized
min (float, optional): Lower bound of normalization range
max (float, optional): Upper bound of normalization range
Returns:
Array of nor... | def norm(values, min=None, max=None):
"""Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
values: Array of values to be normalized
min (float, optional): Lower bound of normalization range
max (float, optional): Upper bound of normaliza... |
Bins data into declared bins
Bins data into declared bins. By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined.
Args:
values: Array of values to be binned
bins: List or array containing the bin boundaries
labels: List of labe... | def bin(values, bins, labels=None):
"""Bins data into declared bins
Bins data into declared bins. By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined.
Args:
values: Array of values to be binned
bins: List or array containing the ... |
Maps discrete values to supplied categories.
Replaces discrete values in input array with a fixed set of
categories defined either as a list or dictionary.
Args:
values: Array of values to be categorized
categories: List or dict of categories to map inputs to
default: Default value... | def categorize(values, categories, default=None):
"""Maps discrete values to supplied categories.
Replaces discrete values in input array with a fixed set of
categories defined either as a list or dictionary.
Args:
values: Array of values to be categorized
categories: List or dict of c... |
Bins continuous values.
Bins continuous using the provided bins and assigns labels
either computed from each bins center point or from the
supplied labels.
Args:
bins: List or array containing the bin boundaries
labels: List of labels to assign to each bin
... | def bin(self, bins, labels=None):
"""Bins continuous values.
Bins continuous using the provided bins and assigns labels
either computed from each bins center point or from the
supplied labels.
Args:
bins: List or array containing the bin boundaries
label... |
Replaces discrete values with supplied categories
Replaces discrete values in input array into a fixed set of
categories defined either as a list or dictionary.
Args:
categories: List or dict of categories to map inputs to
default: Default value to assign if value not i... | def categorize(self, categories, default=None):
"""Replaces discrete values with supplied categories
Replaces discrete values in input array into a fixed set of
categories defined either as a list or dictionary.
Args:
categories: List or dict of categories to map inputs to
... |
Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
limits: tuple of (min, max) defining the normalization range | def norm(self, limits=None):
"""Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
limits: tuple of (min, max) defining the normalization range
"""
kwargs = {}
if limits is not None:
kwargs = {'min': li... |
Determines whether the dim transform can be applied to the
Dataset, i.e. whether all referenced dimensions can be
resolved. | def applies(self, dataset):
"""
Determines whether the dim transform can be applied to the
Dataset, i.e. whether all referenced dimensions can be
resolved.
"""
if isinstance(self.dimension, dim):
applies = self.dimension.applies(dataset)
else:
... |
Evaluates the transform on the supplied dataset.
Args:
dataset: Dataset object to evaluate the expression on
flat: Whether to flatten the returned array
expanded: Whether to use the expanded expand values
ranges: Dictionary for ranges for normalization
... | def apply(self, dataset, flat=False, expanded=None, ranges={}, all_values=False):
"""Evaluates the transform on the supplied dataset.
Args:
dataset: Dataset object to evaluate the expression on
flat: Whether to flatten the returned array
expanded: Whether to use the ... |
Computes the node quad glyph data.x | def _compute_quads(self, element, data, mapping):
"""
Computes the node quad glyph data.x
"""
quad_mapping = {'left': 'x0', 'right': 'x1', 'bottom': 'y0', 'top': 'y1'}
quad_data = dict(data['scatter_1'])
quad_data.update({'x0': [], 'x1': [], 'y0': [], 'y1': []})
f... |
Computes labels for the nodes and adds it to the data. | def _compute_labels(self, element, data, mapping):
"""
Computes labels for the nodes and adds it to the data.
"""
if element.vdims:
edges = Dataset(element)[element[element.vdims[0].name]>0]
nodes = list(np.unique([edges.dimension_values(i) for i in range(2)]))
... |
Replace edge start and end hover data with label_index data. | def _patch_hover(self, element, data):
"""
Replace edge start and end hover data with label_index data.
"""
if not (self.inspection_policy == 'edges' and 'hover' in self.handles):
return
lidx = element.nodes.get_dimension(self.label_index)
src, tgt = [dimensio... |
Select a style by name, e.g. set_style('default'). To revert to the
previous style use the key 'unset' or False. | def set_style(key):
"""
Select a style by name, e.g. set_style('default'). To revert to the
previous style use the key 'unset' or False.
"""
if key is None:
return
elif not key or key in ['unset', 'backup']:
if 'backup' in styles:
plt.rcParams.update(styles['backup'])... |
Builds a parameter filter using the supplied pattern (may be a
general Python regular expression) | def regexp_filter(self_or_cls, pattern):
"""
Builds a parameter filter using the supplied pattern (may be a
general Python regular expression)
"""
def inner_filter(name, p):
name_match = re.search(pattern,name)
if name_match is not None:
re... |
Get parameter information from the supplied class or object. | def get_parameter_info(cls, obj, ansi=False, show_values=True,
pattern=None, max_col_len=40):
"""
Get parameter information from the supplied class or object.
"""
if cls.ppager is None: return ''
if pattern is not None:
obj = ParamFilter(ob... |
Turn the supplied heading text into a suitable heading with
optional underline and color. | def heading(cls, heading_text, char='=', level=0, ansi=False):
"""
Turn the supplied heading text into a suitable heading with
optional underline and color.
"""
heading_color = cls.headings[level] if ansi else '%s'
if char is None:
return heading_color % '%s\n... |
Show information about an object in the given category. ANSI
color codes may be enabled or disabled. | def info(cls, obj, ansi=False, backend='matplotlib', visualization=True,
pattern=None, elements=[]):
"""
Show information about an object in the given category. ANSI
color codes may be enabled or disabled.
"""
cls.elements = elements
ansi_escape = re.compile(... |
Return the type.group.label dotted information | def component_type(cls_or_slf, node):
"Return the type.group.label dotted information"
if node is None: return ''
return cls_or_slf.type_formatter.format(type=str(type(node).__name__)) |
Recursive function that builds up an ASCII tree given an
AttrTree node. | def recurse(cls_or_slf, node, attrpath=None, attrpaths=[], siblings=[], level=0, value_dims=True):
"""
Recursive function that builds up an ASCII tree given an
AttrTree node.
"""
level, lines = cls_or_slf.node_info(node, attrpath, attrpaths, siblings, level, value_dims)
a... |
Given a node, return relevant information. | def node_info(cls_or_slf, node, attrpath, attrpaths, siblings, level, value_dims):
"""
Given a node, return relevant information.
"""
opts = None
if hasattr(node, 'children'):
(lvl, lines) = (level, [(level, cls_or_slf.component_type(node))])
opts = cls_or... |
Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names. | def element_info(cls_or_slf, node, siblings, level, value_dims):
"""
Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names.
"""
info = cls_or_slf.component_type(node)
if len(node.kdims) >= 1:
info ... |
Split a Path type containing a single NaN separated path into
multiple subpaths. | def split_path(path):
"""
Split a Path type containing a single NaN separated path into
multiple subpaths.
"""
path = path.split(0, 1)[0]
values = path.dimension_values(0)
splits = np.concatenate([[0], np.where(np.isnan(values))[0]+1, [None]])
subpaths = []
data = PandasInterface.as_... |
Given a 2D selection consisting of slices/coordinates, a
SheetCoordinateSystem and the shape of the array returns a new
BoundingBox representing the sliced region. | def compute_slice_bounds(slices, scs, shape):
"""
Given a 2D selection consisting of slices/coordinates, a
SheetCoordinateSystem and the shape of the array returns a new
BoundingBox representing the sliced region.
"""
xidx, yidx = slices
ys, xs = shape
l, b, r, t = scs.bounds.lbrt()
... |
Aggregation function to get the first non-zero value. | def reduce_fn(x):
"""
Aggregation function to get the first non-zero value.
"""
values = x.values if pd and isinstance(x, pd.Series) else x
for v in values:
if not is_nan(v):
return v
return np.NaN |
Lay out nodes on a circle and add node index. | def circular_layout(nodes):
"""
Lay out nodes on a circle and add node index.
"""
N = len(nodes)
if not N:
return ([], [], [])
circ = np.pi/N*np.arange(N)*2
x = np.cos(circ)
y = np.sin(circ)
return (x, y, nodes) |
Compute quadratic bezier spline given start and end coordinate and
two control points. | def quadratic_bezier(start, end, c0=(0, 0), c1=(0, 0), steps=50):
"""
Compute quadratic bezier spline given start and end coordinate and
two control points.
"""
steps = np.linspace(0, 1, steps)
sx, sy = start
ex, ey = end
cx0, cy0 = c0
cx1, cy1 = c1
xs = ((1-steps)**3*sx + 3*((1-... |
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation depends on pandas and is a lot faster than the pure
NumPy equivalent. | def connect_edges_pd(graph):
"""
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation depends on pandas and is a lot faster than the pure
NumPy equivalent.
"""
edges = graph.dframe()
edges.index.name = 'grap... |
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation just uses internal HoloViews operations and will be a
lot slower than the pandas equivalent. | def connect_edges(graph):
"""
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation just uses internal HoloViews operations and will be a
lot slower than the pandas equivalent.
"""
paths = []
for start, end ... |
Get the coordinates of the 2D aggregate, maintaining the correct
sorting order. | def _get_coords(self, obj):
"""
Get the coordinates of the 2D aggregate, maintaining the correct
sorting order.
"""
xdim, ydim = obj.dimensions(label=True)[:2]
xcoords = obj.dimension_values(xdim, False)
ycoords = obj.dimension_values(ydim, False)
# Deter... |
Generates a gridded Dataset from a column-based dataset and
lists of xcoords and ycoords | def _aggregate_dataset(self, obj, xcoords, ycoords):
"""
Generates a gridded Dataset from a column-based dataset and
lists of xcoords and ycoords
"""
dim_labels = obj.dimensions(label=True)
vdims = obj.dimensions()[2:]
xdim, ydim = dim_labels[:2]
shape = (... |
Generates a categorical 2D aggregate by inserting NaNs at all
cross-product locations that do not already have a value assigned.
Returns a 2D gridded Dataset object. | def _process(self, obj, key=None):
"""
Generates a categorical 2D aggregate by inserting NaNs at all
cross-product locations that do not already have a value assigned.
Returns a 2D gridded Dataset object.
"""
if isinstance(obj, Dataset) and obj.interface.gridded:
... |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None, plot=None, plots=None, source=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
element = self.hmap.last
key = self.keys[-1]
self.current_frame = element
... |
Updates an existing plot with data corresponding
to the key. | def update_frame(self, key, ranges=None, plot=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
element = self._get_frame(key)
self._get_title_div(key, '12pt')
# Cache frame object id to skip updating data if unchanged
previous_i... |
The set of samples available along a particular dimension. | def dimension_values(self, dim, expanded=True, flat=True):
"""
The set of samples available along a particular dimension.
"""
dim_idx = self.get_dimension_index(dim)
if not expanded and dim_idx == 0:
return np.array(range(self.data.shape[1]))
elif not expanded... |
Sample the Raster along one or both of its dimensions,
returning a reduced dimensionality type, which is either
a ItemTable, Curve or Scatter. If two dimension samples
and a new_xaxis is provided the sample will be the value
of the sampled unit indexed by the value in the new_xaxis
... | def sample(self, samples=[], **sample_values):
"""
Sample the Raster along one or both of its dimensions,
returning a reduced dimensionality type, which is either
a ItemTable, Curve or Scatter. If two dimension samples
and a new_xaxis is provided the sample will be the value
... |
Reduces the Raster using functions provided via the
kwargs, where the keyword is the dimension to be reduced.
Optionally a label_prefix can be provided to prepend to
the result Element label. | def reduce(self, dimensions=None, function=None, **reduce_map):
"""
Reduces the Raster using functions provided via the
kwargs, where the keyword is the dimension to be reduced.
Optionally a label_prefix can be provided to prepend to
the result Element label.
"""
... |
Returns a clone of the object with matching parameter values
containing the specified args and kwargs.
If shared_data is set to True and no data explicitly supplied,
the clone will share data with the original. May also supply
a new_type, which will inherit all shared parameters. | def clone(self, data=None, shared_data=True, new_type=None, link=True,
*args, **overrides):
"""
Returns a clone of the object with matching parameter values
containing the specified args and kwargs.
If shared_data is set to True and no data explicitly supplied,
the... |
Allows selecting data by the slices, sets and scalar values
along a particular dimension. The indices should be supplied as
keywords mapping between the selected dimension and
value. Additionally selection_specs (taking the form of a list
of type.group.label strings, types or functions) ... | def select(self, selection_specs=None, **selection):
"""
Allows selecting data by the slices, sets and scalar values
along a particular dimension. The indices should be supplied as
keywords mapping between the selected dimension and
value. Additionally selection_specs (taking the... |
Allows sampling of an Image as an iterator of coordinates
matching the key dimensions, returning a new object containing
just the selected samples. Alternatively may supply kwargs to
sample a coordinate on an object. On an Image the coordinates
are continuously indexed and will always sn... | def sample(self, samples=[], **kwargs):
"""
Allows sampling of an Image as an iterator of coordinates
matching the key dimensions, returning a new object containing
just the selected samples. Alternatively may supply kwargs to
sample a coordinate on an object. On an Image the coo... |
Given a single coordinate or multiple coordinates as
a tuple or list of tuples or keyword arguments matching
the dimension closest will find the closest actual x/y
coordinates. | def closest(self, coords=[], **kwargs):
"""
Given a single coordinate or multiple coordinates as
a tuple or list of tuples or keyword arguments matching
the dimension closest will find the closest actual x/y
coordinates.
"""
if kwargs and coords:
raise... |
Returns an raster element or raw numpy array from a PNG image
file, using matplotlib.
The specified height determines the bounds of the raster
object in sheet coordinates: by default the height is 1 unit
with the width scaled appropriately by the image aspect ratio.
Note that a... | def load_image(cls, filename, height=1, array=False, bounds=None, bare=False, **kwargs):
"""
Returns an raster element or raw numpy array from a PNG image
file, using matplotlib.
The specified height determines the bounds of the raster
object in sheet coordinates: by default the... |
Conversion from HSV to RGB. | def rgb(self):
"""
Conversion from HSV to RGB.
"""
coords = tuple(self.dimension_values(d, expanded=False)
for d in self.kdims)
data = [self.dimension_values(d, flat=False)
for d in self.vdims]
hsv = self.hsv_to_rgb(*data[:3])
... |
Converts a QuadMesh into a TriMesh. | def trimesh(self):
"""
Converts a QuadMesh into a TriMesh.
"""
# Generate vertices
xs = self.interface.coords(self, 0, edges=True)
ys = self.interface.coords(self, 1, edges=True)
if xs.ndim == 1:
if np.all(xs[1:] < xs[:-1]):
xs = xs[::... |
Fixed version of IPyton.completer.completions_sorting_key | def completions_sorting_key(cls, word):
"Fixed version of IPyton.completer.completions_sorting_key"
prio1, prio2 = 0, 0
if word.startswith('__'): prio1 = 2
elif word.startswith('_'): prio1 = 1
if word.endswith('='): prio1 = -1
if word.startswith('%%'):
if... |
Finds the list of resources from the keyword parameters and pops
them out of the params dictionary. | def _get_resources(self, args, params):
"""
Finds the list of resources from the keyword parameters and pops
them out of the params dictionary.
"""
resources = []
disabled = []
for resource in ['holoviews'] + list(Store.renderers.keys()):
if resource i... |
Displays javascript and CSS to initialize HoloViews widgets. | def load_hvjs(cls, logo=False, bokeh_logo=False, mpl_logo=False, plotly_logo=False,
JS=True, message='HoloViewsJS successfully loaded.'):
"""
Displays javascript and CSS to initialize HoloViews widgets.
"""
import jinja2
# Evaluate load_notebook.html template wi... |
Generates a docstring that can be used to enable tab-completion
of resources. | def tab_completion_docstring(self_or_cls):
"""
Generates a docstring that can be used to enable tab-completion
of resources.
"""
elements = ['%s=Boolean' %k for k in list(Store.renderers.keys())]
for name, p in self_or_cls.params().items():
param_type = p.__cl... |
Get the dictionary of valid completions | def setup_completer(cls):
"Get the dictionary of valid completions"
try:
for element in Store.options().keys():
options = Store.options()['.'.join(element)]
plotkws = options['plot'].allowed_keywords
stylekws = options['style'].allowed_keywords... |
Supply the appropriate key in Store.options and supply
suggestions for further completion. | def dotted_completion(cls, line, sorted_keys, compositor_defs):
"""
Supply the appropriate key in Store.options and supply
suggestions for further completion.
"""
completion_key, suggestions = None, []
tokens = [t for t in reversed(line.replace('.', ' ').split())]
... |
Tab completion hook for the %%opts cell magic. | def option_completer(cls, k,v):
"Tab completion hook for the %%opts cell magic."
line = v.text_until_cursor
completions = cls.setup_completer()
compositor_defs = {el.group:el.output_type.__name__
for el in Compositor.definitions if el.group}
return cls.... |
Registers the Link | def link(self):
"""
Registers the Link
"""
if self.source in self.registry:
links = self.registry[self.source]
params = {
k: v for k, v in self.get_param_values() if k != 'name'}
for link in links:
link_params = {
... |
Unregisters the Link | def unlink(self):
"""
Unregisters the Link
"""
links = self.registry.get(self.source)
if self in links:
links.pop(links.index(self)) |
Get factors for categorical axes. | def _get_factors(self, element):
"""
Get factors for categorical axes.
"""
if not element.kdims:
xfactors, yfactors = [element.label], []
else:
factors = [key for key in element.groupby(element.kdims).data.keys()]
if element.ndims > 1:
... |
Limit hover tool to annular wedges only. | def _postprocess_hover(self, renderer, source):
"""
Limit hover tool to annular wedges only.
"""
if isinstance(renderer.glyph, AnnularWedge):
super(RadialHeatMapPlot, self)._postprocess_hover(renderer, source) |
Map elements from given `order` array to bins of start and end values
for radius or angle dimension. | def _get_bins(self, kind, order, reverse=False):
"""
Map elements from given `order` array to bins of start and end values
for radius or angle dimension.
"""
if kind == "radius":
start = self.max_radius * self.radius_inner
end = self.max_radius
e... |
Extract first and second value from tuples of mapped bins. | def _get_bounds(mapper, values):
"""
Extract first and second value from tuples of mapped bins.
"""
array = np.array([mapper.get(x) for x in values])
return array[:, 0], array[:, 1] |
Supply custom, static extents because radial heatmaps always have
the same boundaries. | def get_extents(self, view, ranges, range_type='combined'):
"""Supply custom, static extents because radial heatmaps always have
the same boundaries.
"""
if range_type not in ('data', 'combined'):
return (None,)*4
lower = -self.radius_outer
upper = 2 * self.ma... |
Create dictionary containing default ColumnDataSource glyph to data
mappings. | def get_default_mapping(self, z, cmapper):
"""Create dictionary containing default ColumnDataSource glyph to data
mappings.
"""
map_annular = dict(x=self.max_radius, y=self.max_radius,
inner_radius="inner_radius",
outer_radius="oute... |
Helper function to convert values to corresponding dimension type. | def _pprint(self, element, dim_label, vals):
"""Helper function to convert values to corresponding dimension type.
"""
if vals.dtype.kind not in 'SU':
dim = element.gridded.get_dimension(dim_label)
return [dim.pprint_value(v) for v in vals]
return vals |
Helper function to compute tick mappings based on `ticks` and
default orders and bins. | def _compute_tick_mapping(self, kind, order, bins):
"""Helper function to compute tick mappings based on `ticks` and
default orders and bins.
"""
if kind == "angle":
ticks = self.xticks
reverse = True
elif kind == "radius":
ticks = self.ytick... |
Generate ColumnDataSource dictionary for segment labels. | def _get_seg_labels_data(self, order_seg, bins_seg):
"""Generate ColumnDataSource dictionary for segment labels.
"""
if self.xticks is None:
return dict(x=[], y=[], text=[], angle=[])
mapping = self._compute_tick_mapping("angle", order_seg, bins_seg)
values = [(te... |
Generate ColumnDataSource dictionary for annular labels. | def _get_ann_labels_data(self, order_ann, bins_ann):
"""Generate ColumnDataSource dictionary for annular labels.
"""
if self.yticks is None:
return dict(x=[], y=[], text=[], angle=[])
mapping = self._compute_tick_mapping("radius", order_ann, bins_ann)
values = [(la... |
Helper function to get marker positions depending on mark type. | def _get_markers(marks, order, bins):
"""Helper function to get marker positions depending on mark type.
"""
if callable(marks):
markers = [x for x in order if marks(x)]
elif isinstance(marks, list):
markers = [order[x] for x in marks]
elif isinstance(ma... |
Generate ColumnDataSource dictionary for segment separation lines. | def _get_xmarks_data(self, order_seg, bins_seg):
"""Generate ColumnDataSource dictionary for segment separation lines.
"""
if not self.xmarks:
return dict(xs=[], ys=[])
angles = self._get_markers(self.xmarks, order_seg, bins_seg)
inner = self.max_radius * self.rad... |
Generate ColumnDataSource dictionary for segment separation lines. | def _get_ymarks_data(self, order_ann, bins_ann):
"""Generate ColumnDataSource dictionary for segment separation lines.
"""
if not self.ymarks:
return dict(radius=[])
radius = self._get_markers(self.ymarks, order_ann, bins_ann)
return dict(radius=radius) |
Merge a collection of AttrTree objects. | def merge(cls, trees):
"""
Merge a collection of AttrTree objects.
"""
first = trees[0]
for tree in trees:
first.update(tree)
return first |
Returns the path up to the root for the current node. | def path(self):
"Returns the path up to the root for the current node."
if self.parent:
return '.'.join([self.parent.path, str(self.identifier)])
else:
return self.identifier if self.identifier else self.__class__.__name__ |
Updated the contents of the current AttrTree with the
contents of a second AttrTree. | def update(self, other):
"""
Updated the contents of the current AttrTree with the
contents of a second AttrTree.
"""
if not isinstance(other, AttrTree):
raise Exception('Can only update with another AttrTree type.')
fixed_status = (self.fixed, other.fixed)
... |
Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format. | def set_path(self, path, val):
"""
Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format.
"""
path = tuple(path.split('.')) if isinstance(path , str) else tuple(path)
disallowed = [p for p in path if not type(self)._... |
Filters the loaded AttrTree using the supplied path_filters. | def filter(self, path_filters):
"""
Filters the loaded AttrTree using the supplied path_filters.
"""
if not path_filters: return self
# Convert string path filters
path_filters = [tuple(pf.split('.')) if not isinstance(pf, tuple)
else pf for pf in... |
Propagate the value up to the root node. | def _propagate(self, path, val):
"""
Propagate the value up to the root node.
"""
if val == '_DELETE':
if path in self.data:
del self.data[path]
else:
items = [(key, v) for key, v in self.data.items()
if not... |
Get a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The indexed node of the AttrTree | def get(self, identifier, default=None):
"""Get a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The indexed node of the AttrTree
"""
split... |
Pop a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The node that was removed from the AttrTree | def pop(self, identifier, default=None):
"""Pop a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The node that was removed from the AttrTree
"""
... |
Filter event values that do not originate from the plotting
handles associated with a particular stream using their
ids to match them. | def _filter_msg(self, msg, ids):
"""
Filter event values that do not originate from the plotting
handles associated with a particular stream using their
ids to match them.
"""
filtered_msg = {}
for k, v in msg.items():
if isinstance(v, dict) and 'id' i... |
Find all requested plotting handles and cache them along
with the IDs of the models the callbacks will be attached to. | def _init_plot_handles(self):
"""
Find all requested plotting handles and cache them along
with the IDs of the models the callbacks will be attached to.
"""
plots = [self.plot]
if self.plot.subplots:
plots += list(self.plot.subplots.values())
handles ... |
Gather the ids of the plotting handles attached to this callback
This allows checking that a stream is not given the state
of a plotting handle it wasn't attached to | def _get_stream_handle_ids(self, handles):
"""
Gather the ids of the plotting handles attached to this callback
This allows checking that a stream is not given the state
of a plotting handle it wasn't attached to
"""
stream_handle_ids = defaultdict(dict)
for strea... |
Generates JS code to look up attributes on JS objects from
an attributes specification dictionary. If the specification
references a plotting particular plotting handle it will also
generate JS code to get the ID of the object.
Simple example (when referencing cb_data or cb_obj):
... | def attributes_js(cls, attributes):
"""
Generates JS code to look up attributes on JS objects from
an attributes specification dictionary. If the specification
references a plotting particular plotting handle it will also
generate JS code to get the ID of the object.
Sim... |
Creates a CustomJS callback that will send the requested
attributes back to python. | def get_customjs(self, references, plot_id=None):
"""
Creates a CustomJS callback that will send the requested
attributes back to python.
"""
# Generate callback JS code to get all the requested data
if plot_id is None:
plot_id = self.plot.id or 'PLACEHOLDER_P... |
Generates a CustomJS callback by generating the required JS
code and gathering all plotting handles and installs it on
the requested callback handle. | def set_customjs_callback(self, js_callback, handle):
"""
Generates a CustomJS callback by generating the required JS
code and gathering all plotting handles and installs it on
the requested callback handle.
"""
if self.on_events:
for event in self.on_events:
... |
Resolves a Callback attribute specification looking the
corresponding attribute up on the cb_obj, which should be a
bokeh model. If not model is supplied cb_obj is assumed to
be the same as the model. | def resolve_attr_spec(cls, spec, cb_obj, model=None):
"""
Resolves a Callback attribute specification looking the
corresponding attribute up on the cb_obj, which should be a
bokeh model. If not model is supplied cb_obj is assumed to
be the same as the model.
"""
i... |
Process change events adding timeout to process multiple concerted
value change at once rather than firing off multiple plot updates. | def on_change(self, attr, old, new):
"""
Process change events adding timeout to process multiple concerted
value change at once rather than firing off multiple plot updates.
"""
self._queue.append((attr, old, new))
if not self._active and self.plot.document:
... |
Process bokeh UIEvents adding timeout to process multiple concerted
value change at once rather than firing off multiple plot updates. | def on_event(self, event):
"""
Process bokeh UIEvents adding timeout to process multiple concerted
value change at once rather than firing off multiple plot updates.
"""
self._queue.append((event))
if not self._active and self.plot.document:
self.plot.document... |
Trigger callback change event and triggering corresponding streams. | def process_on_event(self):
"""
Trigger callback change event and triggering corresponding streams.
"""
if not self._queue:
self._active = False
return
# Get unique event types in the queue
events = list(OrderedDict([(event.event_name, event)
... |
Set up on_change events for bokeh server interactions. | def set_server_callback(self, handle):
"""
Set up on_change events for bokeh server interactions.
"""
if self.on_events:
for event in self.on_events:
handle.on_event(event, self.on_event)
if self.on_changes:
for change in self.on_changes:
... |
Clips out of bounds values | def _process_out_of_bounds(self, value, start, end):
"Clips out of bounds values"
if isinstance(value, np.datetime64):
v = dt64_to_dt(value)
if isinstance(start, (int, float)):
start = convert_timestamp(start)
if isinstance(end, (int, float)):
... |
Traverses the supplied plot and searches for any Links on
the plotted objects. | def find_links(cls, root_plot):
"""
Traverses the supplied plot and searches for any Links on
the plotted objects.
"""
plot_fn = lambda x: isinstance(x, GenericElementPlot) and not isinstance(x, GenericOverlayPlot)
plots = root_plot.traverse(lambda x: x, [plot_fn])
... |
Searches a GenericElementPlot for a Link. | def find_link(cls, plot, link=None):
"""
Searches a GenericElementPlot for a Link.
"""
registry = Link.registry.items()
for source in plot.link_sources:
if link is None:
links = [
l for src, links in registry for l in links
... |
Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten array
Returns:
NumPy array of values along the requested di... | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten arra... |
Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Additional arguments to pass to constructor
... | def clone(self, data=None, shared_data=True, new_type=None, *args, **overrides):
"""Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Typ... |
Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten array
Returns:
NumPy array of values along the requested di... | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten arra... |
Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten array
Returns:
NumPy array of values along the requested di... | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten arra... |
Get the formatted cell value for the given row and column indices. | def pprint_cell(self, row, col):
"""
Get the formatted cell value for the given row and column indices.
"""
if col > 2:
raise Exception("Only two columns available in a ItemTable.")
elif row >= self.rows:
raise Exception("Maximum row index is %d" % self.ro... |
Deprecated method to access the ItemTable value dimension values. | def values(self):
"""
Deprecated method to access the ItemTable value dimension values.
"""
self.param.warning('ItemTable values method is deprecated.')
return tuple(self.data.get(d.name, np.NaN)
for d in self.vdims) |
Hook to process the object currently being displayed. | def process_object(obj):
"Hook to process the object currently being displayed."
invalid_options = OptsMagic.process_element(obj)
if invalid_options: return invalid_options
OutputMagic.info(obj) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.