INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Set the value for a Gauge. | def gauge(self, slug, current_value):
"""Set the value for a Gauge.
* ``slug`` -- the unique identifier (or key) for the Gauge
* ``current_value`` -- the value that the gauge should display
"""
k = self._gauge_key(slug)
self.r.sadd(self._gauge_slugs_key, slug) # keep t... |
Removes all gauges with the given slug. | def delete_gauge(self, slug):
"""Removes all gauges with the given ``slug``."""
key = self._gauge_key(slug)
self.r.delete(key) # Remove the Gauge
self.r.srem(self._gauge_slugs_key, slug) |
Renders a template with a menu to view a metric ( or metrics ) for a given number of years. | def metrics_since(slugs, years, link_type="detail", granularity=None):
"""Renders a template with a menu to view a metric (or metrics) for a
given number of years.
* ``slugs`` -- A Slug or a set/list of slugs
* ``years`` -- Number of years to show past metrics
* ``link_type`` -- What type of chart ... |
Include a Donut Chart for the specified Gauge. | def gauge(slug, maximum=9000, size=200, coerce='float'):
"""Include a Donut Chart for the specified Gauge.
* ``slug`` -- the unique slug for the Gauge.
* ``maximum`` -- The maximum value for the gauge (default is 9000)
* ``size`` -- The size (in pixels) of the gauge (default is 200)
* ``coerce`` --... |
Template Tag to display a metric s * current * detail. | def metric_detail(slug, with_data_table=False):
"""Template Tag to display a metric's *current* detail.
* ``slug`` -- the metric's unique slug
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
granularities = list(r._granularities())
metrics = r.get_metric(s... |
Template Tag to display a metric s history. | def metric_history(slug, granularity="daily", since=None, to=None,
with_data_table=False):
"""Template Tag to display a metric's history.
* ``slug`` -- the metric's unique slug
* ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly
* ``since`` -- a datetime obje... |
Template Tag to display multiple metrics. | def aggregate_detail(slug_list, with_data_table=False):
"""Template Tag to display multiple metrics.
* ``slug_list`` -- A list of slugs to display
* ``with_data_table`` -- if True, prints the raw data in a table.
"""
r = get_r()
metrics_data = []
granularities = r._granularities()
# X... |
Template Tag to display history for multiple metrics. | def aggregate_history(slugs, granularity="daily", since=None, with_data_table=False):
"""Template Tag to display history for multiple metrics.
* ``slug_list`` -- A list of slugs to display
* ``granularity`` -- the granularity: seconds, minutes, hourly,
daily, weekly, monthly, yearl... |
Run query on vars and return the result ( s ). | def apply(query, replacements=None, vars=None, allow_io=False,
libs=("stdcore", "stdmath")):
"""Run 'query' on 'vars' and return the result(s).
Arguments:
query: A query object or string with the query.
replacements: Built-time parameters to the query, either as dict or
as... |
Create an EFILTER - callable version of function func. | def user_func(func, arg_types=None, return_type=None):
"""Create an EFILTER-callable version of function 'func'.
As a security precaution, EFILTER will not execute Python callables
unless they implement the IApplicative protocol. There is a perfectly good
implementation of this protocol in the standard... |
Determine the type of the query s output without actually running it. | def infer(query, replacements=None, root_type=None,
libs=("stdcore", "stdmath")):
"""Determine the type of the query's output without actually running it.
Arguments:
query: A query object or string with the query.
replacements: Built-time parameters to the query, either as dict or as
... |
Yield objects from data that match the query. | def search(query, data, replacements=None):
"""Yield objects from 'data' that match the 'query'."""
query = q.Query(query, params=replacements)
for entry in data:
if solve.solve(query, entry).value:
yield entry |
Look ahead doesn t affect current_token and next_token. | def peek(self, steps=1):
"""Look ahead, doesn't affect current_token and next_token."""
try:
tokens = iter(self)
for _ in six.moves.range(steps):
next(tokens)
return next(tokens)
except StopIteration:
return None |
Skip ahead by steps tokens. | def skip(self, steps=1):
"""Skip ahead by 'steps' tokens."""
for _ in six.moves.range(steps):
self.next_token() |
Returns the next logical token advancing the tokenizer. | def next_token(self):
"""Returns the next logical token, advancing the tokenizer."""
if self.lookahead:
self.current_token = self.lookahead.popleft()
return self.current_token
self.current_token = self._parse_next_token()
return self.current_token |
Will parse patterns until it gets to the next token or EOF. | def _parse_next_token(self):
"""Will parse patterns until it gets to the next token or EOF."""
while self._position < self.limit:
token = self._next_pattern()
if token:
return token
return None |
Parses the next pattern by matching each in turn. | def _next_pattern(self):
"""Parses the next pattern by matching each in turn."""
current_state = self.state_stack[-1]
position = self._position
for pattern in self.patterns:
if current_state not in pattern.states:
continue
m = pattern.regex.match(... |
Raise a nice error with the token highlighted. | def _error(self, message, start, end=None):
"""Raise a nice error, with the token highlighted."""
raise errors.EfilterParseError(
source=self.source, start=start, end=end, message=message) |
Emits a token using the current pattern match and pattern label. | def emit(self, string, match, pattern, **_):
"""Emits a token using the current pattern match and pattern label."""
return grammar.Token(name=pattern.name, value=string,
start=match.start(), end=match.end()) |
Get version string by parsing PKG - INFO. | def get_pkg_version():
"""Get version string by parsing PKG-INFO."""
try:
with open("PKG-INFO", "r") as fp:
rgx = re.compile(r"Version: (\d+)")
for line in fp.readlines():
match = rgx.match(line)
if match:
return match.group(1)
... |
Generates a version string. | def get_version(dev_version=False):
"""Generates a version string.
Arguments:
dev_version: Generate a verbose development version from git commits.
Examples:
1.1
1.1.dev43 # If 'dev_version' was passed.
"""
if dev_version:
version = git_dev_version()
if not ... |
** Purpose **: Method to be executed in the heartbeat thread. This method sends a request to the heartbeat - req queue. It expects a response message from the heartbeart - res queue within 10 seconds. This message should contain the same correlation id. If no message if received in 10 seconds the tmgr is assumed dead. ... | def _heartbeat(self):
"""
**Purpose**: Method to be executed in the heartbeat thread. This method sends a 'request' to the
heartbeat-req queue. It expects a 'response' message from the 'heartbeart-res' queue within 10 seconds. This
message should contain the same correlation id. If no me... |
** Purpose **: Method to be run by the tmgr process. This method receives a Task from the pending_queue and submits it to the RTS. At all state transititons they are synced ( blocking ) with the AppManager in the master process. | def _tmgr(self, uid, rmgr, logger, mq_hostname, port, pending_queue, completed_queue):
"""
**Purpose**: Method to be run by the tmgr process. This method receives a Task from the pending_queue
and submits it to the RTS. At all state transititons, they are synced (blocking) with the AppManager
... |
** Purpose **: Method to start the heartbeat thread. The heartbeat function is not to be accessed directly. The function is started in a separate thread using this method. | def start_heartbeat(self):
"""
**Purpose**: Method to start the heartbeat thread. The heartbeat function
is not to be accessed directly. The function is started in a separate
thread using this method.
"""
if not self._hb_thread:
try:
self._l... |
** Purpose **: Method to terminate the heartbeat thread. This method is blocking as it waits for the heartbeat thread to terminate ( aka join ). | def terminate_heartbeat(self):
"""
**Purpose**: Method to terminate the heartbeat thread. This method is
blocking as it waits for the heartbeat thread to terminate (aka join).
This is the last method that is executed from the TaskManager and
hence closes the profiler.
"... |
** Purpose **: Method to terminate the tmgr process. This method is blocking as it waits for the tmgr process to terminate ( aka join ). | def terminate_manager(self):
"""
**Purpose**: Method to terminate the tmgr process. This method is
blocking as it waits for the tmgr process to terminate (aka join).
"""
try:
if self._tmgr_process:
if not self._tmgr_terminate.is_set():
... |
Yields all the values from generator_func and type - checks. | def getvalues(self):
"""Yields all the values from 'generator_func' and type-checks.
Yields:
Whatever 'generator_func' yields.
Raises:
TypeError: if subsequent values are of a different type than first
value.
ValueError: if subsequent iterat... |
Sorted comparison of values. | def value_eq(self, other):
"""Sorted comparison of values."""
self_sorted = ordered.ordered(self.getvalues())
other_sorted = ordered.ordered(repeated.getvalues(other))
return self_sorted == other_sorted |
Print a detailed audit of all calls to this function. | def call_audit(func):
"""Print a detailed audit of all calls to this function."""
def audited_func(*args, **kwargs):
import traceback
stack = traceback.extract_stack()
r = func(*args, **kwargs)
func_name = func.__name__
print("@depth %d, trace %s -> %s(*%r, **%r) => %r" ... |
See class_multimethod. | def _class_dispatch(args, kwargs):
"""See 'class_multimethod'."""
_ = kwargs
if not args:
raise ValueError(
"Multimethods must be passed at least one positional arg.")
if not isinstance(args[0], type):
raise TypeError(
"class_multimethod must be called with a typ... |
Prefer one type over another type all else being equivalent. | def prefer_type(self, prefer, over):
"""Prefer one type over another type, all else being equivalent.
With abstract base classes (Python's abc module) it is possible for
a type to appear to be a subclass of another type without the supertype
appearing in the subtype's MRO. As such, the ... |
Finds the best implementation of this function given a type. | def _find_and_cache_best_function(self, dispatch_type):
"""Finds the best implementation of this function given a type.
This function caches the result, and uses locking for thread safety.
Returns:
Implementing function, in below order of preference:
1. Explicitly regis... |
Parse the arguments and return a tuple of types to implement for. | def __get_types(for_type=None, for_types=None):
"""Parse the arguments and return a tuple of types to implement for.
Raises:
ValueError or TypeError as appropriate.
"""
if for_type:
if for_types:
raise ValueError("Cannot pass both for_type and for... |
Return a decorator that will register the implementation. | def implementation(self, for_type=None, for_types=None):
"""Return a decorator that will register the implementation.
Example:
@multimethod
def add(x, y):
pass
@add.implementation(for_type=int)
def add(x, y):
return x + y
... |
Registers an implementing function for for_type. | def implement(self, implementation, for_type=None, for_types=None):
"""Registers an implementing function for for_type.
Arguments:
implementation: Callable implementation for this type.
for_type: The type this implementation applies to.
for_types: Same as for_type, b... |
Converts the given list of vlues into a list of integers. If the integer conversion fails ( e. g. non - numeric strings or None - values ) this filter will include a 0 instead. | def to_int_list(values):
"""Converts the given list of vlues into a list of integers. If the
integer conversion fails (e.g. non-numeric strings or None-values), this
filter will include a 0 instead."""
results = []
for v in values:
try:
results.append(int(v))
except (Type... |
** Purpose **: Validate the resource description provided to the ResourceManager | def _validate_resource_desc(self):
"""
**Purpose**: Validate the resource description provided to the ResourceManager
"""
self._prof.prof('validating rdesc', uid=self._uid)
self._logger.debug('Validating resource description')
expected_keys = ['resource',
... |
** Purpose **: Populate the ResourceManager class with the validated resource description | def _populate(self):
"""
**Purpose**: Populate the ResourceManager class with the validated
resource description
"""
if self._validated:
self._prof.prof('populating rmgr', uid=self._uid)
self._logger.debug('Populating resource manager ... |
Includes the Gauge slugs and data in the context. | def get_context_data(self, **kwargs):
"""Includes the Gauge slugs and data in the context."""
data = super(GaugesView, self).get_context_data(**kwargs)
data.update({'gauges': get_r().gauge_slugs()})
return data |
Includes the metrics slugs in the context. | def get_context_data(self, **kwargs):
"""Includes the metrics slugs in the context."""
data = super(MetricsListView, self).get_context_data(**kwargs)
# Metrics organized by category, like so:
# { <category_name>: [ <slug1>, <slug2>, ... ]}
data.update({'metrics': get_r().metric_... |
Includes the metrics slugs in the context. | def get_context_data(self, **kwargs):
"""Includes the metrics slugs in the context."""
data = super(MetricDetailView, self).get_context_data(**kwargs)
data['slug'] = kwargs['slug']
data['granularities'] = list(get_r()._granularities())
return data |
Includes the metrics slugs in the context. | def get_context_data(self, **kwargs):
"""Includes the metrics slugs in the context."""
data = super(MetricHistoryView, self).get_context_data(**kwargs)
# Accept GET query params for ``since``
since = self.request.GET.get('since', None)
if since and len(since) == 10: # yyyy-mm-d... |
Reverses the redis_metric_aggregate_detail URL using self. metric_slugs as an argument. | def get_success_url(self):
"""Reverses the ``redis_metric_aggregate_detail`` URL using
``self.metric_slugs`` as an argument."""
slugs = '+'.join(self.metric_slugs)
url = reverse('redis_metric_aggregate_detail', args=[slugs])
# Django 1.6 quotes reversed URLs, which changes + into... |
Pull the metrics from the submitted form and store them as a list of strings in self. metric_slugs. | def form_valid(self, form):
"""Pull the metrics from the submitted form, and store them as a
list of strings in ``self.metric_slugs``.
"""
self.metric_slugs = [k.strip() for k in form.cleaned_data['metrics']]
return super(AggregateFormView, self).form_valid(form) |
Includes the metrics slugs in the context. | def get_context_data(self, **kwargs):
"""Includes the metrics slugs in the context."""
r = get_r()
category = kwargs.pop('category', None)
data = super(AggregateDetailView, self).get_context_data(**kwargs)
if category:
slug_set = r._category_slugs(category)
... |
Includes the metrics slugs in the context. | def get_context_data(self, **kwargs):
"""Includes the metrics slugs in the context."""
r = get_r()
data = super(AggregateHistoryView, self).get_context_data(**kwargs)
slug_set = set(kwargs['slugs'].split('+'))
granularity = kwargs.get('granularity', 'daily')
# Accept GET... |
See if this view was called with a specified category. | def get(self, *args, **kwargs):
"""See if this view was called with a specified category."""
self.initial = {"category_name": kwargs.get('category_name', None)}
return super(CategoryFormView, self).get(*args, **kwargs) |
Get the category name/ metric slugs from the form and update the category so contains the given metrics. | def form_valid(self, form):
"""Get the category name/metric slugs from the form, and update the
category so contains the given metrics."""
form.categorize_metrics()
return super(CategoryFormView, self).form_valid(form) |
Rerun sets the state of the Pipeline to scheduling so that the Pipeline can be checked for new stages | def rerun(self):
"""
Rerun sets the state of the Pipeline to scheduling so that the Pipeline
can be checked for new stages
"""
self._state = states.SCHEDULING
self._completed_flag = threading.Event()
print 'Pipeline %s in %s state'%(self._uid, self._state) |
Convert current Pipeline ( i. e. its attributes ) into a dictionary | def to_dict(self):
"""
Convert current Pipeline (i.e. its attributes) into a dictionary
:return: python dictionary
"""
pipeline_desc_as_dict = {
'uid': self._uid,
'name': self._name,
'state': self._state,
'state_history': self._s... |
Create a Pipeline from a dictionary. The change is in inplace. | def from_dict(self, d):
"""
Create a Pipeline from a dictionary. The change is in inplace.
:argument: python dictionary
:return: None
"""
if 'uid' in d:
if d['uid']:
self._uid = d['uid']
if 'name' in d:
if d['name']:
... |
Purpose: Increment stage pointer. Also check if Pipeline has completed. | def _increment_stage(self):
"""
Purpose: Increment stage pointer. Also check if Pipeline has completed.
"""
try:
if self._cur_stage < self._stage_count:
self._cur_stage += 1
else:
self._completed_flag.set()
except Excepti... |
Purpose: Decrement stage pointer. Reset completed flag. | def _decrement_stage(self):
"""
Purpose: Decrement stage pointer. Reset completed flag.
"""
try:
if self._cur_stage > 0:
self._cur_stage -= 1
self._completed_flag = threading.Event() # reset
except Exception, ex:
raise E... |
Purpose: Validate whether the argument stages is of list of Stage objects | def _validate_entities(self, stages):
"""
Purpose: Validate whether the argument 'stages' is of list of Stage objects
:argument: list of Stage objects
"""
if not stages:
raise TypeError(expected_type=Stage, actual_type=type(stages))
if not isinstance(stages,... |
Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of current object | def _assign_uid(self, sid):
"""
Purpose: Assign a uid to the current object based on the sid passed. Pass the current uid to children of
current object
"""
self._uid = ru.generate_id(
'pipeline.%(item_counter)04d', ru.ID_CUSTOM, namespace=sid)
for stage in sel... |
Purpose: Pass current Pipeline s uid to all Stages. | def _pass_uid(self):
"""
Purpose: Pass current Pipeline's uid to all Stages.
:argument: List of Stage objects (optional)
"""
for stage in self._stages:
stage.parent_pipeline['uid'] = self._uid
stage.parent_pipeline['name'] = self._name
stage.... |
Hexdump function by sbz and 7h3rAm on Github: ( https:// gist. github. com/ 7h3rAm/ 5603718 ).: param src: Source the string to be shown in hexadecimal format: param length: Number of hex characters to print in one row: param sep: Unprintable characters representation: return: | def hexdump(src, length=16, sep='.'):
"""
Hexdump function by sbz and 7h3rAm on Github:
(https://gist.github.com/7h3rAm/5603718).
:param src: Source, the string to be shown in hexadecimal format
:param length: Number of hex characters to print in one row
:param sep: Unprintable characters repres... |
Extracts YANG model from an IETF RFC or draft text file. This is the main ( external ) API entry for the module. | def xym(source_id, srcdir, dstdir, strict=False, strict_examples=False, debug_level=0, add_line_refs=False,
force_revision_pyang=False, force_revision_regexp=False):
"""
Extracts YANG model from an IETF RFC or draft text file.
This is the main (external) API entry for the module.
:param add_lin... |
Prints out a warning message to stderr.: param s: The warning string to print: return: None | def warning(self, s):
"""
Prints out a warning message to stderr.
:param s: The warning string to print
:return: None
"""
print(" WARNING: '%s', %s" % (self.src_id, s), file=sys.stderr) |
Prints out an error message to stderr.: param s: The error string to print: return: None | def error(self, s):
"""
Prints out an error message to stderr.
:param s: The error string to print
:return: None
"""
print(" ERROR: '%s', %s" % (self.src_id, s), file=sys.stderr) |
This function is a part of the model post - processing pipeline. It removes leading spaces from an extracted module ; depending on the formatting of the draft/ rfc text may have multiple spaces prepended to each line. The function also determines the length of the longest line in the module - this value can be used by ... | def remove_leading_spaces(self, input_model):
"""
This function is a part of the model post-processing pipeline. It
removes leading spaces from an extracted module; depending on the
formatting of the draft/rfc text, may have multiple spaces prepended
to each line. The function a... |
This function is a part of the model post - processing pipeline. For each line in the module it adds a reference to the line number in the original draft/ RFC from where the module line was extracted.: param input_model: The YANG model to be processed: return: Modified YANG model where line numbers from the RFC/ Draft ... | def add_line_references(self, input_model):
"""
This function is a part of the model post-processing pipeline. For
each line in the module, it adds a reference to the line number in
the original draft/RFC from where the module line was extracted.
:param input_model: The YANG mode... |
Removes superfluous newlines from a YANG model that was extracted from a draft or RFC text. Newlines are removed whenever 2 or more consecutive empty lines are found in the model. This function is a part of the model post - processing pipeline.: param input_model: The YANG model to be processed: return: YANG model with... | def remove_extra_empty_lines(self, input_model):
"""
Removes superfluous newlines from a YANG model that was extracted
from a draft or RFC text. Newlines are removed whenever 2 or more
consecutive empty lines are found in the model. This function is a
part of the model post-proce... |
This function defines the order and execution logic for actions that are performed in the model post - processing pipeline.: param input_model: The YANG model to be processed in the pipeline: param add_line_refs: Flag that controls whether line number references should be added to the model.: return: List of strings th... | def post_process_model(self, input_model, add_line_refs):
"""
This function defines the order and execution logic for actions
that are performed in the model post-processing pipeline.
:param input_model: The YANG model to be processed in the pipeline
:param add_line_refs: Flag th... |
Write a YANG model that was extracted from a source identifier ( URL or source. txt file ) to a. yang destination file: param mdl: YANG model as a list of lines: param fn: Name of the YANG model file: return: | def write_model_to_file(self, mdl, fn):
"""
Write a YANG model that was extracted from a source identifier
(URL or source .txt file) to a .yang destination file
:param mdl: YANG model, as a list of lines
:param fn: Name of the YANG model file
:return:
"""
... |
Debug print of the currently parsed line: param i: The line number of the line that is being currently parsed: param level: Parser level: param line: the line that is currently being parsed: return: None | def debug_print_line(self, i, level, line):
"""
Debug print of the currently parsed line
:param i: The line number of the line that is being currently parsed
:param level: Parser level
:param line: the line that is currently being parsed
:return: None
"""
... |
Debug print indicating that an empty line is being skipped: param i: The line number of the line that is being currently parsed: param line: the parsed line: return: None | def debug_print_strip_msg(self, i, line):
"""
Debug print indicating that an empty line is being skipped
:param i: The line number of the line that is being currently parsed
:param line: the parsed line
:return: None
"""
if self.debug_level == 2:
print... |
Skip over empty lines: param content: parsed text: param i: current parsed line: return: number of skipped lined | def strip_empty_lines_forward(self, content, i):
"""
Skip over empty lines
:param content: parsed text
:param i: current parsed line
:return: number of skipped lined
"""
while i < len(content):
line = content[i].strip(' \r\n\t\f')
if line !... |
Strips empty lines preceding the line that is currently being parsed. This fucntion is called when the parser encounters a Footer.: param model: lines that were added to the model up to this point: param line_num: the number of teh line being parsed: param max_lines_to_strip: max number of lines to strip from the model... | def strip_empty_lines_backward(self, model, max_lines_to_strip):
"""
Strips empty lines preceding the line that is currently being parsed. This
fucntion is called when the parser encounters a Footer.
:param model: lines that were added to the model up to this point
:param line_nu... |
Extracts one or more YANG models from an RFC or draft text string in which the models are specified. The function skips over page formatting ( Page Headers and Footers ) and performs basic YANG module syntax checking. In strict mode the function also enforces the <CODE BEGINS >/ <CODE ENDS > tags - a model is not extra... | def extract_yang_model(self, content):
"""
Extracts one or more YANG models from an RFC or draft text string in
which the models are specified. The function skips over page
formatting (Page Headers and Footers) and performs basic YANG module
syntax checking. In strict mode, the f... |
Decorator for retrying method calls based on instance parameters. | def auto_retry(fun):
"""Decorator for retrying method calls, based on instance parameters."""
@functools.wraps(fun)
def decorated(instance, *args, **kwargs):
"""Wrapper around a decorated function."""
cfg = instance._retry_config
remaining_tries = cfg.retry_attempts
current_... |
Extracts used strings from a % ( foo ) s pattern. | def extract_pattern(fmt):
"""Extracts used strings from a %(foo)s pattern."""
class FakeDict(object):
def __init__(self):
self.seen_keys = set()
def __getitem__(self, key):
self.seen_keys.add(key)
return ''
def keys(self):
return self.see... |
Generate an isocurve from vertex data in a surface mesh. | def iso_mesh_line(vertices, tris, vertex_data, levels):
"""Generate an isocurve from vertex data in a surface mesh.
Parameters
----------
vertices : ndarray, shape (Nv, 3)
Vertex coordinates.
tris : ndarray, shape (Nf, 3)
Indices of triangular element into the vertices array.
ve... |
Set the data | def set_data(self, vertices=None, tris=None, data=None):
"""Set the data
Parameters
----------
vertices : ndarray, shape (Nv, 3) | None
Vertex coordinates.
tris : ndarray, shape (Nf, 3) | None
Indices into the vertex array.
data : ndarray, shape (... |
Set the color | def set_color(self, color):
"""Set the color
Parameters
----------
color : instance of Color
The color to use.
"""
if color is not None:
self._color_lev = color
self._need_color_update = True
self.update() |
compute LineVisual color from level index and corresponding level color | def _compute_iso_color(self):
""" compute LineVisual color from level index and corresponding level
color
"""
level_color = []
colors = self._lc
for i, index in enumerate(self._li):
level_color.append(np.zeros((index, 4)) + colors[i])
self._cl = np.vst... |
Remove the layer artist for good | def remove(self):
"""
Remove the layer artist for good
"""
self._multivol.deallocate(self.id)
ARRAY_CACHE.pop(self.id, None)
PIXEL_CACHE.pop(self.id, None) |
Inject functions and constants from PyOpenGL but leave out the names that are deprecated or that we provide in our API. | def _inject():
""" Inject functions and constants from PyOpenGL but leave out the
names that are deprecated or that we provide in our API.
"""
# Get namespaces
NS = globals()
GLNS = _GL.__dict__
# Get names that we use in our API
used_names = []
used_names.extend([names[0] ... |
Alternative to imp. find_module that can also search in subpackages. | def _find_module(name, path=None):
"""
Alternative to `imp.find_module` that can also search in subpackages.
"""
parts = name.split('.')
for part in parts:
if path is not None:
path = [path]
fh, path, descr = imp.find_module(part, path)
if fh is not None and pa... |
Triangulate a set of vertices | def triangulate(vertices):
"""Triangulate a set of vertices
Parameters
----------
vertices : array-like
The vertices.
Returns
-------
vertices : array-like
The vertices.
tringles : array-like
The triangles.
"""
n = len(vertices)
vertices = np.asarray... |
Do the triangulation | def triangulate(self):
"""Do the triangulation
"""
self._initialize()
pts = self.pts
front = self._front
## Begin sweep (sec. 3.4)
for i in range(3, pts.shape[0]):
pi = pts[i]
#debug("========== New point %d: %s ==========... |
Force edge ( i j ) to be present in mesh. This works by removing intersected triangles and filling holes up to the cutting edge. | def _edge_event(self, i, j):
"""
Force edge (i, j) to be present in mesh.
This works by removing intersected triangles and filling holes up to
the cutting edge.
"""
front_index = self._front.index(i)
#debug(" == edge event ==")
front = self._fro... |
Return the triangle that has edge [ 0 ] as one of its vertices and is bisected by edge. Return None if no triangle is found. | def _find_cut_triangle(self, edge):
"""
Return the triangle that has edge[0] as one of its vertices and is
bisected by edge.
Return None if no triangle is found.
"""
edges = [] # opposite edge for each triangle attached to edge[0]
for tri in self.tris:
... |
Return the index where * edge * appears in the current front. If the edge is not in the front return - 1 | def _edge_in_front(self, edge):
""" Return the index where *edge* appears in the current front.
If the edge is not in the front, return -1
"""
e = (list(edge), list(edge)[::-1])
for i in range(len(self._front)-1):
if self._front[i:i+2] in e:
return i
... |
Given a triangle return the edge that is opposite point i. Vertexes are returned in the same orientation as in tri. | def _edge_opposite_point(self, tri, i):
""" Given a triangle, return the edge that is opposite point i.
Vertexes are returned in the same orientation as in tri.
"""
ind = tri.index(i)
return (tri[(ind+1) % 3], tri[(ind+2) % 3]) |
Given a triangle formed by edge and i return the triangle that shares edge. * i * may be either a point or the entire triangle. | def _adjacent_tri(self, edge, i):
"""
Given a triangle formed by edge and i, return the triangle that shares
edge. *i* may be either a point or the entire triangle.
"""
if not np.isscalar(i):
i = [x for x in i if x not in edge][0]
try:
pt1 = self.... |
Return the only tri that contains * edge *. If two tris share this edge raise an exception. | def _tri_from_edge(self, edge):
"""Return the only tri that contains *edge*. If two tris share this
edge, raise an exception.
"""
edge = tuple(edge)
p1 = self._edges_lookup.get(edge, None)
p2 = self._edges_lookup.get(edge[::-1], None)
if p1 is None:
if... |
Return the edges in * tri * excluding * edge *. | def _edges_in_tri_except(self, tri, edge):
"""Return the edges in *tri*, excluding *edge*.
"""
edges = [(tri[i], tri[(i+1) % 3]) for i in range(3)]
try:
edges.remove(tuple(edge))
except ValueError:
edges.remove(tuple(edge[::-1]))
return edges |
Return True if * edge * is below the current front. One of the points in * edge * must be _on_ the front at * front_index *. | def _edge_below_front(self, edge, front_index):
"""Return True if *edge* is below the current front.
One of the points in *edge* must be _on_ the front, at *front_index*.
"""
f0 = self._front[front_index-1]
f1 = self._front[front_index+1]
return (self._orientati... |
Given a list of * edges * return the first that is intersected by * cut_edge *. | def _intersected_edge(self, edges, cut_edge):
""" Given a list of *edges*, return the first that is intersected by
*cut_edge*.
"""
for edge in edges:
if self._edges_intersect(edge, cut_edge):
return edge |
Return a dictionary containing for each edge in self. edges a list of the positions at which the edge should be split. | def _find_edge_intersections(self):
"""
Return a dictionary containing, for each edge in self.edges, a list
of the positions at which the edge should be split.
"""
edges = self.pts[self.edges]
cuts = {} # { edge: [(intercept, point), ...], ... }
for i in range(ed... |
Return projection of ( a b ) onto ( a c ) Arguments are point locations not indexes. | def _projection(self, a, b, c):
"""Return projection of (a,b) onto (a,c)
Arguments are point locations, not indexes.
"""
ab = b - a
ac = c - a
return a + ((ab*ac).sum() / (ac*ac).sum()) * ac |
Return 1 if edges intersect completely ( endpoints excluded ) | def _edges_intersect(self, edge1, edge2):
"""
Return 1 if edges intersect completely (endpoints excluded)
"""
h12 = self._intersect_edge_arrays(self.pts[np.array(edge1)],
self.pts[np.array(edge2)])
h21 = self._intersect_edge_arrays(self.... |
Return a 2D array of intercepts such that intercepts [ i j ] is the intercept of lines [ i ] onto lines [ j ]. * lines * must be an array of point locations with shape ( N 2 2 ) where the axes are ( lines points_per_line xy_per_point ). The intercept is described in intersect_edge_arrays (). | def _intersection_matrix(self, lines):
"""
Return a 2D array of intercepts such that
intercepts[i, j] is the intercept of lines[i] onto lines[j].
*lines* must be an array of point locations with shape (N, 2, 2), where
the axes are (lines, points_per_line, xy_per_point).... |
Return the intercepts of all lines defined in * lines1 * as they intersect all lines in * lines2 *. Arguments are of shape (... 2 2 ) where axes are: 0: number of lines 1: two points per line 2: x y pair per point | def _intersect_edge_arrays(self, lines1, lines2):
"""Return the intercepts of all lines defined in *lines1* as they
intersect all lines in *lines2*.
Arguments are of shape (..., 2, 2), where axes are:
0: number of lines
1: two points per line
2: x,y pa... |
Returns + 1 if edge [ 0 ] - > point is clockwise from edge [ 0 ] - > edge [ 1 ] - 1 if counterclockwise and 0 if parallel. | def _orientation(self, edge, point):
""" Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1],
-1 if counterclockwise, and 0 if parallel.
"""
v1 = self.pts[point] - self.pts[edge[0]]
v2 = self.pts[edge[1]] - self.pts[edge[0]]
c = np.cross(v1, v2) # positive i... |
Entry point of the IPython extension | def load_ipython_extension(ipython):
""" Entry point of the IPython extension
Parameters
----------
IPython : IPython interpreter
An instance of the IPython interpreter that is handed
over to the extension
"""
import IPython
# don't continue if IPython version is < 3.0
... |
Load the webgl backend for the IPython notebook | def _load_webgl_backend(ipython):
""" Load the webgl backend for the IPython notebook"""
from .. import app
app_instance = app.use_app("ipynb_webgl")
if app_instance.backend_name == "ipynb_webgl":
ipython.write("Vispy IPython module has loaded successfully")
else:
# TODO: Improve t... |
Draw collection | def draw(self, mode=None):
""" Draw collection """
if self._need_update:
self._update()
program = self._programs[0]
mode = mode or self._mode
if self._indices_list is not None:
program.draw(mode, self._indices_buffer)
else:
program.d... |
Drop - in replacement for scipy. ndimage. gaussian_filter. | def gaussian_filter(data, sigma):
"""
Drop-in replacement for scipy.ndimage.gaussian_filter.
(note: results are only approximately equal to the output of
gaussian_filter)
"""
if np.isscalar(sigma):
sigma = (sigma,) * data.ndim
baseline = data.mean()
filtered = data - baseline
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.