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 visit_Compound(self, node): """Visitor for `Compound` AST node."""
self.memory.append_scope() for child in node.children: return_value = self.visit(child) if isinstance(child, ReturnStatement): return return_value if isinstance(child, (IfStatement, WhileStatement)): if return_value is not None: return return_value self.memory.pop_scope()
<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_UnaryOperation(self, node): """Visitor for `UnaryOperation` AST node."""
if node.op.nature == Nature.PLUS: return +self.visit(node.right) elif node.op.nature == Nature.MINUS: return -self.visit(node.right) elif node.op.nature == Nature.NOT: return Bool(not self.visit(node.right))
<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_Boolean(self, node): """Visitor for `Boolean` AST node."""
if node.value == 'true': return Bool(True) elif node.value == 'false': return Bool(False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret(self): """Generic entrypoint of `Interpreter` class."""
self.load_builtins() self.load_functions(self.tree) self.visit(self.tree)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def up(name, debug=False): ''' Create servers and containers as required to meet the configuration specified in _name_. Args: * name: The name of the yaml config file (you can omit the .yml extension for convenience) Example: fab ensemble.up:wordpress ''' if debug: env.ensemble_debug = True filenames_to_try = [ name, '%s.yml' % name, '%s.yaml' % name, ] for filename in filenames_to_try: if os.path.exists(filename): with open(filename, 'r') as f: config = yaml.load(f) break else: abort('Ensemble manifest not found: %s' % name) uncache() try: do_up(config) except exceptions.ConfigException, e: abort('Config error: ' + str(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 stop(name, file=sys.stderr): """ Stop a profiling timer. Arguments: name (str): The name of the timer to stop. If no name is given, stop the global anonymous timer. Returns: bool: Whether or not profiling is enabled. Raises: KeyError: If the named timer does not exist. """
if is_enabled(): elapsed = (time() - __TIMERS[name]) if elapsed > 60: elapsed_str = '{:.1f} m'.format(elapsed / 60) elif elapsed > 1: elapsed_str = '{:.1f} s'.format(elapsed) else: elapsed_str = '{:.1f} ms'.format(elapsed * 1000) del __TIMERS[name] print("[prof]", name, elapsed_str, file=file) return is_enabled()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def profile(fun, *args, **kwargs): """ Profile a function. """
timer_name = kwargs.pop("prof_name", None) if not timer_name: module = inspect.getmodule(fun) c = [module.__name__] parentclass = labtypes.get_class_that_defined_method(fun) if parentclass: c.append(parentclass.__name__) c.append(fun.__name__) timer_name = ".".join(c) start(timer_name) ret = fun(*args, **kwargs) stop(timer_name) 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 geh(m, c): """Error function for hourly traffic flow measures after Geoffrey E. Havers"""
if m + c == 0: return 0 else: return math.sqrt(2 * (m - c) * (m - c) / (m + c))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def avg(self): """return the mean value"""
# XXX rename this method if len(self.values) > 0: return sum(self.values) / float(len(self.values)) else: 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 avg_abs(self): """return the mean of absolute values"""
# XXX rename this method if len(self.values) > 0: return sum(map(abs, self.values)) / float(len(self.values)) else: 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 meanAndStdDev(self, limit=None): """return the mean and the standard deviation optionally limited to the last limit values"""
if limit is None or len(self.values) < limit: limit = len(self.values) if limit > 0: mean = sum(self.values[-limit:]) / float(limit) sumSq = 0. for v in self.values[-limit:]: sumSq += (v - mean) * (v - mean) return mean, math.sqrt(sumSq / limit) else: 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 relStdDev(self, limit=None): """return the relative standard deviation optionally limited to the last limit values"""
moments = self.meanAndStdDev(limit) if moments is None: return None return moments[1] / moments[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 mean(self): """return the median value"""
# XXX rename this method if len(self.values) > 0: return sorted(self.values)[len(self.values) / 2] else: 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 mean_abs(self): """return the median of absolute values"""
# XXX rename this method if len(self.values) > 0: return sorted(map(abs, self.values))[len(self.values) / 2] else: 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 copy_resources_to_log_dir(log_dir): """Copies the necessary static assets to the log_dir and returns the path of the main css file."""
css_path = resource_filename(Requirement.parse("egat"), "/egat/data/default.css") header_path = resource_filename(Requirement.parse("egat"), "/egat/data/egat_header.png") shutil.copyfile(css_path, log_dir + "/style.css") shutil.copyfile(header_path, log_dir + "/egat_header.png") return log_dir + os.sep + "style.css"
<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_queue(queue): """ Empties all pending items in a queue and returns them in a list. """
result = [] try: while True: item = queue.get_nowait() result.append(item) except: Empty return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(command, cwd=os.path.curdir, **options): """ Run the system command with optional options. Args: * command: system command. * cwd: current working directory. * verbose: direct options for :func:`subprocess.Popen`. Returns: Opened process, standard output & error. """
process = subprocess.Popen(shlex.split(command), cwd=cwd, **options) stdout, stderr = process.communicate() return process, stdout, stderr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self, copy=False): """Convert the struct to a dictionary. If `copy == True`, returns a deep copy of the values. """
new_dict = {} for attr, value in self: if copy: value = deepcopy(value) new_dict[attr] = value return new_dict
<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): """Start the process, essentially forks and calls target function."""
logger.info("starting process") process = os.fork() time.sleep(0.01) if process != 0: logger.debug('starting child watcher') self.loop.reset() self.child_pid = process self.watcher = pyev.Child(self.child_pid, False, self.loop, self._child) self.watcher.start() else: self.loop.reset() logger.debug('running main function') self.run(*self.args, **self.kwargs) logger.debug('quitting') sys.exit(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 setup(settings): """ Setup the database connection. """
connector = settings.get('db_connector') if connector == 'postgres': from playhouse.pool import PooledPostgresqlExtDatabase return PooledPostgresqlExtDatabase(settings['db_name'], user=settings['db_user'], password=settings['db_password'], host=settings['db_host'], port=settings.get('db_port'), max_connections=settings.get('db_max_conn'), stale_timeout=settings.get('db_stale_timeout'), timeout=settings.get('db_timeout'), register_hstore=False)
<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(module, db): """ Initialize the models. """
for model in farine.discovery.import_models(module): model._meta.database = db
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self, extras=None): """ Convert a model into a json using the playhouse shortcut. """
extras = extras or {} to_dict = model_to_dict(self) to_dict.update(extras) return json.dumps(to_dict, cls=sel.serializers.JsonEncoder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lazy(func): """ Decorator, which can be used for lazy imports @lazy def yaml(): import yaml return yaml """
try: frame = sys._getframe(1) except Exception: _locals = None else: _locals = frame.f_locals func_name = func.func_name if six.PY2 else func.__name__ return LazyStub(func_name, func, _locals)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_reftrack(self, reftrack): """Add a reftrack object to the root. This will not handle row insertion in the model! It is automatically done when setting the parent of the :class:`Reftrack` object. :param reftrack: the reftrack object to add :type reftrack: :class:`Reftrack` :returns: None :rtype: None :raises: None """
self._reftracks.add(reftrack) refobj = reftrack.get_refobj() if refobj: self._parentsearchdict[refobj] = reftrack
<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_reftrack(self, reftrack): """Remove the reftrack from the root. This will not handle row deletion in the model! It is automatically done when calling :meth:`Reftrack.delete`. :param reftrack: the reftrack object to remove :type reftrack: :class:`Reftrack` :returns: None :rtype: None :raises: None """
self._reftracks.remove(reftrack) refobj = reftrack.get_refobj() if refobj and refobj in self._parentsearchdict: del self._parentsearchdict[refobj]
<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_refobj(self, old, new, reftrack): """Update the parent search dict so that the reftrack can be found with the new refobj and delete the entry for the old refobj. Old or new can also be None. :param old: the old refobj of reftrack :param new: the new refobj of reftrack :param reftrack: The reftrack, which refobj was updated :type reftrack: :class:`Reftrack` :returns: None :rtype: None :raises: None """
if old: del self._parentsearchdict[old] if new: self._parentsearchdict[new] = reftrack
<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_scene_suggestions(self, refobjinter): """Return a list of suggested Reftracks for the current scene, that are not already in this root. A suggestion is a combination of type and element. :param refobjinter: a programm specific reftrack object interface :type refobjinter: :class:`RefobjInterface` :returns: A list of suggestions :rtype: :class:`list` :raises: None """
sugs = [] cur = refobjinter.get_current_element() if not cur: return sugs for typ in refobjinter.types: inter = refobjinter.get_typ_interface(typ) elements = inter.get_scene_suggestions(cur) for e in elements: for r in self._reftracks: if not r.get_parent() and typ == r.get_typ() and e == r.get_element(): break else: sugs.append((typ, e)) return sugs
<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_unwrapped(self, root, refobjinter): """Return a set with all refobjects in the scene that are not in already wrapped in root. :param root: the root that groups all reftracks and makes it possible to search for parents :type root: :class:`ReftrackRoot` :param refobjinter: a programm specific reftrack object interface :type refobjinter: :class:`RefobjInterface` :returns: a set with unwrapped refobjects :rtype: set :raises: None """
all_refobjs = set(refobjinter.get_all_refobjs()) wrapped = set(root._parentsearchdict.keys()) return all_refobjs - 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 set_refobj(self, refobj, setParent=True): """Set the reftrack object. The reftrack object interface will determine typ, element, taskfileinfo, status and parent and set these values. If the reftrack object is None, the :class:`Reftrack` object will keep the initial typ, element but will loose it\'s parent, status and taskfileinfo :param refobj: a reftrack object or None :type refobj: None | reftrack object :param setParent: If True, set also the parent :type setParent: :class:`bool` :returns: None :rtype: None :raises: None """
root = self.get_root() old = self._refobj self._refobj = refobj refobjinter = self.get_refobjinter() if self._refobj: self.set_typ(refobjinter.get_typ(self._refobj)) self.set_taskfileinfo(refobjinter.get_taskfileinfo(self._refobj)) self.set_element(refobjinter.get_element(self._refobj)) if setParent: parentrefobj = refobjinter.get_parent(self._refobj) parentreftrack = root.get_reftrack(parentrefobj) self.set_parent(parentreftrack) self.set_status(refobjinter.get_status(self._refobj)) else: self.set_taskfileinfo(None) if setParent: self.set_parent(None) self.set_status(None) root.update_refobj(old, refobj, self) self.fetch_uptodate()
<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_typ(self, typ): """Set the type of the entity Make sure the type is registered in the :class:`RefobjInterface`. :param typ: the type of the entity :type typ: str :returns: None :rtype: None :raises: ValueError """
if typ not in self._refobjinter.types: raise ValueError("The given typ is not supported by RefobjInterface. Given %s, supported: %s" % (typ, self._refobjinter.types.keys())) self._typ = typ self._typicon = self.get_refobjinter().get_typ_icon(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 set_parent(self, parent): """Set the parent reftrack object If a parent gets deleted, the children will be deleted too. .. Note:: Once the parent is set, it cannot be set again! :param parent: the parent reftrack object :type parent: :class:`Reftrack` | None :returns: None :rtype: None :raises: AssertionError """
assert self._parent is None or self._parent is parent,\ "Cannot change the parent. Can only set from None." if parent and self._parent is parent: return self._parent = parent if parent: refobjinter = self.get_refobjinter() refobj = self.get_refobj() # set the parent of the refobj only if it is not already set # and only if there is one! oO if refobj and not refobjinter.get_parent(refobj): refobjinter.set_parent(refobj, parent.get_refobj()) # add to parent self._parent.add_child(self) if not self.get_refobj(): self.set_id(self.fetch_new_id()) pitem = self._parent._treeitem if self._parent else self.get_root().get_rootitem() self._treeitem.set_parent(pitem) self.fetch_alien()
<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_id(self, identifier): """Set the id of the given reftrack This will set the id on the refobject :param identifier: the identifier number :type identifier: int :returns: None :rtype: None :raises: None """
self._id = identifier refobj = self.get_refobj() if refobj: self.get_refobjinter().set_id(refobj, identifier)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_new_id(self, ): """Return a new id for the given reftrack to be set on the refobject The id can identify reftracks that share the same parent, type and element. :returns: A new id :rtype: int :raises: None """
parent = self.get_parent() if parent: others = parent._children else: others = [r for r in self.get_root()._reftracks if r.get_parent() is None] others = [r for r in others if r != self and r.get_typ() == self.get_typ() and r.get_element() == self.get_element()] highest = -1 for r in others: identifier = r.get_id() if identifier > highest: highest = identifier return highest + 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 create_treeitem(self, ): """Create a new treeitem for this reftrack instance. .. Note:: Parent should be set, Parent should already have a treeitem. If there is no parent, the root tree item is used as parent for the treeitem. :returns: a new treeitem that contains a itemdata with the reftrack instanec. :rtype: :class:`TreeItem` :raises: None """
p = self.get_parent() root = self.get_root() if p: pitem = p.get_treeitem() else: pitem = root.get_rootitem() idata = root.create_itemdata(self) item = TreeItem(idata, parent=pitem) return item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_options(self, ): """Set and return the options for possible files to load, replace etc. The stored element will determine the options. The refobjinterface and typinterface are responsible for providing the options :returns: the options :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """
self._options, self._taskfileinfo_options = self.get_refobjinter().fetch_options(self.get_typ(), self.get_element()) return self._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 fetch_uptodate(self, ): """Set and return whether the currently loaded entity is the newest version in the department. :returns: True, if newest version. False, if there is a newer version. None, if there is nothing loaded yet. :rtype: bool | None :raises: None """
tfi = self.get_taskfileinfo() if tfi: self._uptodate = tfi.is_latest() else: self._uptodate = None return self._uptodate
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_alien(self, ): """Set and return, if the reftrack element is linked to the current scene. Askes the refobj interface for the current scene. If there is no current scene then True is returned. :returns: whether the element is linked to the current scene :rtype: bool :raises: None """
parent = self.get_parent() if parent: parentelement = parent.get_element() else: parentelement = self.get_refobjinter().get_current_element() if not parentelement: self._alien = True return self._alien element = self.get_element() if element == parentelement: self._alien = False # test if it is the element is a global shot # first test if we have a shot # then test if it is in a global sequence. then the shot is global too. # test if the parent element is a shot, if they share the sequence, and element is global elif isinstance(element, djadapter.models.Shot)\ and (element.sequence.name == djadapter.GLOBAL_NAME\ or (isinstance(parentelement, djadapter.models.Shot)\ and parentelement.sequence == element.sequence and element.name == djadapter.GLOBAL_NAME)): self._alien = False else: assets = parentelement.assets.all() self._alien = element not in assets return self._alien
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reference(self, taskfileinfo): """Reference the entity into the scene. Only possible if the current status is None. This will create a new refobject, then call :meth:`RefobjInterface.reference` and afterwards set the refobj on the :class:`Reftrack` instance. :param taskfileinfo: the taskfileinfo to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """
assert self.status() is None,\ "Can only reference, if the entity is not already referenced/imported. Use replace instead." refobj = self.create_refobject() with self.set_parent_on_new(refobj): self.get_refobjinter().reference(taskfileinfo, refobj) self.set_refobj(refobj) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
<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, ): """If the reference is in the scene but unloaded, load it. .. Note:: Do not confuse this with reference or import. Load means that it is already referenced. But the data from the reference was not read until now. Load loads the data from the reference. This will call :meth:`RefobjInterface.load` and set the status to :data:`Reftrack.LOADED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """
assert self.status() == self.UNLOADED,\ "Cannot load if there is no unloaded reference. Use reference instead." self.get_refobjinter().load(self._refobj) self.set_status(self.LOADED) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unload(self, ): """If the reference is loaded, unload it. .. Note:: Do not confuse this with a delete. This means, that the reference stays in the scene, but no data is read from the reference. This will call :meth:`RefobjInterface.unload` and set the status to :data:`Reftrack.UNLOADED`. It will also throw away all children :class:`Reftrack`. They will return after :meth:`Reftrack.load`. The problem might be that children depend on their parent, but will not get unloaded. E.g. you imported a child. It will stay in the scene after the unload and become an orphan. In this case an error is raised. It is not possible to unload such an entity. The orphan might get its parents back after you call load, but it will introduce bugs when wrapping children of unloaded entities. So we simply disable the feature in that case and raise an :class:`IntegrityError` :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """
assert self.status() == self.LOADED,\ "Cannot unload if there is no loaded reference. \ Use delete if you want to get rid of a reference or import." childrentodelete = self.get_children_to_delete() if childrentodelete: raise ReftrackIntegrityError("Cannot unload because children of the reference would become orphans.", childrentodelete) self.get_refobjinter().unload(self._refobj) self.set_status(self.UNLOADED) self.throw_children_away() self.update_restrictions() self.emit_data_changed()
<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_file(self, taskfileinfo): """Import the file for the given taskfileinfo This will also update the status to :data:`Reftrack.IMPORTED`. This will also call :meth:`fetch_new_children`. Because after the import, we might have new children. :param taskfileinfo: the taskfileinfo to import. If None is given, try to import the current reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` | None :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """
assert self.status() is None,\ "Entity is already in scene. Use replace instead." refobjinter = self.get_refobjinter() refobj = self.create_refobject() with self.set_parent_on_new(refobj): refobjinter.import_taskfile(refobj, taskfileinfo) self.set_refobj(refobj) self.set_status(self.IMPORTED) self.fetch_new_children() self.update_restrictions() self.emit_data_changed()
<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_reference(self, ): """Import the currently loaded reference This will also update the status to :data:`Reftrack.IMPORTED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """
assert self.status() in (self.LOADED, self.UNLOADED),\ "There is no reference for this entity." refobjinter = self.get_refobjinter() refobjinter.import_reference(self.get_refobj()) self.set_status(self.IMPORTED) self.update_restrictions() for c in self.get_all_children(): c.update_restrictions() self.emit_data_changed()
<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(self, taskfileinfo): """Replace the current reference or imported entity. If the given refobj is not replaceable, e.g. it might be imported or it is not possible to switch the data, then the entity will be deleted, then referenced or imported again, depending on the current status. A replaced entity might have other children. This introduces a problem: A child might get deleted, e.g. an asset which itself has another child, that will not get deleted, e.g. an imported shader. In this case the imported shader will be left as an orphan. This will check all children that will not be deleted (:meth:`Reftrack.get_children_to_delete`) and checks if they are orphans after the replace. If they are, they will get deleted! After the replace, all children will be reset. This will simply throw away all children reftracks (the content will not be deleted) and wrap all new children again. See: :meth:`Reftrack.fetch_new_children`. :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: ReftrackIntegrityError """
assert self.status() is not None,\ "Can only replace entities that are already in the scene." refobjinter = self.get_refobjinter() refobj = self.get_refobj() if self.status() in (self.LOADED, self.UNLOADED) and refobjinter.is_replaceable(refobj): # possible orphans will not get replaced, by replace # but their parent might dissapear in the process possibleorphans = self.get_children_to_delete() with self.set_parent_on_new(refobj): refobjinter.replace(refobj, taskfileinfo) self.set_taskfileinfo(taskfileinfo) self.fetch_uptodate() for o in possibleorphans: # find if orphans were created and delete them # we get the refobj of the parent # if it still exists, it is no orphan parent = o.get_parent() refobj = parent.get_refobj() if not parent.get_refobjinter().exists(refobj): # orphans will be deleted! # this is politically incorrect, i know! # the world of programming is a harsh place. o.delete() # reset the children # throw them away at first self.throw_children_away() # gather them again self.fetch_new_children() else: status = self.status() self.delete(removealien=False) if status == self.IMPORTED: self.import_file(taskfileinfo) else: self.reference(taskfileinfo) self.update_restrictions() self.emit_data_changed()
<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(self, ): """Internal implementation for deleting a reftrack. This will just delete the reftrack, set the children to None, update the status, and the rootobject. If the object is an alien, it will also set the parent to None, so it dissapears from the model. :returns: None :rtype: None :raises: None """
refobjinter = self.get_refobjinter() refobjinter.delete(self.get_refobj()) self.set_refobj(None, setParent=False) if self.alien(): # it should not be in the scene # so also remove it from the model # so we cannot load it again parent = self.get_parent() if parent: parent.remove_child(self) self._treeitem.parent().remove_child(self._treeitem) else: # only remove all children from the model and set their parent to None for c in self.get_all_children(): c._parent = None self._treeitem.remove_child(c._treeitem) # this should not have any children anymore self._children = [] self.set_status(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_all_children(self): """Get all children including children of children :returns: all children including children of children :rtype: list of :class:`Reftrack` :raises: None """
children = self._children[:] oldlen = 0 newlen = len(children) while oldlen != newlen: start = oldlen oldlen = len(children) for i in range(start, len(children)): children.extend(children[i]._children) newlen = len(children) return children
<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_children_to_delete(self): """Return all children that are not referenced :returns: list or :class:`Reftrack` :rtype: list :raises: None """
refobjinter = self.get_refobjinter() children = self.get_all_children() todelete = [] for c in children: if c.status() is None: # if child is not in scene we do not have to delete it continue rby = refobjinter.referenced_by(c.get_refobj()) if rby is None: # child is not part of another reference. # we have to delete it for sure todelete.append(c) continue # check if child is referenced by any parent up to self # if it is not referenced by any refrence of a parent, then we # can assume it is referenced by a parent of a greater scope, # e.g. the parent of self. because we do not delete anything above self # we would have to delete the child manually parent = c.get_parent() while parent != self.get_parent(): if refobjinter.get_reference(parent.get_refobj()) == rby: # is referenced by a parent so it will get delted when the parent is deleted. break parent = parent.get_parent() else: todelete.append(c) return todelete
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_new_children(self, ): """Collect all new children and add the suggestions to the children as well When an entity is loaded, referenced, imported etc there might be new children. Also it might want to suggest children itself, like a Shader for an asset. First we wrap all unwrapped children. See: :meth:`Reftrack.get_unwrapped`, :meth:`Reftrack.wrap`. Then we get the suggestions. See: :meth:`Reftrack.get_suggestions`. All suggestions that are not already a child of this Reftrack instance, will be used to create a new Reftrack with the type and element of the suggestion and the this instance as parent. :returns: None :rtype: None :raises: None """
root = self.get_root() refobjinter = self.get_refobjinter() unwrapped = self.get_unwrapped(root, refobjinter) self.wrap(self.get_root(), self.get_refobjinter(), unwrapped) suggestions = self.get_suggestions() for typ, element in suggestions: for c in self._children: if typ == c.get_typ() and element == c.get_element(): break else: Reftrack(root=root, refobjinter=refobjinter, typ=typ, element=element, parent=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 set_parent_on_new(self, parentrefobj): """Contextmanager that on close will get all new unwrapped refobjects, and for every refobject with no parent sets is to the given one. :returns: None :rtype: None :raises: None """
refobjinter = self.get_refobjinter() # to make sure we only get the new one # we get all current unwrapped first old = self.get_unwrapped(self.get_root(), refobjinter) yield new = self.get_unwrapped(self.get_root(), refobjinter) - old for refobj in new: if refobjinter.get_parent(refobj) is None: refobjinter.set_parent(refobj, parentrefobj)
<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_restricted(self, obj, restricted): """Set the restriction on the given object. You can use this to signal that a certain function is restricted. Then you can query the restriction later with :meth:`Reftrack.is_restricted`. :param obj: a hashable object :param restricted: True, if you want to restrict the object. :type restricted: :class:`bool` :returns: None :rtype: None :raises: None """
if restricted: self._restricted.add(obj) elif obj in self._restricted: self._restricted.remove(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_reference_restriction(self, ): """Fetch whether referencing is restricted :returns: True, if referencing is restricted :rtype: :class:`bool` :raises: None """
inter = self.get_refobjinter() restricted = self.status() is not None return restricted or inter.fetch_action_restriction(self, 'reference')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_load_restriction(self, ): """Fetch whether loading is restricted :returns: True, if loading is restricted :rtype: :class:`bool` :raises: None """
inter = self.get_refobjinter() restricted = self.status() != self.UNLOADED return restricted or inter.fetch_action_restriction(self, 'load')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_import_ref_restriction(self,): """Fetch whether importing the reference is restricted :returns: True, if importing the reference is restricted :rtype: :class:`bool` :raises: None """
inter = self.get_refobjinter() restricted = self.status() not in (self.LOADED, self.UNLOADED) return restricted or inter.fetch_action_restriction(self, 'import_reference')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_import_f_restriction(self,): """Fetch whether importing a file is restricted :returns: True, if import is restricted :rtype: :class:`bool` :raises: None """
inter = self.get_refobjinter() restricted = self.status() is not None return restricted or inter.fetch_action_restriction(self, 'import_taskfile')
<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_data_changed(self): """Emit the data changed signal on the model of the treeitem if the treeitem has a model. :returns: None :rtype: None :raises: None """
item = self.get_treeitem() m = item.get_model() if m: start = m.index_of_item(item) parent = start.parent() end = m.index(start.row(), item.column_count()-1, parent) m.dataChanged.emit(start, 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 create(self, typ, identifier, parent=None): """Create a new refobj with the given typ and parent :param typ: the entity type :type typ: str :param identifier: the refobj id. Used to identify refobjects of the same parent, element and type in the UI :type identifier: int :param parent: the parent refobject :type parent: refobj :returns: The created refobj :rtype: refobj :raises: None """
refobj = self.create_refobj() self.set_typ(refobj, typ) self.set_id(refobj, identifier) if parent: self.set_parent(refobj, parent) return refobj
<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(self, refobj): """Delete the given refobj and the contents of the entity :param refobj: the refobj to delete :type refobj: refobj :returns: None :rtype: None :raises: None """
i = self.get_typ_interface(self.get_typ(refobj)) i.delete(refobj) self.delete_refobj(refobj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reference(self, taskfileinfo, refobj): """Reference the given taskfile info and set the created reference on the refobj This will call :meth:`ReftypeInterface.reference`, then :meth:`ReftypeInterface.set_reference`. :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :param refobj: the refobj that should represent the new reference :type refobj: refobj :returns: None :rtype: None :raises: None """
inter = self.get_typ_interface(self.get_typ(refobj)) ref = inter.reference(refobj, taskfileinfo) self.set_reference(refobj, ref)
<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(self, refobj, taskfileinfo): """Replace the given refobjs reference with the taskfileinfo This will call :meth:`ReftypeInterface.replace`. :param refobj: the refobject :type refobj: refobj :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """
inter = self.get_typ_interface(self.get_typ(refobj)) ref = self.get_reference(refobj) inter.replace(refobj, ref, taskfileinfo)
<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_replaceable(self, refobj): """Return whether the given reference of the refobject is replaceable or if it should just get deleted and loaded again. This will call :meth:`ReftypeInterface.is_replaceable`. :param refobj: the refobject to query :type refobj: refobj :returns: True, if replaceable :rtype: bool :raises: None """
inter = self.get_typ_interface(self.get_typ(refobj)) return inter.is_replaceable(refobj)
<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_reference(self, refobj): """Import the reference of the given refobj Here we assume, that the reference is already in the scene and we break the encapsulation and pull the data from the reference into the current scene. This will call :meth:`ReftypeInterface.import_reference` and set the reference on the refobj to None. :param refobj: the refobj with a reference :type refobj: refobj :returns: None :rtype: None :raises: None """
inter = self.get_typ_interface(self.get_typ(refobj)) ref = self.get_reference(refobj) inter.import_reference(refobj, ref) self.set_reference(refobj, 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_element(self, refobj): """Return the element the refobj represents. The element is either an Asset or a Shot. :param refobj: the refobject to query :type refobj: refobj :returns: The element the reftrack represents :rtype: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :raises: None """
tf = self.get_taskfile(refobj) return tf.task.element
<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_option_labels(self, typ, element): """Return labels for each level of the option model. The options returned by :meth:`RefobjInterface.fetch_options` is a treemodel with ``n`` levels. Each level should get a label to describe what is displays. E.g. if you organize your options, so that the first level shows the tasks, the second level shows the descriptors and the third one shows the versions, then your labels should be: ``["Task", "Descriptor", "Version"]``. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for which the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: label strings for all levels :rtype: list :raises: None """
inter = self.get_typ_interface(typ) return inter.get_option_labels(element)
<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_option_columns(self, typ, element): """Return the column of the model to show for each level Because each level might be displayed in a combobox. So you might want to provide the column to show. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str :param element: The element for wich the options should be fetched. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of columns :rtype: list :raises: None """
inter = self.get_typ_interface(typ) return inter.get_option_columns(element)
<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_suggestions(self, reftrack): """Return a list with possible children for this reftrack Each Reftrack may want different children. E.g. a Asset wants to suggest a shader for itself and all assets that are linked in to it in the database. Suggestions only apply for enities with status other than None. A suggestion is a tuple of typ and element. It will be used to create a newlen :class:`Reftrack`. The parent will be this instance, root and interface will of course be the same. This will delegate the call to the appropriate :class:`ReftypeInterface`. So suggestions may vary for every typ and might depend on the status of the reftrack. :param reftrack: the reftrack which needs suggestions :type reftrack: :class:`Reftrack` :returns: list of suggestions, tuples of type and element. :rtype: list :raises: None """
inter = self.get_typ_interface(reftrack.get_typ()) return inter.get_suggestions(reftrack)
<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_available_types_for_scene(self, element): """Return a list of types that can be used in combination with the given element to add new reftracks to the scene. This allows for example the user, to add new reftracks (aliens) to the scene. So e.g. for a shader, it wouldn't make sense to make it available to be added to the scene, because one would use them only as children of let's say an asset or cache. Some types might only be available for shots or assets etc. :param element: the element that could be used in conjuction with the returned types to create new reftracks. :type element: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` :returns: a list of types :rtype: :class:`list` :raises: None """
available = [] for typ, inter in self.types.items(): if inter(self).is_available_for_scene(element): available.append(typ) return available
<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_process_call(self, name="Unknown", endpoint_params=None): """ This is called by the method_decorator within the Endpoint. The point is to capture a slot for the endpoint.method to put it's final _calls. It also allows for some special new arguments that will be extracted before the endpoint is called :param name: str of the name of the endpoint calling function :param endpoint_params: dict of the arguments passed to the endpoint method """
call_temps = self._call_temps.get(self._get_thread_id(), None) call_params = call_temps and call_temps.pop() or {} default_params = dict(name=name, label='ID_' + str(self._count), base_uri=self.base_uri, timeout=self.timeout, headers={}, cookies={}, proxies=self.proxies, accepted_return=self.accepted_return or 'json') for k, v in default_params.items(): if call_params.get(k, None) is None: call_params[k] = v sub_base_uri = call_params.pop('sub_base_uri', None) if sub_base_uri: call_params['base_uri'] = self.clean_base_uri(sub_base_uri) endpoint_params = endpoint_params or {} for k, v in (call_temps and call_temps.pop().items() or []): if v is not None and k not in endpoint_params: endpoint_params.setdefault(k, v) for k, v in self.cookies.items(): call_params['cookies'].setdefault(k, v) for k, v in self.headers.items(): call_params['headers'].setdefault(k, v) api_call = self.ApiCall(**call_params) self._call_queue.setdefault(self._get_thread_id(), []).append(api_call) if self.max_history is not 0: self._count += 1 # count of _calls if len(self) > self.max_history: self._calls.popitem(0) self._calls[call_params['label']] = api_call return api_call
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def function(fname): """ Make a function to Function class """
def _f(func): class WrapFunction(Function): name = fname def __call__(self, *args, **kwargs): return func(*args, **kwargs) return WrapFunction return _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 parse_cookie(header, charset='utf-8', errors='ignore'): """Parse a cookie. :param header: the header to be used to parse the cookie. :param charset: the charset for the cookie values. :param errors: the error behavior for the charset decoding. """
cookie = _ExtendedCookie() if header: cookie.load(header) result = {} # decode to unicode and skip broken items. Our extended morsel # and extended cookie will catch CookieErrors and convert them to # `None` items which we have to skip here. for key, value in cookie.iteritems(): if value.value is not None: result[key] = unquote_header_value(value.value) \ .decode(charset, errors) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equals_as(self, value_type, other): """ Compares this object value to specified specified value. When direct comparison gives negative results it converts values to type specified by type code and compare them again. :param value_type: the Typecode type that defined the type of the result :param other: the value to be compared with. :return: true when objects are equal and false otherwise. """
if other == None and self.value == None: return True if other == None or self.value == None: return False if isinstance(other, AnyValue): other = other._value if other == self.value: return True value1 = TypeConverter.to_type(value_type, self.value) value2 = TypeConverter.to_type(value_type, other) if value1 == None or value2 == None: return False return value1 == value2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _collect_images(self, content: str, md_file_path: Path) -> str: '''Find images outside the source directory, copy them into the source directory, and replace the paths in the source. This is necessary because MkDocs can't deal with images outside the project's doc_dir. :param content: Markdown content :param md_file_path: Path to the Markdown file with content ``content`` :returns: Markdown content with image paths pointing within the source directory ''' self.logger.debug(f'Looking for images in {md_file_path}.') def _sub(image): image_caption = image.group('caption') image_path = (md_file_path.parent / Path(image.group('path'))).resolve() self.logger.debug(f'Detected image: caption="{image_caption}", path={image_path}') if self.working_dir.resolve() not in image_path.parents: self.logger.debug('Image outside source directory.') self._collected_imgs_path.mkdir(exist_ok=True) collected_img_path = ( self._collected_imgs_path/f'{image_path.stem}_{str(uuid1())}' ).with_suffix(image_path.suffix) copy(image_path, collected_img_path) self.logger.debug(f'Image copied to {collected_img_path}') rel_img_path = Path(relpath(collected_img_path, md_file_path.parent)).as_posix() else: self.logger.debug('Image inside source directory.') rel_img_path = Path(relpath(image_path, md_file_path.parent)).as_posix() img_ref = f'![{image_caption}]({rel_img_path})' self.logger.debug(f'Replacing with: {img_ref}') return img_ref return self._image_pattern.sub(_sub, 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 has_prop_attribute(cls, prop_name): # @NoSelf """This methods returns True if there exists a class attribute for the given property. The attribute is searched locally only"""
return (prop_name in cls.__dict__ and not isinstance(cls.__dict__[prop_name], types.FunctionType))
<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_value_change(cls, old, new): # @NoSelf """Checks whether the value of the property changed in type or if the instance has been changed to a different instance. If true, a call to model._reset_property_notification should be called in order to re-register the new property instance or type"""
return (type(old) != type(new) or isinstance(old, wrappers.ObsWrapperBase) and old != new)
<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_getter(cls, prop_name, # @NoSelf user_getter=None, getter_takes_name=False): """Returns a function wich is a getter for a property. prop_name is the name off the property. user_getter is an optional function doing the work. If specified, that function will be called instead of getting the attribute whose name is in 'prop_name'. If user_getter is specified with a False value for getter_takes_name (default), than the method is used to get the value of the property. If True is specified for getter_takes_name, then the user_getter is called by passing the property name (i.e. it is considered a general method which receive the property name whose value has to be returned.) """
if user_getter: if getter_takes_name: # wraps the property name _deps = type(cls)._get_old_style_getter_deps(cls, prop_name, user_getter) def _getter(self, deps=_deps): return user_getter(self, prop_name) else: _getter = user_getter return _getter def _getter(self): # @DuplicatedSignature return getattr(self, PROP_NAME % {'prop_name' : prop_name}) return _getter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=25): ''' Run a cone search of the GALEX archive ''' self.magnitudelimit = magnitudelimit # run the query self.speak('querying GALEX, centered on {} with radius {}'.format(center, radius, magnitudelimit)) coordinatetosearch = '{0.ra.deg} {0.dec.deg}'.format(center) table = astroquery.mast.Catalogs.query_region(coordinates=center, radius=radius, catalog='GALEX') # the gaia DR2 epoch is 2015.5 epoch = 2005#??? # create skycoord objects self.coordinates = coord.SkyCoord( ra=table['ra'].data*u.deg, dec=table['dec'].data*u.deg, obstime=Time(epoch, format='decimalyear')) self.magnitudes = dict(NUV=table['nuv_mag'].data, FUV=table['fuv_mag'].data) self.magnitude = self.magnitudes['NUV']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True): """Upload Nginx site configuration from a template."""
template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf'] site_available = u'/etc/nginx/sites-available/%s' % site_name upload_template(template_name, site_available, context=context, use_sudo=True) if enable: enable_site(site_name)
<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_site(site_name): """Enable an available Nginx site."""
site_available = u'/etc/nginx/sites-available/%s' % site_name site_enabled = u'/etc/nginx/sites-enabled/%s' % site_name if files.exists(site_available): sudo(u'ln -s -f %s %s' % (site_available, site_enabled)) restart_service(u'nginx') else: abort(u'%s site configuration is not available' % site_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_site(site_name): """Disables Nginx site configuration."""
site = u'/etc/nginx/sites-enabled/%s' % site_name if files.exists(site): sudo(u'rm %s' % site) restart_service(u'nginx')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def suppressConsoleOut(meth): """Disable console output during the method is run."""
@wraps(meth) def decorate(*args, **kwargs): """Decorate""" # Disable ansible console output _stdout = sys.stdout fptr = open(os.devnull, 'w') sys.stdout = fptr try: return meth(*args, **kwargs) except Exception as e: raise e finally: # Enable console output sys.stdout = _stdout return decorate
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mount(cls, mount_point, lower_dir, upper_dir, mount_table=None): """Execute the mount. This requires root"""
ensure_directories(mount_point, lower_dir, upper_dir) # Load the mount table if it isn't given if not mount_table: mount_table = MountTable.load() # Check if the mount_point is in use if mount_table.is_mounted(mount_point): # Throw an error if it is raise AlreadyMounted() # Build mount options options = "rw,lowerdir=%s,upperdir=%s" % (lower_dir, upper_dir) # Run the actual mount subwrap.run(['mount', '-t', 'overlayfs', '-o', options, 'olyfs%s' % random_name(), mount_point]) return cls(mount_point, lower_dir, upper_dir)
<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_opened(components): """ Checks if all components are opened. To be checked components must implement [[IOpenable]] interface. If they don't the call to this method returns true. :param components: a list of components that are to be checked. :return: true if all components are opened and false if at least one component is closed. """
if components == None: return True result = True for component in components: result = result and Opener.is_opened_one(component) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(correlation_id, components): """ Opens multiple components. To be opened components must implement [[IOpenable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be closed. """
if components == None: return for component in components: Opener.open_one(correlation_id, component)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_temperature(self): """Gets the compensated temperature in degrees celsius."""
UT = self.read_raw_temp() # Datasheet value for debugging: #UT = 27898 # Calculations below are taken straight from section 3.5 of the datasheet. X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 X2 = (self.cal_MC << 11) // (X1 + self.cal_MD) B5 = X1 + X2 temp = ((B5 + 8) >> 4) / 10.0 self.logger.debug('Calibrated temperature {0} C', temp) return temp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_pressure(self): """Gets the compensated pressure in Pascals."""
UT = self.read_raw_temp() UP = self.read_raw_pressure() # Datasheet values for debugging: #UT = 27898 #UP = 23843 # Calculations below are taken straight from section 3.5 of the datasheet. # Calculate true temperature coefficient B5. X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 X2 = (self.cal_MC << 11) // (X1 + self.cal_MD) B5 = X1 + X2 self.logger.debug('B5 = {0}', B5) # Pressure Calculations B6 = B5 - 4000 self.logger.debug('B6 = {0}', B6) X1 = (self.cal_B2 * (B6 * B6) >> 12) >> 11 X2 = (self.cal_AC2 * B6) >> 11 X3 = X1 + X2 B3 = (((self.cal_AC1 * 4 + X3) << self._mode) + 2) // 4 self.logger.debug('B3 = {0}', B3) X1 = (self.cal_AC3 * B6) >> 13 X2 = (self.cal_B1 * ((B6 * B6) >> 12)) >> 16 X3 = ((X1 + X2) + 2) >> 2 B4 = (self.cal_AC4 * (X3 + 32768)) >> 15 self.logger.debug('B4 = {0}', B4) B7 = (UP - B3) * (50000 >> self._mode) self.logger.debug('B7 = {0}', B7) if B7 < 0x80000000: p = (B7 * 2) // B4 else: p = (B7 // B4) * 2 X1 = (p >> 8) * (p >> 8) X1 = (X1 * 3038) >> 16 X2 = (-7357 * p) >> 16 p = p + ((X1 + X2 + 3791) >> 4) self.logger.debug('Pressure {0} Pa', p) return p/100
<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_rendition_url(request, image_id, target_width=0, target_height=0): ''' get a rendition url if the rendition does nto exist it will be created in the storage if dimensions do not fit master's aspect ratio then image will be cropped with a centered anchor if one dimensions is omitted (0) the other one will be generated accordind to master's aspect ratio :param request: http GET request /renderer/rendition/url/<image_id>/<target_width>/<target_height>/ :param image_id: the master image primary key :param target_width: target image width if 0 renderer will use target_height to generate a image with correct aspect ratio :param target_height: target image height if 0 renderer will use target_width to generate a image height correct aspect ratio :return: rendition url in a json dictionary ''' im = get_object_or_404(MasterImage, pk=image_id) return JsonResponse({ 'url': im.get_rendition_url(target_width, target_height) })
<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_master_url(request, image_id): ''' get image's master url ... :param request: http GET request /renderer/master/url/<image_id>/ :param image_id: the master image primary key :return: master url in a json dictionary ''' im = get_object_or_404(MasterImage, pk=image_id) return JsonResponse({'url': im.get_master_url()})
<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_results(self,results): """ The resolve server responds with some basic HTML formatting, where the actual results are listed as an HTML list. The regular expression RE_RESULT captures each entry """
reslist = [] cursor = 0 match = RE_RESULTS.search(results,cursor) while match: doc = {} doc['bibcode'] = match.group('bibcode') doc['confidence'] = self.__get_confidence_level(match.group('confidence')) doc['refstring'] = match.group('refstring') reslist.append(doc) cursor = match.end() match = RE_RESULTS.search(results,cursor) return reslist
<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_domain_config(self, domain): """Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found """
domain_root = self.identify_domain_root(domain) host = '' if len(domain_root) != len(domain): host = domain.replace('.' + domain_root, '') domain_connect_api = self._identify_domain_connect_api(domain_root) ret = self._get_domain_config_for_root(domain_root, domain_connect_api) return DomainConnectConfig(domain, domain_root, host, 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 get_domain_connect_template_sync_url(self, domain, provider_id, service_id, redirect_uri=None, params=None, state=None, group_ids=None): """Makes full Domain Connect discovery of a domain and returns full url to request sync consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param group_ids: list(str) :return: (str, str) first field is an url which shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: InvalidDomainConnectSettingsException when settings contain missing fields """
# TODO: support for signatures # TODO: support for provider_name (for shared templates) if params is None: params = {} config = self.get_domain_config(domain) self.check_template_supported(config, provider_id, service_id) if config.urlSyncUX is None: raise InvalidDomainConnectSettingsException("No sync URL in config") sync_url_format = '{}/v2/domainTemplates/providers/{}/services/{}/' \ 'apply?domain={}&host={}&{}' if redirect_uri is not None: params["redirect_uri"] = redirect_uri if state is not None: params["state"] = state if group_ids is not None: params["groupId"] = ",".join(group_ids) return sync_url_format.format(config.urlSyncUX, provider_id, service_id, config.domain_root, config.host, urllib.parse.urlencode(sorted(params.items(), key=lambda val: val[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 get_domain_connect_template_async_context(self, domain, provider_id, service_id, redirect_uri, params=None, state=None, service_id_in_path=False): """Makes full Domain Connect discovery of a domain and returns full context to request async consent. :param domain: str :param provider_id: str :param service_id: str :param redirect_uri: str :param params: dict :param state: str :param service_id_in_path: bool :return: (DomainConnectAsyncContext, str) asyncConsentUrl field of returned context shall be used to redirect the browser to second field is an indication of error :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomainConnectSettingsException when settings are not found :raises: TemplateNotSupportedException when template is not found :raises: InvalidDomainConnectSettingsException when parts of the settings are missing :raises: DomainConnectException on other domain connect issues """
if params is None: params = {} config = self.get_domain_config(domain) self.check_template_supported(config, provider_id, service_id) if config.urlAsyncUX is None: raise InvalidDomainConnectSettingsException("No asynch UX URL in config") if service_id_in_path: if type(service_id) is list: raise DomainConnectException("Multiple services are only supported with service_id_in_path=false") async_url_format = '{0}/v2/domainTemplates/providers/{1}/services/{2}' \ '?client_id={1}&scope={2}&domain={3}&host={4}&{5}' else: if type(service_id) is list: service_id = '+'.join(service_id) async_url_format = '{0}/v2/domainTemplates/providers/{1}' \ '?client_id={1}&scope={2}&domain={3}&host={4}&{5}' if redirect_uri is not None: params["redirect_uri"] = redirect_uri if state is not None: params["state"] = state ret = DomainConnectAsyncContext(config, provider_id, service_id, redirect_uri, params) ret.asyncConsentUrl = async_url_format.format(config.urlAsyncUX, provider_id, service_id, config.domain_root, config.host, urllib.parse.urlencode( sorted(params.items(), key=lambda val: val[0]))) 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 get_async_token(self, context, credentials): """Gets access_token in async process :param context: DomainConnectAsyncContext :param credentials: DomainConnectAsyncCredentials :return: DomainConnectAsyncContext context enriched with access_token and refresh_token if existing :raises: AsyncTokenException """
params = {'code': context.code, 'grant_type': 'authorization_code'} if getattr(context, 'iat', None) and getattr(context, 'access_token_expires_in', None) and \ getattr(context, 'refresh_token', None): now = int(time.time()) + 60 if now > context.iat + context.access_token_expires_in: params = {'refresh_token': context.refresh_token, 'grant_type': 'refresh_token', 'client_id': credentials.client_id, 'client_secret': credentials.client_secret } else: logger.debug('Context has a valid access token') return context params['redirect_uri'] = context.return_url url_get_access_token = '{}/v2/oauth/access_token?{}'.format(context.config.urlAPI, urllib.parse.urlencode( sorted(params.items(), key=lambda val: val[0]))) try: # this has to be checked to avoid secret leakage by spoofed "settings" end-point if credentials.api_url != context.config.urlAPI: raise AsyncTokenException("URL API for provider does not match registered one with credentials") data, status = http_request_json(self._networkContext, method='POST', content_type='application/json', body=json.dumps({ 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, }), url=url_get_access_token ) except Exception as ex: logger.debug('Cannot get async token: {}'.format(ex)) raise AsyncTokenException('Cannot get async token: {}'.format(ex)) if 'access_token' not in data \ or 'expires_in' not in data \ or 'token_type' not in data \ or data['token_type'].lower() != 'bearer': logger.debug('Token not complete: {}'.format(data)) raise AsyncTokenException('Token not complete: {}'.format(data)) context.access_token = data['access_token'] context.access_token_expires_in = data['expires_in'] context.iat = int(time.time()) if 'refresh_token' in data: context.refresh_token = data['refresh_token'] return context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def httpretty_callback(request, uri, headers): """httpretty request handler. converts a call intercepted by httpretty to the stack-in-a-box infrastructure :param request: request object :param uri: the uri of the request :param headers: headers for the response :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """
method = request.method response_headers = CaseInsensitiveDict() response_headers.update(headers) request_headers = CaseInsensitiveDict() request_headers.update(request.headers) request.headers = request_headers return StackInABox.call_into(method, request, uri, response_headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def registration(uri): """httpretty handler registration. registers a handler for a given uri with httpretty so that it can be intercepted and handed to stack-in-a-box. :param uri: uri used for the base of the http requests :returns: n/a """
# add the stack-in-a-box specific response codes to # http's status information status_data = { 595: 'StackInABoxService - Unknown Route', 596: 'StackInABox - Exception in Service Handler', 597: 'StackInABox - Unknown Service' } for k, v in six.iteritems(status_data): if k not in httpretty.http.STATUSES: httpretty.http.STATUSES[k] = v # log the uri that is used to access the stack-in-a-box services logger.debug('Registering Stack-In-A-Box at {0} under Python HTTPretty' .format(uri)) # tell stack-in-a-box what uri to match with StackInABox.update_uri(uri) # build the regex for the uri and register all http verbs # with httpretty regex = re.compile('(http)?s?(://)?{0}:?(\d+)?/'.format(uri), re.I) for method in HttpBaseClass.METHODS: register_uri(method, regex, body=httpretty_callback)
<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(self): """ Return the value of the redirect response """
user = self.trigger.agentml.request_log.most_recent().user groups = self.trigger.agentml.request_log.most_recent().groups # Does the redirect statement have tags to parse? if len(self._element): message = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger))) else: message = self._element.text # Is there a default value defined? default = attribute(self._element, 'default', '') response = self.trigger.agentml.get_reply(user.id, message, groups) return response or default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onHello(self, realm, details): """ Callback fired when client wants to attach session. """
log.msg("onHello: {} {}".format(realm, details)) self._pending_auth = None if details.authmethods: for authmethod in details.authmethods: if authmethod == u"wampcra": ## lookup user in user DB salt, key, role, uid = yield self.factory.userdb.get(details.authid) log.msg("salt, key, role: {} {} {} {}".format(salt, key, role, uid)) ## if user found .. if key: log.msg("found key") ## setup pending auth self._pending_auth = PendingAuth(key, details.pending_session, details.authid, role, authmethod, u"userdb", uid) log.msg("setting challenge") ## send challenge to client extra = { u'challenge': self._pending_auth.challenge } ## when using salted passwords, provide the client with ## the salt and then PBKDF2 parameters used if salt: extra[u'salt'] = salt extra[u'iterations'] = 1000 extra[u'keylen'] = 32 defer.returnValue(types.Challenge(u'wampcra', extra)) ## deny client defer.returnValue(types.Deny())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onAuthenticate(self, signature, extra): """ Callback fired when a client responds to an authentication challenge. """
log.msg("onAuthenticate: {} {}".format(signature, extra)) ## if there is a pending auth, and the signature provided by client matches .. if self._pending_auth: if signature == self._pending_auth.signature: ## accept the client return types.Accept(authid = self._pending_auth.uid, authrole = self._pending_auth.authrole, authmethod = self._pending_auth.authmethod, authprovider = self._pending_auth.authprovider) else: ## deny client return types.Deny(message = u"signature is invalid") else: ## deny client return types.Deny(message = u"no pending authentication")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_stdout_logger(log_level=logging.DEBUG): """Configures logging to use STDOUT"""
root = logging.getLogger() root.setLevel(log_level) handler = logging.StreamHandler() handler.setLevel(log_level) handler.setFormatter(logging.Formatter(LOG_FORMAT_ESCAPED)) root.addHandler(handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def silence_logging(method): """Disables logging for the duration of what is being wrapped. This is particularly useful when testing if a test method is supposed to issue an error message which is confusing that the error shows for a successful test. """
@wraps(method) def wrapper(*args, **kwargs): logging.disable(logging.ERROR) result = method(*args, **kwargs) logging.disable(logging.NOTSET) return result return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_create_tool_item(self): """This is called by the UIManager when it is time to instantiate the proxy"""
proxy = SpinToolItem(*self._args_for_toolitem) self.connect_proxy(proxy) return proxy
<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_value(self, value): """Set value to action."""
self._value = value for proxy in self.get_proxies(): proxy.handler_block(self._changed_handlers[proxy]) proxy.set_value(self._value) proxy.handler_unblock(self._changed_handlers[proxy]) pass self.emit('changed') 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 clean(ctx): """ clean generated project files """
os.chdir(PROJECT_DIR) patterns = ['.cache', '.coverage', '.eggs', 'build', 'dist'] ctx.run('rm -vrf {0}'.format(' '.join(patterns))) ctx.run('''find . \( -name '*,cover' -o -name '__pycache__' -o -name '*.py[co]' -o -name '_work' \) ''' '''-exec rm -vrf '{}' \; || true''')