text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.
self.tokens.expect(grammar.select_from)
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 colum... |
if isinstance(expr, ast.Var):
return expr.value
if isinstance(expr, ast.Resolve):
# We know the RHS of resolve is a Literal because that's what
# Parser.dot_rhs does.
return expr.rhs.value
if isinstance(expr, ast.Select) and isinstance(expr.rhs,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.first.end
self.tokens.expect(common_grammar.lparen)
if self.tokens.matche... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def application(self, func):
"""Parse the function application subgrammar. Function application can, conceptually, be thought of as a mixfix operator, similar to... |
start = self.tokens.matched.start
if self.tokens.accept(common_grammar.rparen):
# That was easy.
return ast.Apply(func, start=start, end=self.tokens.matched.end,
source=self.original)
arguments = [self.expression()]
while self.tokens... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 than once.
if only_value is not None:
raise ValueError("%r is not a singleton." % self)
only_value = value
if only_value is self.__Unset... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cpu(self):
"""Record CPU usage.""" |
value = int(psutil.cpu_percent())
set_metric("cpu", value, category=self.category)
gauge("cpu", value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mem(self):
"""Record Memory usage.""" |
value = int(psutil.virtual_memory().percent)
set_metric("memory", value, category=self.category)
gauge("memory", value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(psutil.disk_usage(mountpoints[0]).percent)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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".format(self.device), value, category=self.categor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 must be a type or a Protocol. "
"Got an instance of %r.") % ty... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 '... |
for function in cls.required():
if not function.implemented_for_type(for_type):
raise TypeError(
"%r doesn't implement %r so it cannot participate in "
"the protocol %r." %
(for_type, function.func.__name__, cls))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
for type_ in cls.__get_type_args(for_type, for_types):
implementations = {}
for function in cls.required():
method = getattr(type_, function.__name__, None)
if not callable(method):
raise TypeError(
"%s.implicit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Ar... |
def _late_dynamic_dispatcher(obj, *args):
method = getattr(obj, func_name, None)
if not callable(method):
raise NotImplementedError(
"Instance method %r is not implemented by %r." % (
func_name, obj))
return method... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def implicit_dynamic(cls, for_type=None, for_types=None):
"""Automatically generate late dynamic dispatchers to type. This is similar to 'implicit_static', excep... |
for type_ in cls.__get_type_args(for_type, for_types):
implementations = {}
for function in cls.functions():
implementations[function] = cls._build_late_dispatcher(
func_name=function.__name__)
cls.implement(for_type=type_, implementation... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def implement(cls, implementations, for_type=None, for_types=None):
"""Provide protocol implementation for a type. Register all implementations of multimethod fu... |
for type_ in cls.__get_type_args(for_type, for_types):
cls._implement_for_type(for_type=type_,
implementations=implementations) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)... |
if self.OBJECTFILTER_WORDS.search(source):
syntax_ = "objectfilter"
else:
syntax_ = None # Default it is.
return query.Query(source, syntax=syntax_) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, rules
rules = []
tag = match.group(1)
continue
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize(expr):
"""Pass through n-ary expressions, and eliminate empty branches. Variadic and binary expressions recursively visit all their children. If al... |
children = []
for child in expr.children:
branch = normalize(child)
if branch is None:
continue
if type(branch) is type(expr):
children.extend(branch.children)
else:
children.append(branch)
if len(children) == 0:
return None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
elif g == app_settings.MAX_GRANULARITY and keep:
keep = False
yield g
if keep:
yield g |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 in self._granularities():
date_string = date.strftime(metric_key_patterns[g]["date_format"])
patts[g] = metric_key_patt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
slug = slugify(slug) # Ensure slugs have a consistent format
if date is None:
date = datetime.utcnow()
patts = self._build_key_patterns(slug, date)
if granularity == "all":
return list(patts.values())
return [patts[granularity]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = "m:{0}:*".format(slug)
keys = self.r.keys(prefix)
self.r.delete(*k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 met... |
# Add the slug to the set of metric slugs
self.r.sadd(self._metric_slugs_key, slug)
if category:
self._categorize(slug, category)
# Increment keys. NOTE: current redis-py (2.7.2) doesn't include an
# incrby method; .incr accepts a second ``amount`` parameter.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, wee... |
results = OrderedDict()
granularities = self._granularities()
keys = self._build_keys(slug)
for granularity, key in zip(granularities, keys):
results[granularity] = self.r.get(key)
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 re... |
# meh. I should have been consistent here, but I'm lazy, so support these
# value names instead of granularity names, but respect the min/max
# granularity settings.
keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']
key_mapping = {gran: key for gran, key in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 from Set
self.r.srem(self._categories_key, category) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 *... |
if not type(slugs) == list:
slugs = [slugs]
# Build the set of Redis keys that we need to get.
keys = []
for slug in slugs:
for date in self._date_range(granularity, since, to):
keys += self._build_keys(slug, date, granularity)
keys = lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 t... |
k = self._gauge_key(slug)
self.r.sadd(self._gauge_slugs_key, slug) # keep track of all Gauges
self.r.set(k, current_value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gauge(slug, maximum=9000, size=200, coerce='float'):
"""Include a Donut Chart for the specified Gauge. * ``slug`` -- the unique slug for the Gauge. * ``maxim... |
coerce_options = {'float': float, 'int': int, 'str': str}
coerce = coerce_options.get(coerce, float)
redis = get_r()
value = coerce(redis.get_gauge(slug))
if value < maximum and coerce == float:
diff = round(maximum - value, 2)
elif value < maximum:
diff = maximum - value
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metric_history(slug, granularity="daily", since=None, to=None, with_data_table=False):
"""Template Tag to display a metric's history. * ``slug`` -- the metri... |
r = get_r()
try:
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
if to and len(to) == 10: # yyyy-mm-dd
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_... |
r = get_r()
metrics_data = []
granularities = r._granularities()
# XXX converting granularties into their key-name for metrics.
keys = ['seconds', 'minutes', 'hours', 'day', 'week', 'month', 'year']
key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)}
keys = [key_mapping[gra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate_history(slugs, granularity="daily", since=None, with_data_table=False):
"""Template Tag to display history for multiple metrics. * ``slug_list`` --... |
r = get_r()
slugs = list(slugs)
try:
if since and len(since) == 10: # yyyy-mm-dd
since = datetime.strptime(since, "%Y-%m-%d")
elif since and len(since) == 19: # yyyy-mm-dd HH:MM:ss
since = datetime.strptime(since, "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 execu... |
class UserFunction(std_core.TypedFunction):
name = func.__name__
def __call__(self, *args, **kwargs):
return func(*args, **kwargs)
@classmethod
def reflect_static_args(cls):
return arg_types
@classmethod
def reflect_static_return(cls):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer(query, replacements=None, root_type=None, libs=("stdcore", "stdmath")):
"""Determine the type of the query's output without actually running it. Argume... |
# Always make the scope stack start with stdcore.
if root_type:
type_scope = scope.ScopeStack(std_core.MODULE, root_type)
else:
type_scope = scope.ScopeStack(std_core.MODULE)
stdcore_included = False
for lib in libs:
if lib == "stdcore":
stdcore_included = True
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def skip(self, steps=1):
"""Skip ahead by 'steps' tokens.""" |
for _ in six.moves.range(steps):
self.next_token() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(self.source, position)
if not m:
continue
posit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
except IOError:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version(dev_version=False):
"""Generates a version string. Arguments: dev_version: Generate a verbose development version from git commits. Examples: 1.1... |
if dev_version:
version = git_dev_version()
if not version:
raise RuntimeError("Could not generate dev version from git.")
return version
return "1!%d.%d" % (MAJOR, MINOR) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getvalues(self):
"""Yields all the values from 'generator_func' and type-checks. Yields: Whatever 'generator_func' yields. Raises: TypeError: if subsequent v... |
idx = 0
generator = self._generator_func()
first_value = next(generator)
self._value_type = type(first_value)
yield first_value
for idx, value in enumerate(generator):
if not isinstance(value, self._value_type):
raise TypeError(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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" % (
len(stack),
" -> ".join("%s:%d:%s" % x[0:3] for x in stac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 type, not instance.")
return args[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 poss... |
self._write_lock.acquire()
try:
if self._preferred(preferred=over, over=prefer):
raise ValueError(
"Type %r is already preferred over %r." % (over, prefer))
prefs = self._prefer_table.setdefault(prefer, set())
prefs.add(over)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
result = self._dispatch_table.get(dispatch_type)
if result:
return result
# The outer try ensures the lock is always released.
with self._write_lock:
try:
dispatch_mro = dispatch_type.mro()
except TypeError:
# Not ever... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def implementation(self, for_type=None, for_types=None):
"""Return a decorator that will register the implementation. Example: @multimethod def add(x, y):
pass ... |
for_types = self.__get_types(for_type, for_types)
def _decorator(implementation):
self.implement(implementation, for_types=for_types)
return self
return _decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def implement(self, implementation, for_type=None, for_types=None):
"""Registers an implementing function for for_type. Arguments: implementation: Callable imple... |
unbound_implementation = self.__get_unbound_function(implementation)
for_types = self.__get_types(for_type, for_types)
for t in for_types:
self._write_lock.acquire()
try:
self.implementations.append((t, unbound_implementation))
finally:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 %2B. We want
# want to keep the + in the url (it's ok according to RFC 1738)
# https://docs.djangoproject.com/en/1.6/releases/... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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']:
self._name = d['name']
if 'state' in d:
if isinstance(d['state'], str) or isinstance(d['state'], unicode):
if d['state'] in state... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_wait = cfg.retry_wait
retry_backoff = cfg.retry_backoff
last_error = None
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) ... |
lines = None
connects = None
vertex_level = None
level_index = None
if not all([isinstance(x, np.ndarray) for x in (vertices, tris,
vertex_data, levels)]):
raise ValueError('all inputs must be numpy arrays')
if vertices.shape[1] <= 3:
verts = vertices
elif v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.vstack(level_color) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] for names in _pyopengl2._functions_to_import])
used_names.extend([name for name in _pyopengl2._used_functions])
NS['_used_names'] = used_names
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 part != parts[-1]:
fh.close()
return fh, path, descr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triangulate(vertices):
"""Triangulate a set of vertices Parameters vertices : array-like The vertices. Returns ------- vertices : array-like The vertices. tr... |
n = len(vertices)
vertices = np.asarray(vertices)
zmean = vertices[:, 2].mean()
vertices_2d = vertices[:, :2]
segments = np.repeat(np.arange(n + 1), 2)[1:-1]
segments[-2:] = n - 1, 0
if _TRIANGLE_AVAILABLE:
vertices_2d, triangles = _triangulate_cpp(vertices_2d, segments)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ==========" % (i, pi))
# First, triangulate from fr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(edges.shape[0]-1):
# intersection of edge i onto all others
int1 = self._intersect_edge_arrays(edges[i:i+1], edges[i+1:])
# intersection of all edges onto edge i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_ipython_extension(ipython):
""" Entry point of the IPython extension Parameters IPython : IPython interpreter An instance of the IPython interpreter tha... |
import IPython
# don't continue if IPython version is < 3.0
ipy_version = LooseVersion(IPython.__version__)
if ipy_version < LooseVersion("3.0.0"):
ipython.write_err("Your IPython version is older than "
"version 3.0.0, the minimum for Vispy's"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 this error message
ipython.write_err("Unable to load webgl backend of Vispy") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale(s, dtype=None):
"""Non-uniform scaling along the x, y, and z axes Parameters s : array-like, shape (3,) Scaling in x, y, z. dtype : dtype | None Output... |
assert len(s) == 3
return np.array(np.diag(np.concatenate([s, (1.,)])), dtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotate(angle, axis, dtype=None):
"""The 3x3 rotation matrix for rotation about a vector. Parameters angle : float The angle of rotation, in degrees. axis : n... |
angle = np.radians(angle)
assert len(axis) == 3
x, y, z = axis / np.linalg.norm(axis)
c, s = math.cos(angle), math.sin(angle)
cx, cy, cz = (1 - c) * x, (1 - c) * y, (1 - c) * z
M = np.array([[cx * x + c, cy * x - z * s, cz * x + y * s, .0],
[cx * y + z * s, cy * y + c, cz * y ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perspective(fovy, aspect, znear, zfar):
"""Create perspective projection matrix Parameters fovy : float The field of view along the y axis. aspect : float As... |
assert(znear != zfar)
h = math.tan(fovy / 360.0 * math.pi) * znear
w = h * aspect
return frustum(-w, w, -h, h, znear, zfar) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def affine_map(points1, points2):
""" Find a 3D transformation matrix that maps points1 onto points2. Arguments are specified as arrays of four 3D coordinates, s... |
A = np.ones((4, 4))
A[:, :3] = points1
B = np.ones((4, 4))
B[:, :3] = points2
# solve 3 sets of linear equations to determine
# transformation matrix elements
matrix = np.eye(4)
for i in range(3):
# solve Ax = B; x is one row of the desired transformation matrix
matrix[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finish(self, msg=None):
"""Add a final message; flush the message list if no parent profiler. """ |
if self._finished or self.disable:
return
self._finished = True
if msg is not None:
self(msg)
self._new_msg("< Exiting %s, total time: %0.4f ms",
self._name, (ptime.time() - self._firstTime) * 1000)
type(self)._depth -= 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init():
""" Create global Config object, parse command flags """ |
global config, _data_path, _allowed_config_keys
app_dir = _get_vispy_app_dir()
if app_dir is not None:
_data_path = op.join(app_dir, 'data')
_test_data_path = op.join(app_dir, 'test_data')
else:
_data_path = _test_data_path = None
# All allowed config keys and the types th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_command_line_arguments():
""" Transform vispy specific command line args to vispy config. Put into a function so that any variables dont leak in the v... |
global config
# Get command line args for vispy
argnames = ['vispy-backend=', 'vispy-gl-debug', 'vispy-glir-file=',
'vispy-log=', 'vispy-help', 'vispy-profile=', 'vispy-cprofile',
'vispy-dpi=', 'vispy-audit-tests']
try:
opts, args = getopt.getopt(sys.argv[1:], ''... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_vispy_app_dir():
"""Helper to get the default directory for storing vispy data""" |
# Define default user directory
user_dir = os.path.expanduser('~')
# Get system app data dir
path = None
if sys.platform.startswith('win'):
path1, path2 = os.getenv('LOCALAPPDATA'), os.getenv('APPDATA')
path = path1 or path2
elif sys.platform.startswith('darwin'):
path ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_config_fname():
"""Helper for the vispy config file""" |
directory = _get_vispy_app_dir()
if directory is None:
return None
fname = op.join(directory, 'vispy.json')
if os.environ.get('_VISPY_CONFIG_TESTING', None) is not None:
fname = op.join(_TempDir(), 'vispy.json')
return fname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_config(**kwargs):
"""Save configuration keys to vispy config file Parameters **kwargs : keyword arguments Key/value pairs to save to the config file. ""... |
if kwargs == {}:
kwargs = config._config
current_config = _load_config()
current_config.update(**kwargs)
# write to disk
fname = _get_config_fname()
if fname is None:
raise RuntimeError('config filename could not be determined')
if not op.isdir(op.dirname(fname)):
os... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_data_dir(directory=None, create=False, save=False):
"""Set vispy data download directory Parameters directory : str | None The directory to use. create :... |
if directory is None:
directory = _data_path
if _data_path is None:
raise IOError('default path cannot be determined, please '
'set it manually (directory != None)')
if not op.isdir(directory):
if not create:
raise IOError('directory "%s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _enable_profiling():
""" Start profiling and register callback to print stats when the program exits. """ |
import cProfile
import atexit
global _profiler
_profiler = cProfile.Profile()
_profiler.enable()
atexit.register(_profile_atexit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sys_info(fname=None, overwrite=False):
"""Get relevant system and debugging information Parameters fname : str | None Filename to dump info to. Use None to s... |
if fname is not None and op.isfile(fname) and not overwrite:
raise IOError('file exists, use overwrite=True to overwrite')
out = ''
try:
# Nest all imports here to avoid any circular imports
from ..app import use_app, Canvas
from ..app.backends import BACKEND_NAMES
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compact(vertices, indices, tolerance=1e-3):
""" Compact vertices and indices within given tolerance """ |
# Transform vertices into a structured array for np.unique to work
n = len(vertices)
V = np.zeros(n, dtype=[("pos", np.float32, 3)])
V["pos"][:, 0] = vertices[:, 0]
V["pos"][:, 1] = vertices[:, 1]
V["pos"][:, 2] = vertices[:, 2]
epsilon = 1e-3
decimals = int(np.log(epsilon)/np.log(1/1... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normals(vertices, indices):
""" Compute normals over a triangulated surface Parameters vertices : ndarray (n,3) triangles vertices indices : ndarray (p,3) tr... |
# Compact similar vertices
vertices, indices, mapping = compact(vertices, indices)
T = vertices[indices]
N = np.cross(T[:, 1] - T[:, 0], T[:, 2]-T[:, 0])
L = np.sqrt(np.sum(N * N, axis=1))
L[L == 0] = 1.0 # prevent divide-by-zero
N /= L[:, np.newaxis]
normals = np.zeros_like(vertices... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_native(self):
""" Create the native widget if not already done so. If the widget is already created, this function does nothing. """ |
if self._backend is not None:
return
# Make sure that the app is active
assert self._app.native
# Instantiate the backend with the right class
self._app.backend_module.CanvasBackend(self, **self._backend_kwargs)
# self._backend = set by BaseCanvasBackend
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, fun):
""" Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is... |
# Get and check name
name = fun.__name__
if not name.startswith('on_'):
raise ValueError('When connecting a function based on its name, '
'the name should start with "on_"')
eventname = name[3:]
# Get emitter
try:
emit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show(self, visible=True, run=False):
"""Show or hide the canvas Parameters visible : bool Make the canvas visible. run : bool Run the backend event loop. """ |
self._backend._vispy_set_visible(visible)
if run:
self.app.run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Close the canvas Notes ----- This will usually destroy the GL context. For Qt, the context (and widget) will be destroyed only if the widget ... |
if self._backend is not None and not self._closed:
self._closed = True
self.events.close()
self._backend._vispy_close()
forget_canvas(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_fps(self, event):
"""Update the fps after every window""" |
self._frame_count += 1
diff = time() - self._basetime
if (diff > self._fps_window):
self._fps = self._frame_count / diff
self._basetime = time()
self._frame_count = 0
self._fps_callback(self.fps) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def measure_fps(self, window=1, callback='%1.1f FPS'):
"""Measure the current FPS Sets the update window, connects the draw event to update_fps and sets the call... |
# Connect update_fps function to draw
self.events.draw.disconnect(self._update_fps)
if callback:
if isinstance(callback, string_types):
callback_str = callback # because callback gets overwritten
def callback(x):
print(callback_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self):
""" Render the canvas to an offscreen buffer and return the image array. Returns ------- image : array Numpy array of type ubyte and shape (h, ... |
self.set_current()
size = self.physical_size
fbo = FrameBuffer(color=RenderBuffer(size[::-1]),
depth=RenderBuffer(size[::-1]))
try:
fbo.activate()
self.events.draw()
return fbo.read()
finally:
fbo.deactiv... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drag_events(self):
""" Return a list of all mouse events in the current drag operation. Returns None if there is no current drag operation. """ |
if not self.is_dragging:
return None
event = self
events = []
while True:
# mouse_press events can only be the start of a trail
if event is None or event.type == 'mouse_press':
break
events.append(event)
event ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.