Search is not available for this dataset
text stringlengths 75 104k |
|---|
def accept_operator(self, precedence):
"""Accept the next binary operator only if it's of higher precedence."""
match = grammar.infix(self.tokens)
if not match:
return
if match.operator.precedence < precedence:
return
# The next thing is an operator that... |
def operator(self, lhs, min_precedence):
"""Climb operator precedence as long as there are operators.
This function implements a basic precedence climbing parser to deal
with binary operators in a sane fashion. The outer loop will keep
spinning as long as the next token is an operator w... |
def dot_rhs(self):
"""Match the right-hand side of a dot (.) operator.
The RHS must be a symbol token, but it is interpreted as a literal
string (because that's what goes in the AST of Resolve.)
"""
self.tokens.expect(common_grammar.symbol)
return ast.Literal(self.tokens... |
def select(self):
"""First part of an SQL query."""
# Try to match the asterisk, any or list of vars.
if self.tokens.accept(grammar.select_any):
return self.select_any()
if self.tokens.accept(grammar.select_all):
# The FROM after SELECT * is required.
... |
def _guess_name_of(self, expr):
"""Tries to guess what variable name 'expr' ends in.
This is a heuristic that roughly emulates what most SQL databases
name columns, based on selected variable names or applied functions.
"""
if isinstance(expr, ast.Var):
return expr.v... |
def select_limit(self, source_expression):
"""Match LIMIT take [OFFSET drop]."""
start = self.tokens.matched.start
# The expression right after LIMIT is the count to take.
limit_count_expression = self.expression()
# Optional OFFSET follows.
if self.tokens.accept(gramma... |
def builtin(self, keyword):
"""Parse the pseudo-function application subgrammar."""
# The match includes the lparen token, so the keyword is just the first
# token in the match, not the whole thing.
keyword_start = self.tokens.matched.first.start
keyword_end = self.tokens.matched... |
def application(self, func):
"""Parse the function application subgrammar.
Function application can, conceptually, be thought of as a mixfix
operator, similar to the way array subscripting works. However, it is
not clear at this point whether we want to allow it to work as such,
... |
def list(self):
"""Parse a list (tuple) which can contain any combination of types."""
start = self.tokens.matched.start
if self.tokens.accept(common_grammar.rbracket):
return ast.Tuple(start=start, end=self.tokens.matched.end,
source=self.original)
... |
def get_singleton(self):
"""If the row only has one column, return that value; otherwise raise.
Raises:
ValueError, if count of columns is not 1.
"""
only_value = None
for value in six.itervalues(self.ordered_dict):
# This loop will raise if it runs more ... |
def _cpu(self):
"""Record CPU usage."""
value = int(psutil.cpu_percent())
set_metric("cpu", value, category=self.category)
gauge("cpu", value) |
def _mem(self):
"""Record Memory usage."""
value = int(psutil.virtual_memory().percent)
set_metric("memory", value, category=self.category)
gauge("memory", value) |
def _disk(self):
"""Record Disk usage."""
mountpoints = [
p.mountpoint for p in psutil.disk_partitions()
if p.device.endswith(self.device)
]
if len(mountpoints) != 1:
raise CommandError("Unknown device: {0}".format(self.device))
value = int(ps... |
def _net(self):
"""Record Network usage."""
data = psutil.network_io_counters(pernic=True)
if self.device not in data:
raise CommandError("Unknown device: {0}".format(self.device))
# Network bytes sent
value = data[self.device].bytes_sent
metric("net-{0}-sent... |
def implements(obj, protocol):
"""Does the object 'obj' implement the 'prococol'?"""
if isinstance(obj, type):
raise TypeError("First argument to implements must be an instance. "
"Got %r." % obj)
return isinstance(obj, protocol) or issubclass(AnyType, protocol) |
def isa(cls, protocol):
"""Does the type 'cls' participate in the 'protocol'?"""
if not isinstance(cls, type):
raise TypeError("First argument to isa must be a type. Got %s." %
repr(cls))
if not isinstance(protocol, type):
raise TypeError(("Second argument to isa mus... |
def implemented(cls, for_type):
"""Assert that protocol 'cls' is implemented for type 'for_type'.
This will cause 'for_type' to be registered with the protocol 'cls'.
Subsequently, protocol.isa(for_type, cls) will return True, as will
isinstance, issubclass and others.
Raises:
... |
def __get_type_args(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... |
def implicit_static(cls, for_type=None, for_types=None):
"""Automatically generate implementations for a type.
Implement the protocol for the 'for_type' type by dispatching each
member function of the protocol to an instance method of the same name
declared on the type 'for_type'.
... |
def _build_late_dispatcher(func_name):
"""Return a function that calls method 'func_name' on objects.
This is useful for building late-bound dynamic dispatch.
Arguments:
func_name: The name of the instance method that should be called.
Returns:
A function that ... |
def implicit_dynamic(cls, for_type=None, for_types=None):
"""Automatically generate late dynamic dispatchers to type.
This is similar to 'implicit_static', except instead of binding the
instance methods, it generates a dispatcher that will call whatever
instance method of the same name ... |
def implement(cls, implementations, for_type=None, for_types=None):
"""Provide protocol implementation for a type.
Register all implementations of multimethod functions in this
protocol and add the type into the abstract base class of the
protocol.
Arguments:
implem... |
def _parse_query(self, source):
"""Parse one of the rules as either objectfilter or dottysql.
Example:
_parse_query("5 + 5")
# Returns Sum(Literal(5), Literal(5))
Arguments:
source: A rule in either objectfilter or dottysql syntax.
Returns:
... |
def _parse_tagfile(self):
"""Parse the tagfile and yield tuples of tag_name, list of rule ASTs."""
rules = None
tag = None
for line in self.original:
match = self.TAG_DECL_LINE.match(line)
if match:
if tag and rules:
yield tag, ... |
def normalize(expr):
"""Normalize both sides, but don't eliminate the expression."""
lhs = normalize(expr.lhs)
rhs = normalize(expr.rhs)
return type(expr)(lhs, rhs, start=lhs.start, end=rhs.end) |
def normalize(expr):
"""No elimination, but normalize arguments."""
args = [normalize(arg) for arg in expr.args]
return type(expr)(expr.func, *args, start=expr.start, end=expr.end) |
def normalize(expr):
"""Pass through n-ary expressions, and eliminate empty branches.
Variadic and binary expressions recursively visit all their children.
If all children are eliminated then the parent expression is also
eliminated:
(& [removed] [removed]) => [removed]
If only one child is ... |
def dedupe(items):
"""Remove duplicates from a sequence (of hashable items) while maintaining
order. NOTE: This only works if items in the list are hashable types.
Taken from the Python Cookbook, 3rd ed. Such a great book!
"""
seen = set()
for item in items:
if item not in seen:
... |
def _date_range(self, granularity, since, to=None):
"""Returns a generator that yields ``datetime.datetime`` objects from
the ``since`` date until ``to`` (default: *now*).
* ``granularity`` -- The granularity at which the generated datetime
objects should be created: seconds, minutes,... |
def _category_slugs(self, category):
"""Returns a set of the metric slugs for the given category"""
key = self._category_key(category)
slugs = self.r.smembers(key)
return slugs |
def _categorize(self, slug, category):
"""Add the ``slug`` to the ``category``. We store category data as
as set, with a key of the form::
c:<category name>
The data is set of metric slugs::
"slug-a", "slug-b", ...
"""
key = self._category_key(category... |
def _granularities(self):
"""Returns a generator of all possible granularities based on the
MIN_GRANULARITY and MAX_GRANULARITY settings.
"""
keep = False
for g in GRANULARITIES:
if g == app_settings.MIN_GRANULARITY and not keep:
keep = True
... |
def _build_key_patterns(self, slug, date):
"""Builds an OrderedDict of metric keys and patterns for the given slug
and date."""
# we want to keep the order, from smallest to largest granularity
patts = OrderedDict()
metric_key_patterns = self._metric_key_patterns()
for g ... |
def _build_keys(self, slug, date=None, granularity='all'):
"""Builds redis keys used to store metrics.
* ``slug`` -- a slug used for a metric, e.g. "user-signups"
* ``date`` -- (optional) A ``datetime.datetime`` object used to
generate the time period for the metric. If omitted, the c... |
def metric_slugs_by_category(self):
"""Return a dictionary of metrics data indexed by category:
{<category_name>: set(<slug1>, <slug2>, ...)}
"""
result = OrderedDict()
categories = sorted(self.r.smembers(self._categories_key))
for category in categories:
... |
def delete_metric(self, slug):
"""Removes all keys for the given ``slug``."""
# To remove all keys for a slug, I need to retrieve them all from
# the set of metric keys, This uses the redis "keys" command, which is
# inefficient, but this shouldn't be used all that often.
prefix... |
def set_metric(self, slug, value, category=None, expire=None, date=None):
"""Assigns a specific value to the *current* metric. You can use this
to start a metric at a value greater than 0 or to reset a metric.
The given slug will be used to generate Redis keys at the following
granulari... |
def metric(self, slug, num=1, category=None, expire=None, date=None):
"""Records a metric, creating it if it doesn't exist or incrementing it
if it does. All metrics are prefixed with 'm', and automatically
aggregate for Seconds, Minutes, Hours, Day, Week, Month, and Year.
Parameters:
... |
def get_metric(self, slug):
"""Get the current values for a metric.
Returns a dictionary with metric values accumulated for the seconds,
minutes, hours, day, week, month, and year.
"""
results = OrderedDict()
granularities = self._granularities()
keys = self._bu... |
def get_metrics(self, slug_list):
"""Get the metrics for multiple slugs.
Returns a list of two-tuples containing the metric slug and a
dictionary like the one returned by ``get_metric``::
(
some-metric, {
'seconds': 0, 'minutes': 0, 'hours': 0,
... |
def get_category_metrics(self, category):
"""Get metrics belonging to the given category"""
slug_list = self._category_slugs(category)
return self.get_metrics(slug_list) |
def delete_category(self, category):
"""Removes the category from Redis. This doesn't touch the metrics;
they simply become uncategorized."""
# Remove mapping of metrics-to-category
category_key = self._category_key(category)
self.r.delete(category_key)
# Remove category... |
def reset_category(self, category, metric_slugs):
"""Resets (or creates) a category containing a list of metrics.
* ``category`` -- A category name
* ``metric_slugs`` -- a list of all metrics that are members of the
category.
"""
key = self._category_key(category)
... |
def get_metric_history(self, slugs, since=None, to=None, granularity='daily'):
"""Get history for one or more metrics.
* ``slugs`` -- a slug OR a list of slugs
* ``since`` -- the date from which we start pulling metrics
* ``to`` -- the date until which we start pulling metrics
*... |
def get_metric_history_as_columns(self, slugs, since=None,
granularity='daily'):
"""Provides the same data as ``get_metric_history``, but in a columnar
format. If you had the following yearly history, for example::
[
('m:bar:y:2012', '1'... |
def get_metric_history_chart_data(self, slugs, since=None, granularity='daily'):
"""Provides the same data as ``get_metric_history``, but with metrics
data arranged in a format that's easy to plot with Chart.js. If you had
the following yearly history, for example::
[
... |
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... |
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) |
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 ... |
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`` --... |
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... |
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... |
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... |
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... |
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... |
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... |
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
... |
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 |
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 |
def skip(self, steps=1):
"""Skip ahead by 'steps' tokens."""
for _ in six.moves.range(steps):
self.next_token() |
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 |
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 |
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(... |
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) |
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()) |
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)
... |
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 ... |
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... |
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
... |
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... |
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.
"... |
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():
... |
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... |
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 |
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" ... |
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... |
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 ... |
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... |
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... |
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
... |
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... |
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... |
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',
... |
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 ... |
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 |
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_... |
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 |
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... |
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... |
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) |
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)
... |
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... |
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) |
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) |
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) |
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... |
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']:
... |
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... |
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... |
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,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.