INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
calculate usage for all EBS limits and update Limits | def _find_usage_ebs(self):
"""calculate usage for all EBS limits and update Limits"""
vols = 0
piops = 0
piops_gb = 0
gp_gb = 0
mag_gb = 0
st_gb = 0
sc_gb = 0
logger.debug("Getting usage for EBS volumes")
results = paginate_dict(
... |
find snapshot usage | def _find_usage_snapshots(self):
"""find snapshot usage"""
logger.debug("Getting usage for EBS snapshots")
snaps = paginate_dict(
self.conn.describe_snapshots,
OwnerIds=['self'],
alc_marker_path=['NextToken'],
alc_data_path=['Snapshots'],
... |
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
if self.limits != {}:
return self.limits
... |
Return a dict of EBS-related limits only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict | def _get_limits_ebs(self):
"""
Return a dict of EBS-related limits only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
limits = {}
limits['Provisioned IOPS'] = AwsLimit(
'Provisioned IOPS',
... |
Run the actual usage and limit check, with overrides.
see: http://awslimitchecker.readthedocs.org/en/latest/python_usage.html#ci-deployment-checks | def check_limits(self, verbose=False):
"""
Run the actual usage and limit check, with overrides.
see: http://awslimitchecker.readthedocs.org/en/latest/python_usage.html#ci-deployment-checks
"""
# instantiate the class
checker = AwsLimitChecker()
# set your overri... |
Main entry point. | def run(self, error_on_warning=False, verbose=False):
"""
Main entry point.
"""
warnings, criticals = self.check_limits(verbose=verbose)
# output
if len(warnings) > 0:
print("\nWARNING:\n")
for w in warnings:
print(w)
if len... |
Set a new limit ``value`` for the specified limit, overriding
the default. If ``override_ta`` is True, also use this value
instead of any found by Trusted Advisor. This method simply
passes the data through to the
:py:meth:`~awslimitchecker.limit.AwsLimit.set_limit_override`
meth... | def set_limit_override(self, limit_name, value, override_ta=True):
"""
Set a new limit ``value`` for the specified limit, overriding
the default. If ``override_ta`` is True, also use this value
instead of any found by Trusted Advisor. This method simply
passes the data through to... |
Set the value for the limit as reported by Trusted Advisor,
for the specified limit.
This method should only be called by :py:class:`~.TrustedAdvisor`.
:param limit_name: the name of the limit to override the value for
:type limit_name: str
:param value: the Trusted Advisor lim... | def _set_ta_limit(self, limit_name, value):
"""
Set the value for the limit as reported by Trusted Advisor,
for the specified limit.
This method should only be called by :py:class:`~.TrustedAdvisor`.
:param limit_name: the name of the limit to override the value for
:ty... |
Override the default warning and critical thresholds used to evaluate
the specified limit's usage. Theresholds can be specified as a
percentage of the limit, or as a usage count, or both.
:param warn_percent: new warning threshold, percentage used
:type warn_percent: int
:param ... | def set_threshold_override(self, limit_name, warn_percent=None,
warn_count=None, crit_percent=None,
crit_count=None):
"""
Override the default warning and critical thresholds used to evaluate
the specified limit's usage. Theresholds c... |
Checks current usage against configured thresholds for all limits
for this service.
:returns: a dict of limit name to :py:class:`~.AwsLimit` instance
for all limits that crossed one or more of their thresholds.
:rtype: :py:obj:`dict` of :py:class:`~.AwsLimit` | def check_thresholds(self):
"""
Checks current usage against configured thresholds for all limits
for this service.
:returns: a dict of limit name to :py:class:`~.AwsLimit` instance
for all limits that crossed one or more of their thresholds.
:rtype: :py:obj:`dict` of ... |
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... |
Generate a node that references a label | def label_ref_node(docname, ref_to, title):
"""Generate a node that references a label"""
txt = Text(title, rawsource=title)
newchild = inline(
':ref:`%s`' % ref_to,
'',
txt,
classes=['xref', 'std', 'std-ref']
)
newnode = pending_xref(
':ref:`%s`' % ref_to,
... |
When the doctree has been read in, and ``include`` directives have been
executed and replaced with the included file, walk the tree via
LinkToRefVisitor. | def on_doctree_read(_, doctree):
"""
When the doctree has been read in, and ``include`` directives have been
executed and replaced with the included file, walk the tree via
LinkToRefVisitor.
"""
docname = os.path.splitext(
os.path.basename(doctree.attributes['source']))[0]
if docname... |
When we find a target node, first make sure it matches the last
reference node we saw. Assuming it does, see if its refuri (link URI)
is in our replacement list. If so, replace the link with an internal
reference. | def visit_target(self, node):
"""
When we find a target node, first make sure it matches the last
reference node we saw. Assuming it does, see if its refuri (link URI)
is in our replacement list. If so, replace the link with an internal
reference.
"""
if self.last... |
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
self.conn... |
calculate On-Demand instance usage for all types and update Limits | def _find_usage_instances(self):
"""calculate On-Demand instance usage for all types and update Limits"""
# update our limits with usage
inst_usage = self._instance_usage()
res_usage = self._get_reserved_instance_count()
logger.debug('Reserved instance count: %s', res_usage)
... |
calculate spot instance request usage and update Limits | def _find_usage_spot_instances(self):
"""calculate spot instance request usage and update Limits"""
logger.debug('Getting spot instance request usage')
try:
res = self.conn.describe_spot_instance_requests()
except botocore.exceptions.ClientError as e:
if e.respons... |
calculate spot fleet request usage and update Limits | def _find_usage_spot_fleets(self):
"""calculate spot fleet request usage and update Limits"""
logger.debug('Getting spot fleet request usage')
try:
res = self.conn.describe_spot_fleet_requests()
except botocore.exceptions.ClientError as e:
if e.response['Error']['... |
For each availability zone, get the count of current instance
reservations of each instance type. Return as a nested
dict of AZ name to dict of instance type to reservation count.
:rtype: dict | def _get_reserved_instance_count(self):
"""
For each availability zone, get the count of current instance
reservations of each instance type. Return as a nested
dict of AZ name to dict of instance type to reservation count.
:rtype: dict
"""
reservations = default... |
Find counts of currently-running EC2 Instances
(On-Demand or Reserved) by placement (Availability
Zone) and instance type (size). Return as a nested dict
of AZ name to dict of instance type to count.
:rtype: dict | def _instance_usage(self):
"""
Find counts of currently-running EC2 Instances
(On-Demand or Reserved) by placement (Availability
Zone) and instance type (size). Return as a nested dict
of AZ name to dict of instance type to count.
:rtype: dict
"""
# On-De... |
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
if self.limits != {}:
return self.limits
... |
Query EC2's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``. | def _update_limits_from_api(self):
"""
Query EC2's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
"""
self.connect()
self.connect_resource()
logger.info("Querying EC2 DescribeAccountAttributes for limits"... |
Return a dict of limits for EC2 instances only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict | def _get_limits_instances(self):
"""
Return a dict of limits for EC2 instances only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
# from: http://aws.amazon.com/ec2/faqs/
# (On-Demand, Reserved, Spot)
defau... |
Return a dict of limits for spot requests only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict | def _get_limits_spot(self):
"""
Return a dict of limits for spot requests only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
limits = {}
limits['Max spot instance requests per region'] = AwsLimit(
'Max... |
calculate usage for VPC-related things | def _find_usage_networking_sgs(self):
"""calculate usage for VPC-related things"""
logger.debug("Getting usage for EC2 VPC resources")
sgs_per_vpc = defaultdict(int)
rules_per_sg = defaultdict(int)
for sg in self.resource_conn.security_groups.all():
if sg.vpc_id is no... |
Return a dict of VPC-related limits only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict | def _get_limits_networking(self):
"""
Return a dict of VPC-related limits only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
limits = {}
limits['Security groups per VPC'] = AwsLimit(
'Security groups p... |
Return a list of all known EC2 instance types
:returns: list of all valid known EC2 instance types
:rtype: list | def _instance_types(self):
"""
Return a list of all known EC2 instance types
:returns: list of all valid known EC2 instance types
:rtype: list
"""
GENERAL_TYPES = [
'a1.2xlarge',
'a1.4xlarge',
'a1.large',
'a1.medium',
... |
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... |
find usage for DB Instances and related limits | def _find_usage_instances(self):
"""find usage for DB Instances and related limits"""
paginator = self.conn.get_paginator('describe_db_instances')
for page in paginator.paginate():
for instance in page['DBInstances']:
self.limits['Read replicas per master']._add_curre... |
find usage for subnet groups | def _find_usage_subnet_groups(self):
"""find usage for subnet groups"""
paginator = self.conn.get_paginator('describe_db_subnet_groups')
for page in paginator.paginate():
for group in page['DBSubnetGroups']:
self.limits['Subnets per Subnet Group']._add_current_usage(
... |
find usage for security groups | def _find_usage_security_groups(self):
"""find usage for security groups"""
vpc_count = 0
paginator = self.conn.get_paginator('describe_db_security_groups')
for page in paginator.paginate():
for group in page['DBSecurityGroups']:
if 'VpcId' in group and group... |
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
if self.limits != {}:
return self.limits
... |
Query RDS's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
We ignore the usage information from the API, | def _update_limits_from_api(self):
"""
Query RDS's DescribeAccountAttributes API action, and update limits
with the quotas returned. Updates ``self.limits``.
We ignore the usage information from the API,
"""
self.connect()
logger.info("Querying RDS DescribeAccoun... |
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... |
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict | def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
logger.debug("Gathering %s's limits from AWS", self.se... |
Calculate current usage for CloudTrail related metrics | def _find_usage_cloudtrail(self):
"""Calculate current usage for CloudTrail related metrics"""
trail_list = self.conn.describe_trails()['trailList']
trail_count = len(trail_list) if trail_list else 0
for trail in trail_list:
data_resource_count = 0
if self.conn.... |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
fig = self.generate_plot(self.keys[-1], ranges)
self.drawn = True
return fig |
Returns the dimensions corresponding to each axis.
Should return a list of dimensions or list of lists of
dimensions, which will be formatted to label the axis
and to link axes. | def _get_axis_dims(self, element):
"""Returns the dimensions corresponding to each axis.
Should return a list of dimensions or list of lists of
dimensions, which will be formatted to label the axis
and to link axes.
"""
dims = element.dimensions()[:3]
pad = [None... |
Updates an existing plot with data corresponding
to the key. | def update_frame(self, key, ranges=None, element=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
self.generate_plot(key, ranges, element) |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
return self.generate_plot(list(self.hmap.data.keys())[0], ranges) |
Find the name the user is using to access holoviews. | def get_namespace(self):
"""
Find the name the user is using to access holoviews.
"""
if 'holoviews' not in sys.modules:
raise ImportError('HoloViews does not seem to be imported')
matches = [k for k,v in get_ipython().user_ns.items() # noqa (get_ipython)
i... |
Helper to show the status of the last call to the export method. | def last_export_status(self):
"Helper to show the status of the last call to the export method."
if self.export_success is True:
print("The last call to holoviews.archive.export was successful.")
return
elif self.export_success is None:
print("Status of the la... |
Method to enable or disable automatic capture, allowing you to
simultaneously set the instance parameters. | def auto(self, enabled=True, **kwargs):
"""
Method to enable or disable automatic capture, allowing you to
simultaneously set the instance parameters.
"""
self.namespace = self.get_namespace()
self.notebook_name = "{notebook}"
self._timestamp = tuple(time.localtim... |
Get the current notebook data and export. | def export(self, timestamp=None):
"""
Get the current notebook data and export.
"""
if self._timestamp is None:
raise Exception("No timestamp set. Has the archive been initialized?")
if self.skip_notebook_export:
super(NotebookArchive, self).export(timesta... |
Similar to FileArchive.add but accepts html strings for substitution | def add(self, obj=None, filename=None, data=None, info={}, html=None):
"Similar to FileArchive.add but accepts html strings for substitution"
initial_last_key = list(self._files.keys())[-1] if len(self) else None
if self._auto:
exporters = self.exporters[:]
# Can only ass... |
Computes substitutions before using nbconvert with preprocessors | def _export_with_html(self): # pragma: no cover
"Computes substitutions before using nbconvert with preprocessors"
self.export_success = False
try:
tstamp = time.strftime(self.timestamp_format, self._timestamp)
substitutions = {}
for (basena... |
Load captured notebook node | def _get_notebook_node(self): # pragma: no cover
"Load captured notebook node"
size = len(self._notebook_data)
if size == 0:
raise Exception("Captured buffer size for notebook node is zero.")
node = reader.reads(self._notebook_data)
self.nbversion = ... |
Utility to process style properties converting any
matplotlib specific options to their nearest bokeh
equivalent. | def mpl_to_bokeh(properties):
"""
Utility to process style properties converting any
matplotlib specific options to their nearest bokeh
equivalent.
"""
new_properties = {}
for k, v in properties.items():
if isinstance(v, dict):
new_properties[k] = v
elif k == 's':... |
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
scalar: bool
Returns
-------
valid: boolean or None
If validation is supported returns boolean, othe... | def validate(style, value, scalar=False):
"""
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
scalar: bool
Returns
-------
valid: boolean or None
... |
Ensures RGB(A) tuples in the range 0-1 are scaled to 0-255. | def rgba_tuple(rgba):
"""
Ensures RGB(A) tuples in the range 0-1 are scaled to 0-255.
"""
if isinstance(rgba, tuple):
return tuple(int(c*255) if i<3 else c for i, c in enumerate(rgba))
else:
return COLOR_ALIASES.get(rgba, rgba) |
Computes styles applied to a batched plot by iterating over the
supplied list of style options and expanding any options found in
the supplied style dictionary returning a data and mapping defining
the data that should be added to the ColumnDataSource. | def expand_batched_style(style, opts, mapping, nvals):
"""
Computes styles applied to a batched plot by iterating over the
supplied list of style options and expanding any options found in
the supplied style dictionary returning a data and mapping defining
the data that should be added to the Column... |
Classmethod equivalent to unittest.TestCase method (longMessage = False.) | def simple_equality(cls, first, second, msg=None):
"""
Classmethod equivalent to unittest.TestCase method (longMessage = False.)
"""
if not first==second:
standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
raise cls.failureException(msg or standardMs... |
Classmethod equivalent to unittest.TestCase method | def assertEqual(cls, first, second, msg=None):
"""
Classmethod equivalent to unittest.TestCase method
"""
asserter = None
if type(first) is type(second):
asserter = cls.equality_type_funcs.get(type(first))
try: basestring = basestring # Pytho... |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
properties = dict(properties, **mapping)
if 'xs' in mapping:
renderer = plot.patches(**properties)
else:
renderer ... |
Returns true if the given point is contained within the
bounding box, where all boundaries of the box are
considered to be inclusive. | def contains(self, x, y):
"""
Returns true if the given point is contained within the
bounding box, where all boundaries of the box are
considered to be inclusive.
"""
left, bottom, right, top = self.aarect().lbrt()
return (left <= x <= right) and (bottom <= y <= ... |
Return True if the given point is contained within the
bounding box, where the bottom and right boundaries are
considered exclusive. | def contains_exclusive(self, x, y):
"""
Return True if the given point is contained within the
bounding box, where the bottom and right boundaries are
considered exclusive.
"""
left, bottom, right, top = self._aarect.lbrt()
return (left <= x < right) and (bottom <... |
Returns true if the given BoundingBox x is contained within the
bounding box, where at least one of the boundaries of the box has
to be exclusive. | def containsbb_exclusive(self, x):
"""
Returns true if the given BoundingBox x is contained within the
bounding box, where at least one of the boundaries of the box has
to be exclusive.
"""
left, bottom, right, top = self.aarect().lbrt()
leftx, bottomx, rightx, to... |
Return (left,bottom,right,top) as a tuple. | def lbrt(self):
"""Return (left,bottom,right,top) as a tuple."""
return self._left, self._bottom, self._right, self._top |
Return the centroid of the rectangle. | def centroid(self):
"""
Return the centroid of the rectangle.
"""
left, bottom, right, top = self.lbrt()
return (right + left) / 2.0, (top + bottom) / 2.0 |
Recurses DynamicMap to find DynamicMaps inputs
Args:
dmap: DynamicMap to recurse to look for DynamicMap inputs
Returns:
List of DynamicMap instances that were found | def get_nested_dmaps(dmap):
"""Recurses DynamicMap to find DynamicMaps inputs
Args:
dmap: DynamicMap to recurse to look for DynamicMap inputs
Returns:
List of DynamicMap instances that were found
"""
if not isinstance(dmap, DynamicMap):
return []
dmaps = [dmap]
for ... |
Recurses supplied DynamicMap to find all streams
Args:
dmap: DynamicMap to recurse to look for streams
Returns:
List of streams that were found | def get_nested_streams(dmap):
"""Recurses supplied DynamicMap to find all streams
Args:
dmap: DynamicMap to recurse to look for streams
Returns:
List of streams that were found
"""
return list({s for dmap in get_nested_dmaps(dmap) for s in dmap.streams}) |
Determine whether the Callable should have memoization enabled
based on the supplied streams (typically by a
DynamicMap). Memoization is disabled if any of the streams require
it it and are currently in a triggered state. | def dynamicmap_memoization(callable_obj, streams):
"""
Determine whether the Callable should have memoization enabled
based on the supplied streams (typically by a
DynamicMap). Memoization is disabled if any of the streams require
it it and are currently in a triggered state.
"""
memoization... |
Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
NdOverlay object(s) with supplied dimensions | def overlay(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
N... |
Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
Grid... | def grid(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dim... |
Group by supplied dimension(s) and lay out groups
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension(s) to group by
Returns:
NdLayout with supplied dimensions | def layout(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension(s) to group by
Returns:
NdLayo... |
Applies simplified option definition returning a new object
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects in the HoloMap a simple format may be
used, e.g.:
obj.options(cmap='viridis',... | def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects in the HoloMap a simple format may be
used,... |
Deprecated method to split overlays inside the HoloMap. | def split_overlays(self):
"Deprecated method to split overlays inside the HoloMap."
if util.config.future_deprecations:
self.param.warning("split_overlays is deprecated and is now "
"a private method.")
return self._split_overlays() |
Splits overlays inside the HoloMap into list of HoloMaps | def _split_overlays(self):
"Splits overlays inside the HoloMap into list of HoloMaps"
if not issubclass(self.type, CompositeOverlay):
return None, self.clone()
item_maps = OrderedDict()
for k, overlay in self.data.items():
for key, el in overlay.items():
... |
Helper for __mul__ that returns the list of keys together with
the dimension labels. | def _dimension_keys(self):
"""
Helper for __mul__ that returns the list of keys together with
the dimension labels.
"""
return [tuple(zip([d.name for d in self.kdims], [k] if self.ndims == 1 else k))
for k in self.keys()] |
Implements dynamic version of overlaying operation overlaying
DynamicMaps and HoloMaps where the key dimensions of one is
a strict superset of the other. | def _dynamic_mul(self, dimensions, other, keys):
"""
Implements dynamic version of overlaying operation overlaying
DynamicMaps and HoloMaps where the key dimensions of one is
a strict superset of the other.
"""
# If either is a HoloMap compute Dimension values
if ... |
Collate allows reordering nested containers
Collation allows collapsing nested mapping types by merging
their dimensions. In simple terms in merges nested containers
into a single merged type.
In the simple case a HoloMap containing other HoloMaps can
easily be joined in this w... | def collate(self, merge_type=None, drop=[], drop_constant=False):
"""Collate allows reordering nested containers
Collation allows collapsing nested mapping types by merging
their dimensions. In simple terms in merges nested containers
into a single merged type.
In the simple ca... |
Concatenates and aggregates along supplied dimensions
Useful to collapse stacks of objects into a single object,
e.g. to average a stack of Images or Curves.
Args:
dimensions: Dimension(s) to collapse
Defaults to all key dimensions
function: Aggregation ... | def collapse(self, dimensions=None, function=None, spreadfn=None, **kwargs):
"""Concatenates and aggregates along supplied dimensions
Useful to collapse stacks of objects into a single object,
e.g. to average a stack of Images or Curves.
Args:
dimensions: Dimension(s) to co... |
Samples element values at supplied coordinates.
Allows sampling of element with a list of coordinates matching
the key dimensions, returning a new object containing just the
selected samples. Supports multiple signatures:
Sampling with a list of coordinates, e.g.:
ds.sampl... | def sample(self, samples=[], bounds=None, **sample_values):
"""Samples element values at supplied coordinates.
Allows sampling of element with a list of coordinates matching
the key dimensions, returning a new object containing just the
selected samples. Supports multiple signatures:
... |
Applies reduction to elements along the specified dimension(s).
Allows reducing the values along one or more key dimension
with the supplied function. Supports two signatures:
Reducing with a list of dimensions, e.g.:
ds.reduce(['x'], np.mean)
Defining a reduction using k... | def reduce(self, dimensions=None, function=None, spread_fn=None, **reduce_map):
"""Applies reduction to elements along the specified dimension(s).
Allows reducing the values along one or more key dimension
with the supplied function. Supports two signatures:
Reducing with a list of dim... |
Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to wh... | def relabel(self, label=None, group=None, depth=1):
"""Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to... |
Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimension(s) to compute histogram on
num_bins (int, optional): Number of bins
bin_range (t... | def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, individually=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
... |
Returns True if the callable takes no arguments | def noargs(self):
"Returns True if the callable takes no arguments"
noargs = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
return self.argspec == noargs |
Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object | def clone(self, callable=None, **overrides):
"""Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object
"""
old = {k: v for k, v ... |
Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded. | def unbounded(self):
"""
Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded.
"""
unbounded_dims = []
# Dimensioned streams do not need to be b... |
Construct an initial key for based on the lower range bounds or
values on the key dimensions. | def _initial_key(self):
"""
Construct an initial key for based on the lower range bounds or
values on the key dimensions.
"""
key = []
undefined = []
stream_params = set(util.stream_parameters(self.streams))
for kdim in self.kdims:
if str(kdim)... |
Make sure the supplied key values are within the bounds
specified by the corresponding dimension range and soft_range. | def _validate_key(self, key):
"""
Make sure the supplied key values are within the bounds
specified by the corresponding dimension range and soft_range.
"""
if key == () and len(self.kdims) == 0: return ()
key = util.wrap_tuple(key)
assert len(key) == len(self.kdi... |
Updates attached streams and triggers events
Automatically find streams matching the supplied kwargs to
update and trigger events on them.
Args:
**kwargs: Events to update streams with | def event(self, **kwargs):
"""Updates attached streams and triggers events
Automatically find streams matching the supplied kwargs to
update and trigger events on them.
Args:
**kwargs: Events to update streams with
"""
if self.callback.noargs and self.stream... |
Applies custom option tree to values return by the callback. | def _style(self, retval):
"Applies custom option tree to values return by the callback."
if self.id not in Store.custom_options():
return retval
spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id])
return retval.opts(spec) |
Executes the callback with the appropriate args and kwargs | def _execute_callback(self, *args):
"Executes the callback with the appropriate args and kwargs"
self._validate_key(args) # Validate input key
# Additional validation needed to ensure kwargs don't clash
kdims = [kdim.name for kdim in self.kdims]
kwarg_items = [s.contents.it... |
Applies simplified option definition returning a new object.
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects returned by the DynamicMap a simple
format may be used, e.g.:
obj.options(cm... | def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object.
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects returned by the DynamicMap a simple
format... |
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
link (bool, optional): Whether clone should be linked
... | def clone(self, data=None, shared_data=True, new_type=None, link=True,
*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
... |
Returns a new DynamicMap if the key (tuple form) expresses a
cross product, otherwise returns None. The cache argument is a
dictionary (key:element pairs) of all the data found in the
cache for this key.
Each key inside the cross product is looked up in the cache
(self.data) to ... | def _cross_product(self, tuple_key, cache, data_slice):
"""
Returns a new DynamicMap if the key (tuple form) expresses a
cross product, otherwise returns None. The cache argument is a
dictionary (key:element pairs) of all the data found in the
cache for this key.
Each ke... |
Slices bounded DynamicMaps by setting the soft_ranges on
key dimensions and applies data slice to cached and dynamic
values. | def _slice_bounded(self, tuple_key, data_slice):
"""
Slices bounded DynamicMaps by setting the soft_ranges on
key dimensions and applies data slice to cached and dynamic
values.
"""
slices = [el for el in tuple_key if isinstance(el, slice)]
if any(el.step for el i... |
Applies selection by dimension name
Applies a selection along the dimensions of the object using
keyword arguments. The selection may be narrowed to certain
objects using selection_specs. For container objects the
selection will be applied to all children as well.
Selections ma... | def select(self, selection_specs=None, **kwargs):
"""Applies selection by dimension name
Applies a selection along the dimensions of the object using
keyword arguments. The selection may be narrowed to certain
objects using selection_specs. For container objects the
selection wi... |
Request that a key/value pair be considered for caching. | def _cache(self, key, val):
"""
Request that a key/value pair be considered for caching.
"""
cache_size = (1 if util.dimensionless_contents(self.streams, self.kdims)
else self.cache_size)
if len(self) >= cache_size:
first_key = next(k for k in se... |
Map a function to all objects matching the specs
Recursively replaces elements using a map function when the
specs apply, by default applies to all objects, e.g. to apply
the function to all contained Curve objects:
dmap.map(fn, hv.Curve)
Args:
map_fn: Function... | def map(self, map_fn, specs=None, clone=True, link_inputs=True):
"""Map a function to all objects matching the specs
Recursively replaces elements using a map function when the
specs apply, by default applies to all objects, e.g. to apply
the function to all contained Curve objects:
... |
Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to wh... | def relabel(self, label=None, group=None, depth=1):
"""Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to... |
Splits a DynamicMap into its components. Only well defined for
DynamicMap with consistent number and order of layers. | def _split_overlays(self):
"""
Splits a DynamicMap into its components. Only well defined for
DynamicMap with consistent number and order of layers.
"""
if not len(self):
raise ValueError('Cannot split DynamicMap before it has been initialized')
elif not issub... |
Unpacks DynamicMap into container of DynamicMaps
Collation allows unpacking DynamicMaps which return Layout,
NdLayout or GridSpace objects into a single such object
containing DynamicMaps. Assumes that the items in the layout
or grid that is returned do not change.
Returns:
... | def collate(self):
"""Unpacks DynamicMap into container of DynamicMaps
Collation allows unpacking DynamicMaps which return Layout,
NdLayout or GridSpace objects into a single such object
containing DynamicMaps. Assumes that the items in the layout
or grid that is returned do not... |
Groups DynamicMap by one or more dimensions
Applies groupby operation over the specified dimensions
returning an object of type container_type (expected to be
dictionary-like) containing the groups.
Args:
dimensions: Dimension(s) to group by
container_type: Type... | def groupby(self, dimensions=None, container_type=None, group_type=None, **kwargs):
"""Groups DynamicMap by one or more dimensions
Applies groupby operation over the specified dimensions
returning an object of type container_type (expected to be
dictionary-like) containing the groups.
... |
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
grid: GridSpace
GridSpace with supplied dimensions | def grid(self, dimensions=None, **kwargs):
"""
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
grid: GridSp... |
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
layout: NdLayout
NdLayout with supplied dimensions | def layout(self, dimensions=None, **kwargs):
"""
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
layout: NdL... |
Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
NdOverlay object(s) with supplied dimensions | def overlay(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
N... |
Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimension(s) to compute histogram on
num_bins (int, optional): Number of bins
bin_range (t... | def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimens... |
Reorders key dimensions on DynamicMap
Create a new object with a reordered set of key dimensions.
Dropping dimensions is not allowed on a DynamicMap.
Args:
kdims: List of dimensions to reindex the mapping with
force: Not applicable to a DynamicMap
Returns:
... | def reindex(self, kdims=[], force=False):
"""Reorders key dimensions on DynamicMap
Create a new object with a reordered set of key dimensions.
Dropping dimensions is not allowed on a DynamicMap.
Args:
kdims: List of dimensions to reindex the mapping with
force: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.