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 _remove_code(site): """ Delete project files @type site: Site """
def handle_error(function, path, excinfo): click.secho('Failed to remove path ({em}): {p}'.format(em=excinfo.message, p=path), err=True, fg='red') if os.path.exists(site.root): shutil.rmtree(site.root, onerror=handle_error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handler(self, conn): """ Connection handler thread. Takes care of communication with the client and running the proper task or applying a signal. """
incoming = self.recv(conn) self.log(DEBUG, incoming) try: # E.g. ['twister', [7, 'invert'], {'guess_type': True}] task, args, kw = self.codec.decode(incoming) # OK, so we've received the information. Now to use it. self.log(INFO, 'Ful...
<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_server(self): """ Stop receiving connections, wait for all tasks to end, and then terminate the server. """
self.stop = True while self.task_count: time.sleep(END_RESP) self.terminate = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fastqIterator(fn, verbose=False, allowNameMissmatch=False): """ A generator function which yields FastqSequence objects read from a file or stream. This is a...
it = fastqIteratorSimple(fn, verbose=verbose, allowNameMissmatch=allowNameMissmatch) for s in it: yield 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 during(rrule, duration=None, timestamp=None, **kwargs): """ Check if input timestamp is in rrule+duration period :param rrule: rrule to check :type rrule: st...
result = False # if rrule is a string expression if isinstance(rrule, string_types): rrule_object = rrule_class.rrulestr(rrule) else: rrule_object = rrule_class(**rrule) # if timestamp is None, use now if timestamp is None: timestamp = time() # get now object ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _any(confs=None, **kwargs): """ True iif at least one input condition is equivalent to True. :param confs: confs to check. :type confs: list or dict or str :...
result = False if confs is not None: # ensure confs is a list if isinstance(confs, string_types) or isinstance(confs, dict): confs = [confs] for conf in confs: result = run(conf, **kwargs) if result: # leave function as soon as a result if True ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _all(confs=None, **kwargs): """ True iif all input confs are True. :param confs: confs to check. :type confs: list or dict or str :param kwargs: additional t...
result = False if confs is not None: # ensure confs is a list if isinstance(confs, string_types) or isinstance(confs, dict): confs = [confs] # if at least one conf exists, result is True by default result = True for conf in confs: result = run(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 _not(condition=None, **kwargs): """ Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """
result = True if condition is not None: result = not run(condition, **kwargs) 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 condition(condition=None, statement=None, _else=None, **kwargs): """ Run an statement if input condition is checked and return statement result. :param condi...
result = None checked = False if condition is not None: checked = run(condition, **kwargs) if checked: # if condition is checked if statement is not None: # process statement result = run(statement, **kwargs) elif _else is not None: # else process _else statement...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch( confs=None, remain=False, all_checked=False, _default=None, **kwargs ): """ Execute first statement among conf where task result is True. If remain, ...
# init result result = [] if remain else None # check if remain and one task has already been checked. remaining = False if confs is not None: if isinstance(confs, string_types) or isinstance(confs, dict): confs = [confs] for conf in confs: # check if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, message): """Overrides error to control printing output"""
if self._debug: import pdb _, _, tb = sys.exc_info() if tb: pdb.post_mortem(tb) else: pdb.set_trace() self.print_usage(sys.stderr) self.exit(2, ('\nERROR: {}\n').format(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 format_help(self): """Overrides format_help to not print subparsers"""
formatter = self._get_formatter() # usage formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups) # description formatter.add_text(self.description) # positionals, optionals and user-defined groups, except SubParsers...
<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_attributes_file(self): ''' Called during initialization. Only needs to be explicitly called if save_and_close_attributes is explicitly called beforehand. ''' if not self.saveable(): raise AttributeError("Cannot open attribute file without a valid file...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def save_and_close_attributes(self): ''' Performs the same function as save_attributes but also closes the attribute file. ''' if not self.saveable(): raise AttributeError("Cannot save attribute file without a valid file") if not self._db_closed: 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 split_task_parameters(line): """ Split a string of comma separated words."""
if line is None: result = [] else: result = [parameter.strip() for parameter in line.split(",")] 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 find_tasks(lines): """ Find task lines and corresponding line numbers in a list of lines. """
tasks = [] linenumbers = [] pattern = re.compile(TASK_PATTERN) for n, line in enumerate(lines): if "#" in line and "<-" in line: m = pattern.match(line) if m is not None: groupdict = m.groupdict() linenumbers.append(n) for ...
<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_environment(preamble): """ Create a dictionary of variables obtained from the preamble of the task file and the environment the program is running on....
environment = copy.deepcopy(os.environ) for line in preamble: logging.debug(line) if "=" in line and not line.startswith("#"): tmp = line.split("=") key = tmp[0].strip() value = tmp[1].strip() logging.debug( "Found variable {} with...
<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_input_file(text, variables=None): """ Parser for a file with syntax somewhat similar to Drake."""
text = find_includes(text) lines = text.splitlines() tasks, linenumbers = find_tasks(lines) preamble = [line for line in lines[:linenumbers[0]]] logging.debug("Preamble:\n{}".format("\n".join(preamble))) if variables is not None: preamble += "\n" + "\n".join(variables) environment =...
<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_fields(self, *values): """ Take a list of values, which must be primary keys of the model linked to the related collection, and return a list of related ...
result = [] for related_instance in values: if not isinstance(related_instance, model.RedisModel): related_instance = self.related_field._model(related_instance) result.append(getattr(related_instance, self.related_field.name)) 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 _reverse_call(self, related_method, *values): """ Convert each value to a related field, then call the method on each field, passing self.instance as argumen...
related_fields = self._to_fields(*values) for related_field in related_fields: if callable(related_method): related_method(related_field, self.instance._pk) else: getattr(related_field, related_method)(self.instance._pk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def srem(self, *values): """ Do a "set" call with self.instance as parameter for each value. Values must be primary keys of the related model. """
self._reverse_call(lambda related_field, value: related_field.delete(), *values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lrem(self, *values): """ Do a "lrem" call with self.instance as parameter for each value. Values must be primary keys of the related model. The "count" argum...
self._reverse_call(lambda related_field, value: related_field.lrem(0, value), *values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loaded(self, request, *args, **kwargs): """Return a list of loaded Packs. """
serializer = self.get_serializer(list(Pack.objects.all()), many=True) return Response(serializer.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 indexed_file(self, f): """ Setter for information about the file this object indexes. :param f: a tuple of (filename, handle), either (or both) of which can ...
filename, handle = f if handle is None and filename is not None: handle = open(filename) if (handle is None and filename is None) or \ (filename != self._indexed_filename) or \ (handle != self._indexed_file_handle): self.index = {} if ((handle is not None or filename is not No...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_index(self, fh, to_str_func=str, generate=True, verbose=False): """ Write this index to a file. Only the index dictionary itself is stored, no informat...
try: handle = open(fh, "w") except TypeError: # okay, not a filename, try to treat it as a stream to write to. handle = fh if generate: self.__build_index(verbose=verbose) for key in self._index: handle.write(to_str_func(key) + "\t" + str(self._index[key]) + "\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def steps(self): """Returns an iterable containing the steps to this `Uri` from the root `Uri`, including the root `Uri`."""
def _iter(uri, acc): acc.appendleft(uri.name if uri.name else '') return _iter(uri.parent, acc) if uri.parent else acc return _iter(self, acc=deque())
<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(cls, addr): """Parses a new `Uri` instance from a string representation of a URI. (None, ['', 'foo', 'bar'], '/foo/bar', 'bar') ('somenode:123', ['', '...
if addr.endswith('/'): raise ValueError("Uris must not end in '/'") # pragma: no cover parts = addr.split('/') if ':' in parts[0]: node, parts[0] = parts[0], '' else: node = None ret = None # Uri(name=None, parent=None, node=node) if node 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 new_scope(self, new_scope={}): """Add a new innermost scope for the duration of the with block. Args: new_scope (dict-like): The scope to add. """
old_scopes, self.scopes = self.scopes, self.scopes.new_child(new_scope) yield self.scopes = old_scopes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new(self, val): """Add a new value to me. Args: val (LispVal): The value to be added. Returns: LispVal: The added value. Raises: ~parthial.errs.LimitationEr...
if len(self.things) >= self.max_things: raise LimitationError('too many things') self.things.add(val) return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rec_new(self, val): """Recursively add a new value and its children to me. Args: val (LispVal): The value to be added. Returns: LispVal: The added value. ""...
if val not in self.things: for child in val.children(): self.rec_new(child) self.new(val) return val
<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_rec_new(self, k, val): """Recursively add a new value and its children to me, and assign a variable to it. Args: k (str): The name of the variable to as...
self.rec_new(val) self[k] = val return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval(self, expr): """Evaluate an expression. This does **not** add its argument (or its result) as an element of me! That is the responsibility of the code t...
if self.depth >= self.max_depth: raise LimitationError('too much nesting') if self.steps >= self.max_steps: raise LimitationError('too many steps') self.depth += 1 self.steps += 1 res = expr.eval(self) self.depth -= 1 return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(*args): """Display error message via stderr or GUI."""
if sys.stdin.isatty(): print('ERROR:', *args, file=sys.stderr) else: notify_error(*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 have(cmd): """Determine whether supplied argument is a command on the PATH."""
try: # Python 3.3+ only from shutil import which except ImportError: def which(cmd): """ Given a command, return the path which conforms to the given mode on the PATH, or None if there is no such file. """ def _access_check(p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multithreader(args, paths): """Execute multiple processes at once."""
def shellprocess(path): """Return a ready-to-use subprocess.""" import subprocess return subprocess.Popen(args + [path], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) processes = [shellprocess(path) for path in pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_gui(path): """Prompt for a new filename via GUI."""
import subprocess filepath, extension = os.path.splitext(path) basename = os.path.basename(filepath) dirname = os.path.dirname(filepath) retry_text = 'Sorry, please try again...' icon = 'video-x-generic' # detect and configure dialog program if have('yad'): args = ['yad', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt_terminal(path): """Prompt for a new filename via terminal."""
def rlinput(prompt_msg, prefill=''): """ One line is read from standard input. Display `prompt_msg` on standard error. `prefill` is placed into the editing buffer before editing begins. """ import readline readline.set_startup_hook(lambda: readline.insert_te...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(path): """Rename a file if necessary."""
new_path = prompt(path) if path != new_path: try: from shutil import move except ImportError: from os import rename as move move(path, new_path) return new_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan(subtitles): """Remove advertising from subtitles."""
from importlib.util import find_spec try: import subnuker except ImportError: fatal('Unable to scan subtitles. Please install subnuker.') # check whether aeidon is available aeidon = find_spec('aeidon') is not None if sys.stdin.isatty(): # launch subnuker from the ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getavailable(self): """Return a list of subtitle downloaders available."""
from importlib import import_module available = [] for script in self.SCRIPTS: if have(script): available.append(script) for module in self.MODULES: try: import_module(module) available.append(module) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getdefault(self): """Return an available default downloader."""
if not self.available: error('No supported downloaders available') print('\nPlease install one of the following:', file=sys.stderr) print(self.SUPPORTED, file=sys.stderr) sys.exit(1) default = Config.DOWNLOADER_DEFAULT if default in self.availa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, paths, tool, language): """Download subtitles via a number of tools."""
if tool not in self.available: fatal('{!r} is not installed'.format(tool)) try: from . import plugins downloader = plugins.__getattribute__(tool) except AttributeError: fatal('{!r} is not a supported download tool'.format(tool)) try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def epilog(self): """Return text formatted for the usage description's epilog."""
bold = '\033[1m' end = '\033[0m' available = self.available.copy() index = available.index(Config.DOWNLOADER_DEFAULT) available[index] = bold + '(' + available[index] + ')' + end formatted = ' | '.join(available) return 'Downloaders available: ' + formatted
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_mock_desc(self, patch, *args, **kwarg): """ Context manager or decorator in order to patch a mock definition of service endpoint in a test. :param patc...
return PatchMockDescDefinition(patch, self, *args, **kwarg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def use_mock(self, mock, *args, **kwarg): """ Context manager or decorator in order to use a coroutine as mock of service endpoint in a test. :param mock: Corout...
return UseMockDefinition(mock, self, *args, **kwarg)
<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_install(context): """ - sets an acl user group to hold all intranet users - setup the dynamic groups plugin - sets the addable types for the ploneintran...
marker = 'ploneintranet-workspace.marker' if context.readDataFile(marker) is None: return portal = api.portal.get() # Set up a group to hold all intranet users if api.group.get(groupname=INTRANET_USERS_GROUP_ID) is None: api.group.create(groupname=INTRANET_USERS_GROUP_ID) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, value, **kwargs): """ pre-serialize value """
if self._serialize is not None: return self._serialize(value, **kwargs) else: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def complete_message(buf): "returns msg,buf_remaining or None,buf" # todo: read dollar-length for strings; I dont think I can blindly trust newlines. learn about escaping # note: all the length checks are +1 over what I need because I'm asking for *complete* lines. lines=buf.split('\r\n') if len(lines)<=...
<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_message(self,msg,sock): "serialize and deserialize" command=msg[0] try: f={'GET':self.get,'SET':self.set,'SUBSCRIBE':self.sub,'PUBLISH':self.pub, 'PING':self.ping,'GETSET':self.getset,'EXPIRE':self.expire,'DEL':self.delete}[command] except KeyError: print msg; raise args=msg[...
<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_playbook_from_file(self, path, vars={}): ''' run top level error checking on playbooks and allow them to include other playbooks. ''' playbook_data = utils.parse_yaml_from_file(path) accumulated_plays = [] play_basedirs = [] if type(playbook_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 run(self): ''' run all patterns in the playbook ''' plays = [] matched_tags_all = set() unmatched_tags_all = set() # loop through all patterns and run them self.callbacks.on_start() for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _async_poll(self, poller, async_seconds, async_poll_interval): ''' launch an async job, if poll_interval is set, wait for completion ''' results = poller.wait(async_seconds, async_poll_interval) # mark any hosts that are still listed as started as failed # since these likely got ki...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _list_available_hosts(self, *args): ''' returns a list of hosts that haven't failed and aren't dark ''' return [ h for h in self.inventory.list_hosts(*args) if (h not in self.stats.failures) and (h not in self.stats.dark)]
<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_task_internal(self, task): ''' run a particular module step in a playbook ''' hosts = self._list_available_hosts() self.inventory.restrict_to(hosts) runner = cirruscluster.ext.ansible.runner.Runner( pattern=task.play.hosts, inventory=self.inventory, module_name=tas...
<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_task(self, play, task, is_handler): ''' run a single task in the playbook and recursively run any subtasks. ''' self.callbacks.on_task_start(utils.template(play.basedir, task.name, task.module_vars, lookup_fatal=False), is_handler) # load up an appropriate ansible runner to run the 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 _flag_handler(self, play, handler_name, host): ''' if a task has any notify elements, flag handlers for run at end of execution cycle for hosts that have indicated changes have been made ''' found = False for x in play.handlers(): if handler_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 _do_setup_step(self, play): ''' get facts from the remote system ''' host_list = self._list_available_hosts(play.hosts) if play.gather_facts is False: return {} elif play.gather_facts is None: host_list = [h for h in host_list if h not in self.SETUP_CACHE or...
<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_play(self, play): ''' run a list of tasks for a given pattern, in order ''' self.callbacks.on_play_start(play.name) # if no hosts matches this play, drop out if not self.inventory.list_hosts(play.hosts): self.callbacks.on_no_hosts_matched() return True ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_cmdLine_instructions(args): """ Parses command-line arguments. These are instruction to the manager to create instances and put settings. """
instructions = dict() rargs = list() for arg in args: if arg[:2] == '--': tmp = arg[2:] bits = tmp.split('=', 1) if len(bits) == 1: bits.append('') instructions[bits[0]] = bits[1] else: rargs.append(arg) 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 main(): """ Entry-point """
sarah.coloredLogging.basicConfig(level=logging.DEBUG, formatter=MirteFormatter()) l = logging.getLogger('mirte') instructions, args = parse_cmdLine_instructions(sys.argv[1:]) m = Manager(l) load_mirteFile(args[0] if args else 'default', m, logger=l) execute_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def installed(cls): """ Used in ``yacms.pages.views.page`` to ensure ``PageMiddleware`` or a subclass has been installed. We cache the result on the ``PageMiddle...
try: return cls._installed except AttributeError: name = "yacms.pages.middleware.PageMiddleware" mw_setting = get_middleware_setting() installed = name in mw_setting if not installed: for name in mw_setting: ...
<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_view(self, request, view_func, view_args, view_kwargs): """ Per-request mechanics for the current page object. """
# Load the closest matching page by slug, and assign it to the # request object. If none found, skip all further processing. slug = path_to_slug(request.path_info) pages = Page.objects.with_ascendants_for_slug(slug, for_user=request.user, include_login_required=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unshare(flags): """ Disassociate parts of the process execution context. :param flags int: A bitmask that specifies which parts of the execution context shou...
res = lib.unshare(flags) if res != 0: _check_error(ffi.errno)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setns(fd, nstype): """ Reassociate thread with a namespace :param fd int: The file descriptor referreing to one of the namespace entries in a :directory::`/p...
res = lib.setns(fd, nstype) if res != 0: _check_error(ffi.errno)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset(self): """ Resets class properties. """
self._name = None self._start_time = None self._owner = os.getuid() self._paths['task_dir'] = None self._paths['task_config'] = None self._loaded = 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 _save_active_file(self): """ Saves current task information to active file. Example format:: active_task { name "task name"; start_time "2012-04-23 15:18:22"...
_parser = parser.SettingParser() # add name _parser.add_option(None, 'name', common.to_utf8(self._name)) # add start time start_time = self._start_time.strftime('%Y-%m-%d %H:%M:%S.%f') _parser.add_option(None, 'start_time', start_time) # write it to file ...
<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_prior(self): """ Cleans up from a previous task that didn't exit cleanly. Returns ``True`` if previous task was cleaned. """
if self._loaded: try: pid_file = daemon.get_daemon_pidfile(self) # check if it exists so we don't raise if os.path.isfile(pid_file): # read pid from file pid = int(common.readfile(pid_file)) ...
<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): """ Loads a task if the active file is available. """
try: _parser = parser.parse_config(self._paths['active_file'], self.HEADER_ACTIVE_FILE) # parse expected options into a dict to de-dupe keys = ('name', 'start_time') opts = dict(o for o in _parser.options if o[0] in key...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists(self, task_name): """ Determines if task directory exists. `task_name` Task name. Returns ``True`` if task exists. """
try: return os.path.exists(self._get_task_dir(task_name)) except OSError: return 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 create(self, task_name, clone_task=None): """ Creates a new task directory. `task_name` Task name. `clone_task` Existing task name to use as a template for n...
if not task_name or task_name.startswith('-'): raise ValueError('Invalid task name') try: task_dir = self._get_task_dir(task_name) if self.exists(task_dir): raise errors.TaskExists(task_name) task_cfg = self.get_config_path(task_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 rename(self, old_task_name, new_task_name): """ Renames an existing task directory. `old_task_name` Current task name. `new_task_name` New task name. Returns...
if not old_task_name or old_task_name.startswith('-'): raise ValueError('Old task name is invalid') if not new_task_name or new_task_name.startswith('-'): raise ValueError('New new task name is invalid') if old_task_name == new_task_name: raise ValueError(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, task_name): """ Removes an existing task directory. `task_name` Task name. Returns ``True`` if removal successful. """
try: task_dir = self._get_task_dir(task_name) shutil.rmtree(task_dir) return True except OSError: return 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 get_list_info(self, task_name=None): """ Lists all tasks and associated information. `task_name` Task name to limit. Default: return all valid tasks. Returns...
try: tasks = [] # get all tasks dirs tasks_dir = os.path.join(self._paths['base_dir'], 'tasks') if task_name: # if task folder doesn't exist, return nothing if not os.path.isdir(os.path.join(tasks_dir, task_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 start(self, task_name): """ Starts a new task matching the provided name. `task_name` Name of existing task to start. Returns boolean. * Raises a ``TaskNotFo...
self._clean_prior() if self._loaded: raise errors.ActiveTask # get paths task_dir = os.path.join(self._paths['base_dir'], 'tasks', task_name) task_config = os.path.join(task_dir, 'task.cfg') if not os.path.isdir(task_dir): raise errors.TaskNot...
<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(self): """ Stops the current task and cleans up, including removing active task config file. * Raises ``NoActiveTask`` exception if no active task found...
self._clean_prior() if not self._loaded: raise errors.NoActiveTask self._clean()
<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_total_duration(self, duration): """ Set the total task duration in minutes. """
if duration < 1: raise ValueError(u'Duration must be postive') elif self.duration > duration: raise ValueError(u'{0} must be greater than current duration') self._total_duration = duration
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def active(self): """ Returns if task is active. """
if not os.path.isfile(self._paths['active_file']): return False return self._loaded
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def duration(self): """ Returns task's current duration in minutes. """
if not self._loaded: return 0 delta = datetime.datetime.now() - self._start_time total_secs = (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10 ** 6) / 10 ** 6 return max(0, int(round(total_secs / 60.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 list_objects(self, resources): """Generate a listing for a set of resource handles consisting of resource identifier, name, and timestamp. Parameters resourc...
result = [] for res in resources: result.append('\t'.join([res.identifier, res.name, str(res.timestamp)[:19]])) 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 set_locale(request): """Return locale from GET lang param or automatically."""
return request.query.get('lang', app.ps.babel.select_locale_by_request(request))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def globals(self): """Find the globals of `self` by importing `self.module`"""
try: return vars(__import__(self.module, fromlist=self.module.split('.'))) except ImportError: if self.warn_import: warnings.warn(ImportWarning( 'Cannot import module {} for SerializableFunction. Restricting to builtins.'.format(self.module) ...
<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): """Import the constant from `self.module`"""
module = __import__(self.module, fromlist=self.module.split('.')) if self.name is None: return module return getattr(module, self.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 agg(self, func, *fields, **name): """ Calls the aggregation function `func` on each group in the GroubyTable, and leaves the results in a new column with the...
if name: if len(name) > 1 or 'name' not in name: raise TypeError("Unknown keyword args passed into `agg`: %s" % name) name = name.get('name') if not isinstance(name, basestring): raise TypeError("Column names mu...
<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(self): """ After adding the desired aggregation columns, `collect` finalizes the groupby operation by converting the GroupbyTable into a DataTable. T...
# The final order of columns is determined by the # group keys and the aggregation columns final_field_order = list(self.__groupfields) + self.__grouptable.fields # Transform the group key rows into columns col_values = izip(*self.__grouptable['groupkey']) # Assign the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kv_format_dict(d, keys=None, separator=DEFAULT_SEPARATOR): """Formats the given dictionary ``d``. For more details see :func:`kv_format`. :param collections....
return _format_pairs(dump_dict(d, keys), separator=separator)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kv_format_object(o, keys=None, separator=DEFAULT_SEPARATOR): """Formats an object's attributes. Useful for object representation implementation. Will skip me...
if keys is None: key_values = [] for k, v in ((x, getattr(o, x)) for x in sorted(dir(o))): if k.startswith('_') or isroutine(v): continue key_values += (k, v), else: key_values = ((k, getattr(o, k)) for k in keys) return kv_format_pairs(key_v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, request, *args, **kwargs): """ Triggers the task that sends invitation messages """
status = 201 accepted = {"accepted": True} send_invite_messages.apply_async() return Response(accepted, status=status)
<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(self, request): '''Create a user and token, given an email. If user exists just provide the token.''' serializer = CreateUserSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data.get('email') try: u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, request, *args, **kwargs): """ Redefine parent's method. Called on each new request from user. Main difference between Django's approach and o...
# this part copied from django source code if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed # we changed o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html(self, data=None, template=None): """ Send html document to user. Args: - data: Dict to render template, or string with rendered HTML. - template: Name o...
if data is None: data = {} if template: return render(self.request, template, data) return HttpResponse(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 by_skills(queryset, skill_string=None): """ Filter queryset by a comma delimeted skill list """
if skill_string: operator, items = get_operator_and_items(skill_string) q_obj = SQ() for s in items: if len(s) > 0: q_obj.add(SQ(skills=s), operator) queryset = queryset.filter(q_obj) return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_causes(queryset, cause_string=None): """ Filter queryset by a comma delimeted cause list """
if cause_string: operator, items = get_operator_and_items(cause_string) q_obj = SQ() for c in items: if len(c) > 0: q_obj.add(SQ(causes=c), operator) queryset = queryset.filter(q_obj) return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_published(queryset, published_string='true'): """ Filter queryset by publish status """
if published_string == 'true': queryset = queryset.filter(published=1) elif published_string == 'false': queryset = queryset.filter(published=0) # Any other value will return both published and unpublished return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_name(queryset, name=None): """ Filter queryset by name, with word wide auto-completion """
if name: queryset = queryset.filter(name=name) return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_address(queryset, address='', project=False): """ Filter queryset by publish status. If project=True, we also apply a project exclusive filter """
if address: address = json.loads(address) if u'address_components' in address: q_objs = [] """ Caribbean filter """ if len(address[u'address_components']): if address[u'address_components'][0]['long_name'] == 'Caribbean': queryset = queryset.filter( ...
<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_out(queryset, setting_name): """ Remove unwanted results from queryset """
kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {}) queryset = queryset.exclude(**kwargs) return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_apps(): """ It returns a list of application contained in PROJECT_APPS """
return [(d.split('.')[-1], d.split('.')[-1]) for d in os.listdir( os.getcwd()) if is_app(u"{}/{}".format(os.getcwd(), d))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slug(self): """ It returns node's slug """
if self.is_root_node(): return "" if self.slugable and self.parent.parent: if not self.page.regex or (self.page.regex and not self.page.show_regex) or self.is_leaf_node(): return u"{0}/{1}".format(self.parent.slug, self.page.slug) elif self.page.regex...
<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_pattern(self): """ It returns its url pattern """
if self.is_root_node(): return "" else: parent_pattern = self.parent.get_pattern() if parent_pattern != "": parent_pattern = u"{}".format(parent_pattern) if not self.page and not self.is_leaf_node(): if self.hide_in_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 presentation_type(self): """ It returns page's presentation_type """
if self.page and self.page.presentation_type: return self.page.presentation_type return ""