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 dxdy(line): """ return normalised ascent vector """
x0, y0, x1, y1 = line dx = float(x1 - x0) dy = float(y1 - y0) f = hypot(dx, dy) return dx / f, dy / f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromAttr(mid, ang, dist): """ create from middle, angle and distance """
mx, my = mid dx = cos(ang) * dist * 0.5 dy = sin(ang) * dist * 0.5 return mx - dx, my - dy, mx + dx, my + dy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromAttr2(start, ang, dist): """ create from start, angle and distance """
sx, sy = start dx = cos(ang) * dist dy = sin(ang) * dist return sx, sy, sx + dx, sy + dy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(l1, l2): """ merge 2 lines together """
x1, y1, x2, y2 = l1 xx1, yy1, xx2, yy2 = l2 comb = ((x1, y1, xx1, yy1), (x1, y1, xx2, yy2), (x2, y2, xx1, yy1), (x2, y2, xx2, yy2)) d = [length(c) for c in comb] i = argmax(d) dist = d[i] mid = middle(comb[i]) a = (angle(l1) + angle(l2)) * 0.5 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distance(line, point): """ infinite line to point or line to line distance is point is given as line - use middle point of that liune """
x0, y0, x1, y1 = line try: p1, p2 = point except ValueError: # line is given instead of point p1, p2 = middle(point) n1 = ascent(line) n2 = -1 n0 = y0 - n1 * x0 return abs(n1 * p1 + n2 * p2 + n0) / (n1 ** 2 + n2 ** 2) ** 0.5
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intersection(line1, line2): """ Return the coordinates of a point of intersection given two lines. Return None if the lines are parallel, but non-colli_near....
x1, y1, x2, y2 = line1 u1, v1, u2, v2 = line2 (a, b), (c, d) = (x2 - x1, u1 - u2), (y2 - y1, v1 - v2) e, f = u1 - x1, v1 - y1 # Solve ((a,b), (c,d)) * (t,s) = (e,f) denom = float(a * d - b * c) if _near(denom, 0): # parallel # If colli_near, the equation is solvable with t =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate(line, ascent, offs=0): """ offs -> shifts parallel to line ascent -> rotate line """
# TODO: why do I have thuis factor here? ascent *= -2 offs *= -2 l0 = length(line) # change relative to line: t0 = offs # -h+offs t1 = l0 * ascent + offs return translate2P(line, t0, t1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def splitN(line, n): """ split a line n times returns n sublines """
x0, y0, x1, y1 = line out = empty((n, 4), dtype=type(line[0])) px, py = x0, y0 dx = (x1 - x0) / n dy = (y1 - y0) / n for i in range(n): o = out[i] o[0] = px o[1] = py px += dx py += dy o[2] = px o[3] = py return out
<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_files(files): """ Remove all given files. Args: files (list): List of filenames, which will be removed. """
logger.debug("Request for file removal (_remove_files()).") for fn in files: if os.path.exists(fn): logger.debug("Removing '%s'." % fn) os.remove(fn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_read_meta_file(fn, error_protocol): """ Try to read MetadataFile. If the exception is raised, log the errors to the `error_protocol` and return None. "...
try: return MetadataFile(fn) except Exception, e: error_protocol.append( "Can't read MetadataFile '%s':\n\t%s\n" % (fn, e.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 _process_pair(first_fn, second_fn, error_protocol): """ Look at given filenames, decide which is what and try to pair them. """
ebook = None metadata = None if _is_meta(first_fn) and not _is_meta(second_fn): # 1st meta, 2nd data logger.debug( "Parsed: '%s' as meta, '%s' as data." % (first_fn, second_fn) ) metadata, ebook = first_fn, second_fn elif not _is_meta(first_fn) and _is_meta(secon...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_directory(files, user_conf, error_protocol): """ Look at items in given directory, try to match them for same names and pair them. If the items can'...
items = [] banned = [settings.USER_IMPORT_LOG, settings.USER_ERROR_LOG] files = filter(lambda x: not os.path.basename(x) in banned, files) if len(files) == 2 and conf_merger(user_conf, "SAME_DIR_PAIRING"): logger.debug("There are only two files.") items.extend(_process_pair(files[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 _index(array, item, key=None): """ Array search function. Written, because ``.index()`` method for array doesn't have `key` parameter and raises `ValueError`...
for i, el in enumerate(array): resolved_el = key(el) if key else el if resolved_el == item: return i return -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 _isbn_pairing(items): """ Pair `items` with same ISBN into `DataPair` objects. Args: items (list): list of items, which will be searched. Returns: list: lis...
NameWrapper = namedtuple("NameWrapper", ["name", "obj"]) metas = map( lambda x: NameWrapper(_just_name(x.filename), x), filter(lambda x: isinstance(x, MetadataFile), items) ) ebooks = map( lambda x: NameWrapper(_just_name(x.filename), x), filter(lambda x: isinstance(x, 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 _create_import_log(items): """ Used to create log with successfully imported data. """
log = [] for item in items: if isinstance(item, MetadataFile): log.append( "Metadata file '%s' successfully imported." % item.filename ) elif isinstance(item, EbookFile): log.append( "Ebook file '%s' successfully imported." % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_items(items, user_conf, error_protocol): """ Parse metadata. Remove processed and sucessfully parsed items. Returns sucessfully processed items. """
def process_meta(item, error_protocol): try: return item._parse() except Exception, e: error_protocol.append( "Can't parse %s: %s" % (item._get_filenames()[0], e.message) ) if isinstance(item, DataPair): return item.eb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, daemon=True): """ Start driving the chain asynchronously, return immediately :param daemon: ungracefully kill the driver when the program termina...
if self._run_lock.acquire(False): try: # there is a short race window in which `start` release the lock, # but `run` has not picked it up yet, but the thread exists anyway if self._run_thread is None: self._run_thread = threading.T...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Start driving the chain, block until done """
with self._run_lock: while self.mounts: for mount in self.mounts: try: next(mount) except StopIteration: self.mounts.remove(mount)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill(self, color): """ Fill the whole screen with the given color. :param color: Color to use for filling :type color: tuple """
self.matrix = [[color for _ in range(self.height)] for _ in range(self.width)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_dot(self, pos, color): """ Draw one single dot with the given color on the screen. :param pos: Position of the dot :param color: COlor for the dot :type...
if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height: self.matrix[pos[0]][pos[1]] = 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 draw_line(self, start, end, color): """ Draw a line with the given color on the screen. :param start: Start point of the line :param end: End point of the li...
def dist(p, a, b): return (abs((b[0] - a[0]) * (a[1] - p[1]) - (a[0] - p[0]) * (b[1] - a[1])) / math.sqrt((b[0] - a[0])**2 + (b[1] - a[1])**2)) points = [] for x in range(min(start[0], end[0]), max(start[0], end[0]) + 1): for y in range(min(start[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 draw_rect(self, pos, size, color, fillcolor=None): """ Draw a rectangle with the given color on the screen and optionally fill it with fillcolor. :param pos:...
# draw top and botton line for x in range(size[0]): self.draw_dot((pos[0] + x, pos[1]), color) self.draw_dot((pos[0] + x, pos[1] + size[1] - 1), color) # draw left and right side for y in range(size[1]): self.draw_dot((pos[0], pos[1] + y), 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 draw_circle(self, pos, radius, color, fillcolor=None): """ Draw a circle with the given color on the screen and optionally fill it with fillcolor. :param pos...
#TODO: This still produces rubbish but it's on a good way to success def dist(d, p, r): return abs(math.sqrt((p[0] - d[0])**2 + (p[1] - d[1])**2) - r) points = [] for x in range(pos[0] - radius, pos[0] + radius): for y in range(pos[1] - radius, pos[1] + radius):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blit(self, surface, pos=(0, 0)): """ Blits a surface on this surface at pos :param surface: Surface to blit :param pos: Top left point to start blitting :typ...
for x in range(surface.width): for y in range(surface.height): px = x + pos[0] py = y + pos[1] if 0 < px < self.width and 0 < py < self.height: self.matrix[px][py] = surface.matrix[x][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 replace_color(self, before, after): """ Replaces a color on a surface with another one. :param before: Change all pixels with this color :param after: To tha...
#TODO: find out if this actually works #((self.matrix[x][y] = after for y in range(self.height) if self.matrix[x][y] == before) for x in range(self.width)) for x in range(self.width): for y in range(self.height): if self.matrix[x][y] == before: se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_secrets(): """ Call detect-secrets tool """
# use # blah blah = "foo" # pragma: whitelist secret # to ignore a false posites errors_file = "detect-secrets-results.txt" print(execute_get_text("pwd")) command = "{0} detect-secrets --scan --base64-limit 4 --exclude .idea|.js|.min.js|.html|.xsd|" \ "lock.json|synced_folde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mypy(): """ Are types ok? """
if sys.version_info < (3, 4): print("Mypy doesn't work on python < 3.4") return if IS_TRAVIS: command = "{0} -m mypy {1} --ignore-missing-imports --strict".format(PYTHON, PROJECT_NAME).strip() else: command = "{0} mypy {1} --ignore-missing-imports --strict".format(PIPENV, PR...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gemfury(): """ Push to gem fury, a repo with private options """
# fury login # fury push dist/*.gz --as=YOUR_ACCT # fury push dist/*.whl --as=YOUR_ACCT cp = subprocess.run(("fury login --as={0}".format(GEM_FURY).split(" ")), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, check=True) print(cp.stdout)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def needs_label(model_field, field_name): """ Returns `True` if the label based on the model's verbose name is not equal to the default label it would have based...
default_label = field_name.replace('_', ' ').capitalize() return capfirst(model_field.verbose_name) != default_label
<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_relation_kwargs(field_name, relation_info): """ Creates a default instance of a flat relational field. """
model_field, related_model, to_many, to_field, has_through_model = relation_info kwargs = { 'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model) } if to_many: kwargs['many'] = True if to_field: kwargs['to_field'] = to_field ...
<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_api_dict(bases, url, **kwargs): """Create an API dict :param bases: configuration bases :type bases: :class:`~pyextdirect.configuration.Base` or list ...
api = kwargs or {} api.update({'type': 'remoting', 'url': url, 'actions': defaultdict(list), 'enableUrlEncode': 'data'}) if not isinstance(bases, list): bases = [bases] configuration = merge_configurations([b.configuration for b in bases]) for action, methods in configuration.iteritems(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bundle_sequences(element): """ Convert sequence types to bundles This converter automatically constructs a :py:class:`~.Bundle` from any :py:class:`tuple`, :...
if isinstance(element, (tuple, list, set)): return Bundle(element) return NotImplemented
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def css(app, env): """ Add bolditalic CSS. :param app: Sphinx application context. :param env: Sphinx environment context. """
srcdir = os.path.abspath(os.path.dirname(__file__)) cssfile = 'bolditalic.css' csspath = os.path.join(srcdir, cssfile) buildpath = os.path.join(app.outdir, '_static') try: os.makedirs(buildpath) except OSError: if not os.path.isdir(buildpath): raise copy(csspath,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bolditalic(name, rawtext, text, lineno, inliner, options={}, content=[]): """ Add bolditalic role. Returns 2 part tuple containing list of nodes to insert in...
node = nodes.inline(rawtext, text) node.set_class('bolditalic') return [node], []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_getmodule(o): """Attempts to return the module in which `o` is defined. """
from inspect import getmodule try: return getmodule(o) except: # pragma: no cover #There is nothing we can do about this for now. msg.err("_safe_getmodule: {}".format(o), 2) pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_getattr(o): """Gets the attribute from the specified object, taking the acorn decoration into account. """
def getattribute(attr): # pragma: no cover if hasattr(o, "__acornext__") and o.__acornext__ is not None: return o.__acornext__.__getattribute__(attr) elif hasattr(o, "__acorn__") and o.__acorn__ is not None: #Some of the functions have the original function (when it was not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_hasattr(o, attr): """Returns True if `o` has the specified attribute. Takes edge cases into account where packages didn't intend to be used like acorn ...
try: has = hasattr(o, attr) except: # pragma: no cover has = False msg.err("_safe_hasattr: {}.{}".format(o, attr), 2) pass return has
<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_attrs(nobj, oobj, exceptions=None, acornext=False): """Updates the attributes on `nobj` to match those of old, excluding the any attributes in the ex...
success = True if (acornext and hasattr(oobj, "__acornext__") and oobj.__acornext__ is not None): # pragma: no cover target = oobj.__acornext__ else: target = oobj for a, v in _get_members(target): if hasattr(nobj, a): #We don't want to overwrite som...
<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_name_filter(package, context="decorate", reparse=False): """Makes sure that the name filters for the specified package have been loaded. Args: package (...
global name_filters pkey = (package, context) if pkey in name_filters and not reparse: return name_filters[pkey] from acorn.config import settings spack = settings(package) # The acorn.* sections allow for global settings that affect every package # that ever gets wrapped. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_args(*argl, **argd): """Checks the specified argument lists for objects that are trackable. """
args = {"_": []} for item in argl: args["_"].append(_tracker_str(item)) for key, item in argd.items(): args[key] = _tracker_str(item) return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reduced_stack(istart=3, iend=5, ipython=True): """Returns the reduced function call stack that includes only relevant function calls (i.e., ignores any that...
import inspect return [i[istart:iend] for i in inspect.stack() if _decorated_path(i[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 _pre_create(cls, atdepth, stackdepth, *argl, **argd): """Checks whether the the logging should happen based on the specified parameters. If it should, an ini...
from time import time if not atdepth: rstack = _reduced_stack() reduced = len(rstack) if msg.will_print(3): # pragma: no cover sstack = [' | '.join(map(str, r)) for r in rstack] msg.info("{} => stack ({}): {}".format(cls.__fqdn__, len(rstack), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_create(atdepth, entry, result): """Finishes the entry logging if applicable. """
if not atdepth and entry is not None: if result is not None: #We need to get these results a UUID that will be saved so that any #instance methods applied to this object has a parent to refer to. retid = _tracker_str(result) entry["r"] = retid eke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def creationlog(base, package, stackdepth=_def_stackdepth): """Decorator for wrapping the creation of class instances that are being logged by acorn. Args: base:...
@staticmethod def wrapnew(cls, *argl, **argd): global _atdepth_new, _cstack_new, streamlining origstream = None if not (decorating or streamlining): entry, _atdepth_new = _pre_create(cls, _atdepth_new, stackdepth, *argl, **arg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pre_call(atdepth, parent, fqdn, stackdepth, *argl, **argd): """Checks whether the logging should create an entry based on stackdepth. If so, the entry is cr...
from time import time if not atdepth: rstack = _reduced_stack() if "<module>" in rstack[-1]: # pragma: no cover code = rstack[-1][1] else: code = "" reduced = len(rstack) if msg.will_print(3): # pragma: no cover sstack = [' | '.join(m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_call(atdepth, package, fqdn, result, entry, bound, ekey, argl, argd): """Finishes constructing the log and records it to the database. """
from time import time if not atdepth and entry is not None: ek = ekey if result is not None: retid = _tracker_str(result) if result is not None and not bound: ek = retid entry["r"] = None else: entry["r"] = reti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(fqdn, package, result, entry, bound, ekey, *argl, **argd): """Adds logging for the post-call result of calling the method externally. Args: fqdn (str): ...
global _atdepth_call, _cstack_call _cstack_call.pop() if len(_cstack_call) == 0: _atdepth_call = False r = _post_call(_atdepth_call, package, fqdn, result, entry, bound, ekey, argl, argd) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre(fqdn, parent, stackdepth, *argl, **argd): """Adds logging for a call to the specified function that is being handled by an external module. Args: fqdn (s...
global _atdepth_call, _cstack_call #We add +1 to stackdepth because this method had to be called in #addition to the wrapper method, so we would be off by 1. pcres = _pre_call(_atdepth_call, parent, fqdn, stackdepth+1, *argl, **argd) entry, _atdepth_call, reduced, bound, ekey ...
<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_extension(o, otype, fqdn, pmodule): """Creates an extension object to represent `o` that can have attributes set, but which behaves identically to th...
import types xdict = {"__acornext__": o, "__doc__": o.__doc__} if otype == "classes": classname = o.__name__ try: if fqdn in _explicit_subclasses: xclass = eval(_explicit_subclasses[fqdn]) xclass.__acornext__ = o 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 _extend_object(parent, n, o, otype, fqdn): """Extends the specified object if it needs to be extended. The method attempts to add an attribute to the object;...
from inspect import ismodule, isclass pmodule = parent if ismodule(parent) or isclass(parent) else None try: #The __acornext__ attribute references the original, unextended #object; if the object didn't need extended, then __acornext__ is #none. if otype == "methods": ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fqdn(o, oset=True, recheck=False, pmodule=None): """Returns the fully qualified name of the object. Args: o (type): instance of the object's type. oset (bo...
if id(o) in _set_failures or o is None: return None if recheck or not _safe_hasattr(o, "__fqdn__"): import inspect if not hasattr(o, "__name__"): msg.warn("Skipped object {}: no __name__ attribute.".format(o), 3) return result = 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_stack_depth(package, fqdn, defdepth=_def_stackdepth): """Loads the stack depth settings from the config file for the specified package. Args: package (s...
global _stack_config if package not in _stack_config: from acorn.config import settings spack = settings(package) _stack_config[package] = {} secname = "logging.depth" if spack.has_section(secname): for ofqdn in spack.options(secname): _stack...
<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_subclasses(package): """Loads the subclass settings for the specified package so that we can decorate the classes correctly. """
global _explicit_subclasses from acorn.config import settings spack = settings(package) if spack is not None: if spack.has_section("subclass"): _explicit_subclasses.update(dict(spack.items("subclass")))
<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_callwraps(packname, package): """Loads the special call wrapping settings for functions in the specified package. This allows the result of the origina...
global _callwraps from acorn.config import settings from acorn.logging.descriptors import _obj_getattr spack = settings(packname) if spack is not None: if spack.has_section("callwrap"): wrappings = dict(spack.items("callwrap")) for fqdn, target in wrappings.items(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate(package): """Decorates all the methods in the specified package to have logging enabled according to the configuration for the package. """
from os import sep global _decor_count, _decorated_packs, _decorated_o, _pack_paths global decorating if "acorn" not in _decorated_packs: _decorated_packs.append("acorn") packpath = "acorn{}".format(sep) if packpath not in _pack_paths: #We initialize _pack_paths to 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 visit_named_arg(self, _, children): """Named argument of a filter. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: name of the a...
return self.NamedArg( arg=children[0], arg_type=children[2], value=children[4], )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_filter(self, _, children): """A filter, with optional arguments. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: string, n...
return self.Filter( name=children[0], args=children[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 setup_zmq(self): """Set up a PUSH and a PULL socket. The PUSH socket will push out requests to the workers. The PULL socket will receive responses from the w...
self.context = zmq.Context() self.push = self.context.socket(zmq.PUSH) self.push_port = self.push.bind_to_random_port("tcp://%s" % self.host) # start a listener for the pull socket eventlet.spawn(self.zmq_pull) eventlet.sleep(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 start(self, blocking=True): """Start the producer. This will eventually fire the ``server_start`` and ``running`` events in sequence, which signify that the ...
self.setup_zmq() if blocking: self.serve() else: eventlet.spawn(self.serve) # ensure that self.serve runs now as calling code will # expect start() to have started the server even non-blk eventlet.sleep(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 status_icon(self): 'glyphicon for task status; requires bootstrap' icon = self.status_icon_map.get(self.status.lower(), self.unknown_icon) style = self.status_style.get(self.status.lower(), '') return mark_safe( '<span class="glyphi...
<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_trailing_string(content, trailing): """ Strip trailing component `trailing` from `content` if it exists. Used when generating names from view classes....
if content.endswith(trailing) and content != trailing: return content[:-len(trailing)] return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dedent(content): """ Remove leading indent from a block of text. Used when generating descriptions from docstrings. Note that python's `textwrap.dedent` does...
content = force_text(content) whitespace_counts = [len(line) - len(line.lstrip(' ')) for line in content.splitlines()[1:] if line.lstrip()] # unindent the content if needed if whitespace_counts: whitespace_pattern = '^' + (' ' * min(whitespace_counts)) content ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def camelcase_to_spaces(content): """ Translate 'CamelCaseNames' to 'Camel Case Names'. Used when generating names from view classes. """
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))' content = re.sub(camelcase_boundry, ' \\1', content).strip() return ' '.join(content.split('_')).title()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markup_description(description): """ Apply HTML markup to the given description. """
if apply_markdown: description = apply_markdown(description) else: description = escape(description).replace('\n', '<br />') description = '<p>' + description + '</p>' return mark_safe(description)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_class(class_uri): """ Import a class by string 'from.path.module.class' """
parts = class_uri.split('.') class_name = parts.pop() module_uri = '.'.join(parts) try: module = import_module(module_uri) except ImportError as e: # maybe we are still in a module, test going up one level try: module = import_class(module_uri) except 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 class_name_to_instant_name(name): """ This will convert from 'ParentName_ChildName' to 'parent_name.child_name' """
name = name.replace('/', '_') ret = name[0].lower() for i in range(1, len(name)): if name[i] == '_': ret += '.' elif '9' < name[i] < 'a' and name[i - 1] != '_': ret += '_' + name[i].lower() else: ret += name[i].lower() return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def OR(*fns): """ Validate with any of the chainable valdator functions """
if len(fns) < 2: raise TypeError('At least two functions must be passed') @chainable def validator(v): for fn in fns: last = None try: return fn(v) except ValueError as err: last = err if last: raise la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def NOT(fn): """ Reverse the effect of a chainable validator function """
@chainable def validator(v): try: fn(v) except ValueError: return v raise ValueError('invalid') return validator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spec_validator(spec, key=operator.itemgetter): """ Take a spec in dict form, and return a function that validates objects The spec maps each object's key to ...
spec = {k: (key(k), make_chain(v)) for k, v in spec.items()} def validator(obj): errors = {} for k, v in spec.items(): getter, chain = v val = getter(obj) try: chain(val) except ValueError as err: errors[k] = err ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth(self, auth_type, auth_key, project_id=None): """Creates authenticated client. Parameters: * `auth_type` - Authentication type. Use `session` for auth by...
if auth_type == 'session': return SessionAuthClient( auth_header=get_session_http_auth_header(auth_key), host=self.host, port=self.port, secure=self.secure, requests_session=self.requests_session, reques...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getdoc(obj): """ Get object docstring :rtype: str """
inspect_got_doc = inspect.getdoc(obj) if inspect_got_doc in (object.__init__.__doc__, object.__doc__): return '' # We never want this builtin stuff return (inspect_got_doc or '').strip()
<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_callable(obj, of_class = None): """ Get callable for an object and its full name. Supports: * functions * classes (jumps to __init__()) * methods * @cla...
# Cases o = obj if inspect.isclass(obj): try: o = obj.__init__ of_class = obj except AttributeError: pass # Finish return qualname(obj), o, of_class
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _doc_parse(doc, module=None, qualname=None): """ Parse docstring into a dict :rtype: data.FDocstring """
# Build the rex known_tags = { 'param': 'arg', 'type': 'arg-type', 'return': 'ret', 'returns': 'ret', 'rtype': 'ret-type', 'exception': 'exc', 'except': 'exc', 'raise': 'exc', 'raises': 'exc', } tag_rex = re.compile(r'^\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 _argspec(func): """ For a callable, get the full argument spec :type func: Callable :rtype: list[data.ArgumentSpec] """
assert isinstance(func, collections.Callable), 'Argument must be a callable' try: sp = inspect.getargspec(func) if six.PY2 else inspect.getfullargspec(func) except TypeError: # inspect.getargspec() fails for built-in functions return [] # Collect arguments with defaults ret = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doc(obj, of_class=None): """ Get parsed documentation for an object as a dict. This includes arguments spec, as well as the parsed data from the docstring. `...
# Special care about properties if isinstance(obj, property): docstr = doc(obj.fget) # Some hacks for properties docstr.signature = docstr.qsignature= obj.fget.__name__ docstr.args = docstr.args[1:] return docstr # Module module = inspect.getmodule(obj) if m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subclasses(cls, leaves=False): """ List all subclasses of the given class, including itself. If `leaves=True`, only returns classes which have no subclasses ...
stack = [cls] subcls = [] while stack: c = stack.pop() c_subs = c.__subclasses__() stack.extend(c_subs) if not leaves or not c_subs: subcls.append(c) return subcls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(passphrase, trees=['primary']): """Generate a seed for the primary tree of a Gem wallet. You may choose to store the passphrase for a user so the us...
seeds, multi_wallet = MultiWallet.generate(trees, entropy=True) result = {} for tree in trees: result[tree] = dict(private_seed=seeds[tree], public_seed=multi_wallet.public_wif(tree), encrypted_seed=PassphraseBox.encrypt(passphrase, ...
<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(self, name, passphrase=None, wallet_data=None): """Create a new Wallet object and add it to this Wallets collection. This is only available in this li...
if not self.application: raise RoundError("User accounts are limited to one wallet. Make an " "account or shoot us an email <dev@gem.co> if you " "have a compelling use case for more.") if not passphrase and not wallet_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 unlock(self, passphrase, encrypted_seed=None): """Unlock the Wallet by decrypting the primary_private_seed with the supplied passphrase. Once unlocked, the p...
wallet = self.resource if not encrypted_seed: encrypted_seed = wallet.primary_private_seed try: if encrypted_seed['nonce']: primary_seed = NaclPassphraseBox.decrypt( passphrase, encrypted_seed) else: primary...
<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_accounts(self, fetch=False): """Return this Wallet's accounts object, populating it if fetch is True."""
return Accounts(self.resource.accounts, self.client, wallet=self, populate=fetch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def account(self, key=None, address=None, name=None): """Query for an account by key, address, or name."""
if key: return self.client.account(key, wallet=self) if address: q = dict(address=address) elif name: q = dict(name=name) else: raise TypeError("Missing param: key, address, or name is required.") return Account( 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 dump_addresses(self, network, filename=None): """Return a list of address dictionaries for each address in all of the accounts in this wallet of the network ...
addrs = [addr.data for a in self.accounts.values() if a.network == network for addr in a.addresses] if filename: from json import dump with open(filename, 'w') as f: dump(addrs, f) return addrs
<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_subscriptions(self, fetch=False): """Return this Wallet's subscriptions object, populating it if fetch is True."""
return Subscriptions( self.resource.subscriptions, self.client, populate=fetch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signatures(self, transaction): """Sign a transaction. Args: transaction (coinop.Transaction) Returns: A list of signature dicts of the form [ {'primary': 'ba...
# TODO: output.metadata['type']['change'] if not self.multi_wallet: raise DecryptionError("This wallet must be unlocked with " "wallet.unlock(passphrase)") return self.multi_wallet.signatures(transaction)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def map_exception_codes(): '''Helper function to intialise CODES_TO_EXCEPTIONS.''' werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None)) return {e.code: e for _, e in werkex}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def extract_pathvars(callback): '''Extract the path variables from an Resource operation. Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]} ''' mandatory = [] optional = [] # We loop on the signature because the order of the parameters is # important, and signature is...
<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_extra_args(callback, request, kwargs): '''Inject extra arguments from header, body, form.''' # TODO: this is a temporary pach, should be managed via honouring the # mimetype in the request header.... annots = dict(callback.__annotations__) del annots['return'] for param_name, (param_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter_annotations_by_ptype(function, ptype): '''Filter an annotation by only leaving the parameters of type "ptype".''' ret = {} for k, v in function.__annotations__.items(): if k == 'return': continue pt, _ = v if pt == ptype: ret[k] = v return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def option2tuple(opt): """Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int): tup = opt[1], opt[2:] else: tup = opt[0], opt[1:] return tup
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def opt_func(options, check_mandatory=True): """ Restore argument checks for functions that takes options dicts as arguments Functions that take the option dicti...
# A function `my_function` decorated with `opt_func` is replaced by # `opt_func(options)(my_function)`. This is equivalent to # `validate_arguments(my_function)` using the `options` argument provided # to the decorator. A call to `my_function` results in a call to # `opt_func(options)(my_function)(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _default_dict(self): """Return a dictionary with the default for each option."""
options = {} for attr, _, _, default, multi, _ in self._optiondict.values(): if multi and default is None: options[attr] = [] else: options[attr] = default return options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def help(self, args=None, userlevel=9): """Make a string from the option list"""
out = [main.__file__+"\n"] if args is not None: parsed = self.parse(args, ignore_help=True) else: parsed = self._default_dict() for thing in self.options: if type(thing) == str: out.append(" "+thing) elif thing[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 page_list(cls, pages, base_url='/'): """transform a list of page titles in a list of html links"""
plist = [] for page in pages: url = "<a href=\"{}{}\">{}</a>".format(base_url, cls.slugify(page), page) plist.append(url) return plist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slugify(cls, s): """Return the slug version of the string ``s``"""
slug = re.sub("[^0-9a-zA-Z-]", "-", s) return re.sub("-{2,}", "-", slug).strip('-')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_whitelisted(self, addrinfo): """ Returns if a result of ``socket.getaddrinfo`` is in the socket address whitelist. """
# For details about the ``getaddrinfo`` struct, see the Python docs: # http://docs.python.org/library/socket.html#socket.getaddrinfo family, socktype, proto, canonname, sockaddr = addrinfo address, port = sockaddr[:2] return address in self.socket_address_whitelist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report(self): """ Performs rollups, prints report of sockets opened. """
aggregations = dict( (test, Counter().rollup(values)) for test, values in self.socket_warnings.items() ) total = sum( len(warnings) for warnings in self.socket_warnings.values() ) def format_test_statistics(test, counter): ...
<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_all(self): """ Gets all captured counters. :return: a list with counters. """
self._lock.acquire() try: return list(self._cache.values()) finally: self._lock.release()
<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, name, typ): """ Gets a counter specified by its name. It counter does not exist or its type doesn't match the specified type it creates a new one. ...
if name == None or len(name) == 0: raise Exception("Counter name was not set") self._lock.acquire() try: counter = self._cache[name] if name in self._cache else None if counter == None or counter.type != typ: counter = Counter(name, typ) ...
<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(self, filename, **kwargs): """ Parse a file specified with the filename and return an numpy array Parameters filename : string A path of a file Returns ...
with open(filename, 'r') as f: return self.parse(f, **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 _get_thumbnail_filename(filename, append_text="-thumbnail"): """ Returns a thumbnail version of the file name. """
name, ext = os.path.splitext(filename) return ''.join([name, append_text, ext])