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 copytree(src, dst, symlinks=False, ignore=None): """Copy from source directory to destination"""
# TODO(crow): OSError: [Errno 17] File exists if not osp.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = osp.join(src, item) d = osp.join(dst, item) if osp.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, 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 emptytree(directory): """Delete all the files and dirs under specified directory"""
for p in os.listdir(directory): fp = osp.join(directory, p) if osp.isdir(fp): try: shutil.rmtree(fp) logger.info("Delete directory %s" % fp) except Exception, e: logger.error("Unable to delete directory %s: %s" % (fp, str(e))) elif osp.isfile(fp): try: logging.info("Delete file %s" % fp) os.remove(fp) except Exception, e: logger.error("Unable to delete file %s: %s" % (fp, str(e))) else: logger.error("Unable to delete %s, unknown filetype" % fp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listdir_nohidden(path): """List not hidden files or directories under path"""
for f in os.listdir(path): if isinstance(f, str): f = unicode(f, "utf-8") if not f.startswith('.'): yield 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 check_config(data): """Check if metadata is right TODO(crow): check more """
is_right = True if "title" not in data: logging.error("No 'title' in _config.yml") is_right = False return is_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 get_ymal_data(data): """Get metadata and validate them :param data: metadata in yaml format """
try: format_data = yaml.load(data) except yaml.YAMLError, e: msg = "Yaml format error: {}".format( unicode(str(e), "utf-8") ) logging.error(msg) sys.exit(1) if not check_config(format_data): sys.exit(1) return format_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 parse_markdown(markdown_content, site_settings): """Parse markdown text to html. :param markdown_content: Markdown text lists #TODO# """
markdown_extensions = set_markdown_extensions(site_settings) html_content = markdown.markdown( markdown_content, extensions=markdown_extensions, ) return html_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 wait(self): """ Wait for the request to finish and return the result or error when finished :returns: result or error :type: result tyoe or Error """
self.thread.join() if self.error is not None: return self.error return self.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 filter_objects_by_section(self, rels, section): """Build a queryset containing all objects in the section subtree."""
subtree = section.get_descendants(include_self=True) kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels] q = Q(**kwargs_list[0]) for kwargs in kwargs_list[1:]: q |= Q(**kwargs) return self.get_manager(get_item_model_class()).filter(q).distinct()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fullqualname_py3(obj): """Fully qualified name for objects in Python 3."""
if type(obj).__name__ == 'builtin_function_or_method': return _fullqualname_builtin_py3(obj) elif type(obj).__name__ == 'function': return _fullqualname_function_py3(obj) elif type(obj).__name__ in ['member_descriptor', 'method_descriptor', 'wrapper_descriptor']: return obj.__objclass__.__module__ + '.' + obj.__qualname__ elif type(obj).__name__ == 'method': return _fullqualname_method_py3(obj) elif type(obj).__name__ == 'method-wrapper': return fullqualname_py3(obj.__self__) + '.' + obj.__name__ elif type(obj).__name__ == 'module': return obj.__name__ elif type(obj).__name__ == 'property': return obj.fget.__module__ + '.' + obj.fget.__qualname__ elif inspect.isclass(obj): return obj.__module__ + '.' + obj.__qualname__ return obj.__class__.__module__ + '.' + obj.__class__.__qualname__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fullqualname_builtin_py3(obj): """Fully qualified name for 'builtin_function_or_method' objects in Python 3. """
if obj.__module__ is not None: # built-in functions module = obj.__module__ else: # built-in methods if inspect.isclass(obj.__self__): module = obj.__self__.__module__ else: module = obj.__self__.__class__.__module__ return module + '.' + obj.__qualname__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fullqualname_function_py3(obj): """Fully qualified name for 'function' objects in Python 3. """
if hasattr(obj, "__wrapped__"): # Required for decorator.__version__ <= 4.0.0. qualname = obj.__wrapped__.__qualname__ else: qualname = obj.__qualname__ return obj.__module__ + '.' + qualname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fullqualname_method_py3(obj): """Fully qualified name for 'method' objects in Python 3. """
if inspect.isclass(obj.__self__): cls = obj.__self__.__qualname__ else: cls = obj.__self__.__class__.__qualname__ return obj.__self__.__module__ + '.' + cls + '.' + obj.__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 fullqualname_py2(obj): """Fully qualified name for objects in Python 2."""
if type(obj).__name__ == 'builtin_function_or_method': return _fullqualname_builtin_py2(obj) elif type(obj).__name__ == 'function': return obj.__module__ + '.' + obj.__name__ elif type(obj).__name__ in ['member_descriptor', 'method_descriptor', 'wrapper_descriptor']: return (obj.__objclass__.__module__ + '.' + obj.__objclass__.__name__ + '.' + obj.__name__) elif type(obj).__name__ == 'instancemethod': return _fullqualname_method_py2(obj) elif type(obj).__name__ == 'method-wrapper': return fullqualname_py2(obj.__self__) + '.' + obj.__name__ elif type(obj).__name__ == 'module': return obj.__name__ elif inspect.isclass(obj): return obj.__module__ + '.' + obj.__name__ return obj.__class__.__module__ + '.' + obj.__class__.__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 _fullqualname_builtin_py2(obj): """Fully qualified name for 'builtin_function_or_method' objects in Python 2. """
if obj.__self__ is None: # built-in functions module = obj.__module__ qualname = obj.__name__ else: # built-in methods if inspect.isclass(obj.__self__): cls = obj.__self__ else: cls = obj.__self__.__class__ module = cls.__module__ qualname = cls.__name__ + '.' + obj.__name__ return module + '.' + qualname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fullqualname_method_py2(obj): """Fully qualified name for 'instancemethod' objects in Python 2. """
if obj.__self__ is None: # unbound methods module = obj.im_class.__module__ cls = obj.im_class.__name__ else: # bound methods if inspect.isclass(obj.__self__): # methods decorated with @classmethod module = obj.__self__.__module__ cls = obj.__self__.__name__ else: module = obj.__self__.__class__.__module__ cls = obj.__self__.__class__.__name__ return module + '.' + cls + '.' + obj.__func__.__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 parse(binary, **params): """Turns a TAR file into a frozen sample."""
binary = io.BytesIO(binary) collection = list() with tarfile.TarFile(fileobj=binary, mode='r') as tar: for tar_info in tar.getmembers(): content_type, encoding = mimetypes.guess_type(tar_info.name) content = tar.extractfile(tar_info) content = content_encodings.get(encoding).decode(content) content = content_types.get(content_type).parse(content, **params) collection.apppend((tar_info.name, content)) return collection
<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(collection, **params): """Truns a frozen sample into a TAR file."""
binary = io.BytesIO() with tarfile.TarFile(fileobj=binary, mode='w') as tar: mode = params.get('mode', 0o640) now = calendar.timegm(datetime.datetime.utcnow().timetuple()) for filename, content in collection: content_type, encoding = mimetypes.guess_type(filename) content = content_types.get(content_type).format(content, **params) content = content_encodings.get(encoding).encode(content) member_content = io.BytesIO(content) member_info = tarfile.TarInfo(filename) member_info.size = len(content) member_info.mode = mode member_info.mtime = now tar.addfile(member_info, member_content) binary.seek(0) return binary.read()
<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(tzid): """Return timezone data"""
ns = {} path = os.path.join(DATA_DIR, tzid) with open(path) as f: raw_data = f.read() exec(raw_data, ns, ns) z = ZoneData() z.types = [(delta(offset), delta(save), abbr) for offset, save, abbr in ns['types']] z.times = [(datetime(*time), i) for time, i in ns['times']] z.rules = ns['posix'] return z
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login_required(method): """A decorator that control if a user is logged."""
def wrapper(self, *arg, **karg): if not self.user: if self.request.method == "GET": self.redirect(settings.LOGIN_PATH) else: self.error(403) else: method(self, *arg, **karg) 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 pointcut(self, value): """Change of pointcut. """
pointcut = getattr(self, Interceptor.POINTCUT) # for all targets for target in self.targets: # unweave old advices unweave(target, pointcut=pointcut, advices=self.intercepts) # weave new advices with new pointcut weave(target, pointcut=value, advices=self.intercepts) # and save new pointcut setattr(self, Interceptor._POINTCUT, 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 _bind_target(self, target, ctx=None, *args, **kwargs): """Weave self.intercepts among target advices with pointcut."""
result = super(Interceptor, self)._bind_target( target=target, ctx=ctx, *args, **kwargs ) pointcut = getattr(self, Interceptor.POINTCUT) weave(result, pointcut=pointcut, advices=self.intercepts, ctx=ctx) 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 intercepts(self, joinpoint): """Self target interception if self is enabled :param joinpoint: advices executor """
result = None if self.enable: interception = getattr(self, Interceptor.INTERCEPTION) joinpoint.exec_ctx[Interceptor.INTERCEPTION] = self result = interception(joinpoint) else: result = joinpoint.proceed() 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 create_token(user): """ Create token. """
payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ) # Return values token = jwt_encode_handler(payload) return token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onepara(R): """Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : ndarray DxD matrix with +1 as diagonal elements and 1 common coefficient for all other relations. """
import numpy as np import warnings d = R.shape[0] if d < 2: raise Exception(( "More than one variable is required." "Supply at least a 2x2 matrix.")) # the explicit solution x = (np.sum(R) + np.trace(R)) / (d**2 - d) if x < (-1. / (d - 1)) or x > 1: warnings.warn("No analytic solution found x={:.8f}".format(x)) return None else: C = np.eye(d) C[np.logical_not(C)] = x return 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 _load_rules(self): """ Loads the rules from the SSH-Connection """
with self._sftp_connection.open(self.RULE_PATH) as file: data = file.read() lines = ( line.strip() for line in data.split('\n') ) rule_strings = ( line for line in lines if len(line) > 0 ) rules = ( Rule.parse(rule_string) for rule_string in rule_strings ) self._rules = [ rule for rule in rules if rule is not 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 _exec_command(self, command: str): """ Executes the command and closes the handles afterwards. """
stdin, stdout, stderr = self._ssh.exec_command(command) # Clearing the buffers stdout.read() stderr.read() stdin.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(self, rules: list): """ Synchronizes the given rules with the server and ensures that there are no old rules active which are not in the given list. """
self._reset() old_rules = self.rules to_delete_rules = [ rule for rule in old_rules if rule not in rules ] new_rules = [ rule for rule in rules if rule not in old_rules ] for new_rule in new_rules: assert isinstance(new_rule, Rule) self._exec_command(new_rule.add_command) for to_delete_rule in to_delete_rules: assert isinstance(to_delete_rule, Rule) self._exec_command( to_delete_rule.remove_command ) self._update(rules)
<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(self, rules: list): """ Updates the given rules and stores them on the router. """
self._rules = rules to_store = '\n'.join( rule.config_string for rule in rules ) sftp_connection = self._sftp_connection with sftp_connection.open(self.RULE_PATH, mode='w') as file_handle: file_handle.write(to_store)
<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(self, sp_args, line, rl_prefix, rl_begidx, rl_endidx): """ Override in order to have command or argument completion. It is necessary to return a 'list', i.e. not a tuple or other sequences. """
# TODO: Optionally check that flags are not repeated (i.e. exclude # them from the possible matches if they are already in the # command line) # TODO: Support groups of mutually-exclusive flags, i.e. if one is # already present, the others in the group are not accepted if len(sp_args) == 0 or not line.endswith(sp_args[-1]): # if line.endswith(sp_args[-1]) is False, it means that the last # sp_args is already complete return self.accepted_flags else: matches = [] for arg in self.accepted_flags: if arg.startswith(sp_args[-1]): matches.append(arg) if len(matches) == 1: # In general, SPLIT_ARGS and readline use different word # delimiters, see e.g. the docs for # readline.get_completer_delims() # If for example there's a 'foo-bar' argument, SPLIT_ARGS sees # it as a single word, but readline by default will split it # in two words, 'foo' and 'bar', and if 'foo-b' is entered in # the command line, and Tab is pressed, the word will be # completed as 'foo-bfoo-bar', unless we compensate here by # subtracting the rl_prefix from the found match sub = len(sp_args[-1]) - len(rl_prefix) return [matches[0][sub:]] else: return matches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def local_address(self): """ Local endpoint address as a tuple """
if not self._local_address: self._local_address = self.proto.reader._transport.get_extra_info('sockname') if len(self._local_address) == 4: self._local_address = self._local_address[:2] return self._local_address
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peer_address(self): """ Peer endpoint address as a tuple """
if not self._peer_address: self._peer_address = self.proto.reader._transport.get_extra_info('peername') if len(self._peer_address) == 4: self._peer_address = self._peer_address[:2] return self._peer_address
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def argument_switch_generator(argument_name=None, default=True, reverse=False, keep=False): """ Create switch function which return the status from specified named argument Parameters argument_name : string or None An argument name which is used to judge the status. If ``None`` is specified, the value of ``tolerance.utils.DEFAULT_ARGUMENT_NAME`` will be used instead. default : boolean A default value of this switch function. It is used when specifid ``**kwargs`` does not have named argument reverse : boolean Reverse the status (Default: ``False``) keep : boolean If it is ``True``, keep named argument in ``**kwargs``. Returns ------- function A switch function which return status, args, and kwargs respectively. Examples -------- True True True True True True True True """
def switch_function(*args, **kwargs): if argument_name in kwargs: if keep: status = kwargs.get(argument_name) else: status = kwargs.pop(argument_name) if reverse: status = not status else: status = default return bool(status), args, kwargs if argument_name is None: argument_name = DEFAULT_ARGUMENT_NAME return switch_function
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def command_line(): ''' Parses users command line arguments and returns the namespace containing parsed values. ''' description = 'Kan helps you find the book' version = ' '.join([__version__, __release__]) parser = ArgumentParser(prog='kan', description=description) subparser = parser.add_subparsers(help='Search by') by_title = subparser.add_parser('title', help='Book title',) by_title.add_argument('title', help='Book name') by_isbn = subparser.add_parser('isbn', help='ISBN code') by_isbn.add_argument('code', help='Valid ISBN code') by_author = subparser.add_parser('author', help='Book author') by_author.add_argument('author', help='Authors name') by_author.add_argument('--recent', help='Search by most recent', action='store_true') by_author.add_argument('--top', help='Search by best selling', action='store_true') # Main Parser parser.add_argument( '-v', '--version', action='version', version="%s v%s" % ('kan', version), ) parser.add_argument( '--title', help='Title of the book', metavar='name', ) parser.add_argument( '--author', default=None, metavar='name', help='Name of the author', ) parser.add_argument( '--subject', type=str, help='Specify subject matter by category', metavar='topic', ) parser.add_argument( '--max', type=int, metavar='n', default=3, choices=range(41), help='Maximum results to get per query: default=3, max=40', ) parser.add_argument( '--language', type=str, metavar='code', default='', help='Restrict the search results to those with a certain language code', ) parser.add_argument( '--verbose', action='store_true', help='Print out debug information', ) return parser.parse_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 convert(input_format, output_format, b64_data): """ Convert `b64_data` fron `input_format` to `output_format`. Args: input_format (str): Specification of input format (pdf/epub/whatever), see :attr:`INPUT_FORMATS` for list. output_format (str): Specification of output format (pdf/epub/..), see :attr:`OUTPUT_FORMATS` for list. b64_data (str): Base64 encoded data. Returns: ConversionResponse: `namedtuple` structure with information about \ output ``format``, data (``b64_data``) and \ ``protocol`` from conversion. Structure is defined\ in :class:`.ConversionResponse`. Raises: AssertionError: When bad arguments are handed over. UserWarning: When conversion failed. """
# checks assert input_format in INPUT_FORMATS, "Unsupported input format!" assert output_format in OUTPUT_FORMATS, "Unsupported output format!" with NTFile(mode="wb", suffix="." + input_format, dir="/tmp") as ifile: ofilename = ifile.name + "." + output_format # save received data to the temporary file ifile.write(b64decode(b64_data)) ifile.flush() # free memory from base64 data b64_data = None gc.collect() # convert file protocol = "" try: with NTFile(mode="wb", suffix = ".stdout", dir="/tmp") as stdout: sh.ebook_convert(ifile.name, ofilename, _out=stdout).wait() stdout.flush() protocol = open(stdout.name).read() stdout.close() except sh.ErrorReturnCode_1, e: raise UserWarning( "Conversion failed:\n" + e.message.encode("utf-8", errors='ignore') ) if output_format.upper() + " output written to" not in protocol: raise UserWarning("Conversion failed:\n" + protocol) # read the data from the converted file output_data = None with open(ofilename, "rb") as ofile: output_data = _wrap( b64encode(ofile.read()) ) gc.collect() # we have experienced unplesant memory spikes # remove temporary output file os.remove(ofilename) return ConversionResponse( format=output_format, b64_data=output_data, protocol=protocol )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_sms(self, frm, to, text): """Sends a simple text message. Example usage:: :arg frm: The `from` field, a phone number (international format with or without a leading "+" or alphanumerical). :arg to: The `to` field, a phone number, same format as the `frm` argument. :arg text: The message body. See :meth:`send_request` for return value and exceptions. """
frm = re.sub('[^\d]', '', frm) to = re.sub('[^\d]', '', to) api_url = '%s/sms/json' % API_ENDPOINT params = { 'api_key': self.api_key, 'api_secret': self.api_secret, 'from': frm, 'to': to, 'text': text, } return self.send_request(api_url, params, method='POST')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(self, url, params, method='GET'): """Sends a raw request to the given api endpoint. :arg url: A Nexmpo api endpoint (json only) :arg params: A parameter dictionnary Returns a :class:`~libnexmo.NexmoResponse`. Raises: The library uses `Requests <http://docs.python-requests.org/en/latest/>`_ to perform http requests. `Requests exceptions <http://docs.python-requests.org/en/latest/api/#requests.exceptions.RequestException>`_ won't be caught in case of connection error. Any :class:`~libnexmo.exceptions.NexmoError` subclass. """
method = method.lower() if method not in ['get', 'post']: raise ValueError('The `method` parameter must be either `get` or `post`') response = requests.request(method, url, data=params) response_json = response.json() status = int(response_json['messages'][0]['status']) if status != 0: ErrorClass = status_to_error(status) error = response_json['messages'][0]['error-text'] raise ErrorClass(error) return NexmoResponse(response_json)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenise(string, strict=False, replace=False, diphtongs=False, tones=False, unknown=False, merge=None): """ Tokenise an IPA string into a list of tokens. Raise ValueError if there is a problem; if strict=True, this includes the string not being compliant to the IPA spec. If replace=True, replace some common non-IPA symbols with their IPA counterparts. If diphtongs=True, try to group diphtongs into single tokens. If tones=True, do not ignore tone symbols. If unknown=True, do not ignore symbols that cannot be classified into a relevant category. If merge is not None, use it for within-word token grouping. Part of ipatok's public API. """
words = string.strip().replace('_', ' ').split() output = [] for word in words: tokens = tokenise_word(word, strict, replace, tones, unknown) if diphtongs: tokens = group(are_diphtong, tokens) if merge is not None: tokens = group(merge, tokens) output.extend(tokens) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verify_server_core(timeout=120, start_delay=90): ''' checks to see if the server_core is running args: delay: will cycle till core is up. timeout: number of seconds to wait ''' timestamp = time.time() last_check = time.time() + start_delay - 10 last_delay_notification = time.time() - 10 server_down = True return_val = False timeout += 1 # loop until the server is up or the timeout is reached while((time.time()-timestamp) < timeout) and server_down: # if delaying, the start of the check, print waiting to start if start_delay > 0 and time.time() - timestamp < start_delay \ and (time.time()-last_delay_notification) > 5: print("Delaying server status check until %ss. Current time: %ss" \ % (start_delay, int(time.time() - timestamp))) last_delay_notification = time.time() # send a request check every 10s until the server is up while ((time.time()-last_check) > 10) and server_down: print("Checking status of servers at %ss" % \ int((time.time()-timestamp))) last_check = time.time() try: repo = requests.get(CFG.REPOSITORY_URL) repo_code = repo.status_code print ("\t", CFG.REPOSITORY_URL, " - ", repo_code) except: repo_code = 400 print ("\t", CFG.REPOSITORY_URL, " - DOWN") try: triple = requests.get(CFG.DATA_TRIPLESTORE.url) triple_code = triple.status_code print ("\t", CFG.DATA_TRIPLESTORE.url, " - ", triple_code) except: triple_code = 400 print ("\t", CFG.DATA_TRIPLESTORE.url, " - down") if repo_code == 200 and triple_code == 200: server_down = False return_val = True print("**** Servers up at %ss" % \ int((time.time()-timestamp))) break return 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 load_rml(self, rml_name): """ loads an rml mapping into memory args: rml_name(str): the name of the rml file """
conn = CFG.rml_tstore cache_path = os.path.join(CFG.CACHE_DATA_PATH, 'rml_files', rml_name) if not os.path.exists(cache_path): results = get_graph(NSM.uri(getattr(NSM.kdr, rml_name), False), conn) with open(cache_path, "w") as file_obj: file_obj.write(json.dumps(results, indent=4)) else: results = json.loads(open(cache_path).read()) self.rml[rml_name] = RdfDataset(results) return self.rml[rml_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 get_rml(self, rml_name): """ returns the rml mapping RdfDataset rml_name(str): Name of the rml mapping to retrieve """
try: return getattr(self, rml_name) except AttributeError: return self.load_rml(rml_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 _set_data_filelist(self, start_path, attr_name, conn, file_exts=[], dir_filter=set()): ''' does a directory search for data files ''' def filter_path(filter_terms, dir_path): """ sees if any of the terms are present in the path if so returns True args: filter_terms(list): terms to check dir_path: the path of the directory """
if filter_terms.intersection(set(dir_path.split(os.path.sep))): return True else: return False data_obj = {} files_dict = {} latest_mod = 0 dir_filter = set(dir_filter) for root, dirnames, filenames in os.walk(start_path): if not dir_filter or filter_path(dir_filter, root): if file_exts: filenames = [x for x in filenames if x.split('.')[-1].lower() in file_exts] files_dict[root] = filenames for def_file in filenames: file_mod = os.path.getmtime(os.path.join(root,def_file)) if file_mod > latest_mod: latest_mod = file_mod data_obj['latest_mod'] = latest_mod data_obj['files'] = files_dict json_mod = 0 cache_path = os.path.join(CFG.CACHE_DATA_PATH, attr_name) if cache_path: for root, dirnames, filenames in os.walk(cache_path): for json_file in filenames: file_mod = os.path.getmtime(os.path.join(root,json_file)) if file_mod > json_mod: json_mod = file_mod data_obj['last_json_mod'] = json_mod data_obj['conn'] = conn data_obj['cache_path'] = cache_path self.datafile_obj[attr_name] = data_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 authenticate(self, request): """ Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`. """
jwt_value = self.get_jwt_value(request) if jwt_value is None: return None try: payload = jwt_decode_handler(jwt_value) except jwt.ExpiredSignature: msg = _('Signature has expired.') raise exceptions.AuthenticationFailed(msg) except jwt.DecodeError: msg = _('Error decoding signature.') raise exceptions.AuthenticationFailed(msg) except jwt.InvalidTokenError: raise exceptions.AuthenticationFailed() user = self.authenticate_credentials(payload) return (user, jwt_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 to_ascii_hex(value: int, digits: int) -> str: """Converts an int value to ASCII hex, as used by LifeSOS. Unlike regular hex, it uses the first 6 characters that follow numerics on the ASCII table instead of A - F."""
if digits < 1: return '' text = '' for _ in range(0, digits): text = chr(ord('0') + (value % 0x10)) + text value //= 0x10 return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any: """ Ensures the specified object is serializable, converting if necessary. :param obj: the object to use. :param on_filter: optional function that can be used to filter which properties on the object will be included. :return value representing the object, which is serializable. """
# Will be called recursively when object has children def _serializable(parent_obj: Any, obj: Any, on_filter: Callable[[Any, str], bool]) -> Any: # None can be left as-is if obj is None: return obj # IntFlag enums should be broken down to a list of names elif isinstance(obj, IntFlag): value = str(obj) if value == '0': return None return value.split('|') # Any other enum just use the name elif isinstance(obj, Enum): return str(obj) # Simple types can be left as-is elif isinstance(obj, (bool, int, float, str)): return obj # Class supports method to convert to serializable dictionary; use it elif hasattr(obj, 'as_dict') and parent_obj is not None: return obj.as_dict() elif isinstance(obj, dict): # Dictionaries will require us to check each key and value new_dict = {} for item in obj.items(): new_dict[_serializable(obj, item[0], on_filter=on_filter)] = \ _serializable(obj, item[1], on_filter=on_filter) return new_dict elif isinstance(obj, (list, Container)): # Lists will require us to check each item items = obj # type: Iterable new_list = [] for item in items: new_list.append(_serializable(obj, item, on_filter=on_filter)) return new_list # Convert to a dictionary of property name/values data = {} for name in dir(obj.__class__): if not isinstance(getattr(obj.__class__, name), property): continue elif on_filter and not on_filter(obj, name): continue value = getattr(obj, name) data[name] = _serializable(obj, value, on_filter=on_filter) return data return _serializable(None, obj, on_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 encode_value_using_ma(message_attribute: int, value: Optional[Union[int, float]]) -> int: """Encode special sensor value using the message attribute."""
if message_attribute == MA_TX3AC_100A: # TX-3AC in 100A mode; use value as-is, with 0xFE indicating null if value is None: return 0xfe return int(value) elif message_attribute == MA_TX3AC_10A: # TX-3AC in 10A mode; shift decimal point, with 0xFE indicating null if value is None: return 0xfe return int(value * 10) else: # Signed byte, with 0x80 indicating null if value is None: return 0x80 elif value < 0: return 0x100 + int(value) return int(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 partial_schema(schema, filtered_fields): """ Validator for part of a schema, ignoring some fields :param schema: the Schema :param filtered_fields: fields to filter out """
return Schema({ k: v for k, v in schema.schema.items() if getattr(k, 'schema', k) not in filtered_fields }, extra=ALLOW_EXTRA)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_url(url): """Validate URL is valid NOTE: only support http & https """
schemes = ['http', 'https'] netloc_re = re.compile( r'^' r'(?:\S+(?::\S*)?@)?' # user:pass auth r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])' r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9]))*' # host r'(?::[0-9]{2,5})?' # port r'$', re.IGNORECASE ) try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: raise Invalid('Invalid URL') if scheme not in schemes: raise Invalid('Missing URL scheme') if not netloc_re.search(netloc): raise Invalid('Invalid URL') return 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 validate_reference_links(reference_links): """ Vaidate reference links data structure Expected data structure: { "links": { id_type1: url1, id_type2: url2 }, "redirect_id_type": id_type1 | id1_type2 } where links is an optional key but must be a dictionary with id types to URLs if it exists, and redirect_id_type is optional but if it exists, it must point to one of the existing id types in the links object. It is used to set a default redirect URL that is used by the resolution service. """
allowed_keys = ['links', 'redirect_id_type'] if not isinstance(reference_links, dict): raise Invalid('Expected reference_links to be an object') if 'links' in reference_links and not isinstance(reference_links['links'], dict): raise Invalid('Expected links in reference_links to be an object') links = reference_links.get('links', {}) redirect_id_type = reference_links.get('redirect_id_type') for key in reference_links: if key not in allowed_keys: raise Invalid('Key {} is not allowed'.format(key)) if redirect_id_type and redirect_id_type not in links: raise Invalid('Redirect ID type must point to one of the links\' ID types') [validate_url(url) for url in links.values()] return reference_links
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_state(state, valid_states): """Validate a state string"""
if state in State: return state.name elif state in valid_states: return state else: raise Invalid('Invalid state')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_filelike(ob): """Check for filelikeness of an object. Needed to distinguish it from file names. Returns true if it has a read or a write method. """
if hasattr(ob, 'read') and callable(ob.read): return True if hasattr(ob, 'write') and callable(ob.write): return True 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 dump_engines(target=sys.stderr): """Print successfully imported templating engines."""
print("Available templating engines:", file=target) width = max(len(engine) for engine in engines.engines) for handle, engine in sorted(engines.engines.items()): description = engine.__doc__.split('\n', 0)[0] print(" %-*s - %s" % (width, handle, description), file=target)
<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_engine(handle): """Check availability of requested template engine."""
if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engines: print('Engine "%s" is not available.' % (handle,), file=sys.stderr) sys.exit(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 make_mapping(args): """Make a mapping from the name=value pairs."""
mapping = {} if args: for arg in args: name_value = arg.split('=', 1) mapping[name_value[0]] = (name_value[1] if len(name_value) > 1 else None) return mapping
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_path_properties(file_or_path, prefix=''): """Build useful properties from a file path."""
is_std = file_or_path in (sys.stdin, sys.stdout, sys.stderr) if is_std: path = '-' elif is_filelike(file_or_path): try: path = str(file_or_path.name) except AttributeError: path = None else: path = str(file_or_path) if is_std or not path: abspath = dirname = basename = stem = ext = None realpath = realdrive = realdir = realbase = realstem = realext = None numbers = num = None else: abspath = os.path.abspath(path) dirname, basename = os.path.split(path) stem, ext = os.path.splitext(basename) if not dirname: dirname = os.curdir realpath = os.path.realpath(path) realdrive, tail = os.path.splitdrive(realpath) realdir, realbase = os.path.split(tail) realstem, realext = os.path.splitext(realbase) numbers = [int(s) for s in re.findall(r'\d+', basename)] num = numbers[-1] if numbers else None return { prefix + 'path': path, prefix + 'abspath': abspath, prefix + 'dirname': dirname, prefix + 'basename': basename, prefix + 'stem': stem, prefix + 'ext': ext, prefix + 'realpath': realpath, prefix + 'realdrive': realdrive, prefix + 'realdir': realdir, prefix + 'realbase': realbase, prefix + 'realstem': realstem, prefix + 'realext': realext, prefix + 'numbers': numbers, prefix + 'num': num, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constant_outfile_iterator(outfiles, infiles, arggroups): """Iterate over all output files."""
assert len(infiles) == 1 assert len(arggroups) == 1 return ((outfile, infiles[0], arggroups[0]) for outfile in outfiles)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variable_outfile_iterator(outfiles, infiles, arggroups, engine): """Iterate over variable output file name template."""
assert len(outfiles) == 1 template = engine(outfiles[0], tolerant=False) for infile in infiles: properties = make_path_properties(infile, prefix='') for arggroup in arggroups: outfile = template.apply(dict(arggroup, **properties)) yield (outfile, infile, arggroup)
<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_combinations(combinations, engine, tolerant=False, read_old=False, delete_empty=False, ): """Process outfile-infile-arggroup combinations."""
outfiles = set() templatereader = CachedTemplateReader(engine, tolerant=tolerant) for outfile, infile, arggroup in combinations: template = templatereader.read(infile) properties = make_path_properties(outfile, prefix='ez_') if read_old: if is_filelike(outfile): raise Exception("cannot read already open output streams") try: with open(outfile, 'r') as f: properties['ez_content'] = f.read() except IOError: properties['ez_content'] = None result = template.apply(dict(arggroup, **properties)) if is_filelike(outfile): if result: outfile.write(result) elif result or not delete_empty: if outfile in outfiles: raise IOError("trying to write twice to the same file") outfiles.add(outfile) with open(outfile, 'w') as f: f.write(result) else: try: os.remove(outfile) except OSError as e: if e.errno != errno.ENOENT: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform_templating(args): """Perform templating according to the given arguments."""
engine = engines.engines[args.engine] if args.vary: it = variable_outfile_iterator(args.outfiles, args.infiles, args.args, engine) else: it = constant_outfile_iterator(args.outfiles, args.infiles, args.args) process_combinations(it, engine, tolerant=args.tolerant, read_old=args.read_old, delete_empty=args.delete_empty, )
<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(self, file_or_path): """Read template from cache or file."""
if file_or_path in self._cached_templates: return self._cached_templates[file_or_path] if is_filelike(file_or_path): template = file_or_path.read() dirname = None else: with open(file_or_path, 'r') as f: template = f.read() dirname = os.path.dirname(file_or_path) template = self._engine(template, dirname=dirname, tolerant=self._tolerant) self._cached_templates[file_or_path] = template return template
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(cli_args=None, config_path=None): """ Perform standard setup - get the merged config :param cli_args dict: A dictionary of CLI arguments :param config_path string: Path to the config file to load :return dict: A dictionary of config values drawn from different sources """
config = Config(app_name="MYAPP", cli_args=cli_args, config_path=config_path) config_dict = config.get_config() return config_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 parse_interval(interval): """ Attepmt to parse an ISO8601 formatted ``interval``. Returns a tuple of ``datetime.datetime`` and ``datetime.timedelta`` objects, order dependent on ``interval``. """
a, b = str(interval).upper().strip().split('/') if a[0] is 'P' and b[0] is 'P': raise ParseError() if a[0] != 'P' and b[0] != 'P': return parse_date(a), parse_date(b) if a[0] is 'P': a = parse_duration(a) else: a = parse_date(a) if b[0] is 'P': b = parse_duration(b) else: b = parse_date(b) return a, b
<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, shell=False, ignore_errors=False, stdin=False, check_output=False): """Run subcommand. Args: shell (Optional[bool]): Run command using shell (default False) ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default False) stdin (Optional[bool]): Plug input from stdin when running command (default False) check_output (Optional[bool]): Return command output as string (default False) Returns: String if check_output is True, else None. Raises: subprocess.CalledProcessError when the command has an error, unless ignore_errors is True. """
previous_directory = os.getcwd() os.chdir(self.directory) try: kwargs = { 'stderr': sys.stderr, 'stdin': sys.stdin if stdin else None, 'env': self.env_vars, 'shell': shell, } if check_output: return subprocess.check_output(self.command, **kwargs).decode("utf8") else: kwargs['stdout'] = sys.stdout return subprocess.check_call(self.command, **kwargs) except subprocess.CalledProcessError: if ignore_errors: pass else: raise # Return to previous directory os.chdir(previous_directory)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subcommand(self, *args): """Get subcommand acting on a service. Subcommand will run in service directory and with the environment variables used to run the service itself. Args: *args: Arguments to run command (e.g. "redis-cli", "-n", "1") Returns: Subcommand object. """
return Subcommand(*args, directory=self.directory, env_vars=self.env_vars)
<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_error(self, e): """ Rather than allowing unmanaged exceptions to explode, or raising errors within thread, the worker thread should call this function with an error class or instance. """
self.result = (False, e) self._lock.release()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrapper(self): """ Wraps around a few calls which need to be made in the same thread. """
try: res = self.func(*self.args, **self.kw) except Exception as e: self.mediator.set_error(e) else: self.mediator.set_result(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 addinterval(instr, add, interval): ''' adds string every n character. returns string ''' if not isinstance(instr, str): instr = str(instr) return add.join( instr[i:i+interval] for i in xrange(0,len(instr),interval))
<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_ok(l1, l3): ''' parse html when siren is ok ''' return { 'annee': l1.text.split(' : ')[1].split()[2], 'siren valide': ''.join( l1.text.split(' : ')[1].split(u'\xab')[0].split()[-4:-1]), 'categorie': ' '.join( l1.text.split(' : ')[1].split(u'\xab')[1].split()[:-1]), 'raison sociale': l3.text.split(' : ')[1][:-1], 'statut': 'ok'}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_states(states, sort_list): """ Returns a list of sorted states, original states list remains unsorted The sort list is a list of state field: field key pairs For example (as YAML): - data: position - meta: created_at The field_key part can be a list to simplify input - meta: created_at - meta: updated_at or - meta: - created_at - updated_at It is also possible to sort by grouping values For example, with a grouping called student_id: - groupings: - student_id: index: !!null (optional: when null or missing it uses the first group in the grouping values: - meta: student_id A key which begins with a - inverts the sort, so - -data: position is the inverse of - data: position With groupings only values can have a - to invert the sort (always on the key) - groupings: - student_id: index: !!null values: - -meta: student_id NOT """
sorted_states= states.copy() for sort_pair in reversed( _convert_list_of_dict_to_tuple(sort_list) ): if sort_pair[0].lstrip('-') in ['data','measure','meta']: sorted_states= _state_value_sort(sorted_states, sort_pair, _state_key_function) elif sort_pair[0] == 'groupings': for grouping in reversed(sort_pair[1]): sorted_states= _groupings_values_sort(sorted_states, grouping) return sorted_states
<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_class(alias): """ Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_class} or L{register_package}. 2. Checks all functions registered via L{register_class_loader}. 3. Attempts to load the class via standard module loading techniques. @param alias: The class name. @type alias: C{string} @raise UnknownClassAlias: The C{alias} was not found. @raise TypeError: Expecting class type or L{ClassAlias} from loader. @return: Class registered to the alias. @rtype: C{classobj} """
# Try the CLASS_CACHE first try: return CLASS_CACHE[alias] except KeyError: pass for loader in CLASS_LOADERS: klass = loader(alias) if klass is None: continue if isinstance(klass, python.class_types): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[klass.alias] = klass CLASS_CACHE[klass.klass] = klass return klass raise TypeError("Expecting class object or ClassAlias from loader") mod_class = alias.split('.') if mod_class: module = '.'.join(mod_class[:-1]) klass = mod_class[-1] try: module = util.get_module(module) except (ImportError, AttributeError): pass else: klass = getattr(module, klass) if isinstance(klass, python.class_types): return register_class(klass, alias) elif isinstance(klass, ClassAlias): CLASS_CACHE[klass.alias] = klass CLASS_CACHE[klass.klass] = klass return klass.klass else: raise TypeError("Expecting class type or ClassAlias from loader") # All available methods for finding the class have been exhausted raise UnknownClassAlias("Unknown alias for %r" % (alias,))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(stream, *args, **kwargs): """ A generator function to decode a datastream. @param stream: AMF data to be decoded. @type stream: byte data. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A generator that will decode each element in the stream. """
encoding = kwargs.pop('encoding', DEFAULT_ENCODING) decoder = get_decoder(encoding, stream, *args, **kwargs) return decoder
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(*args, **kwargs): """ A helper function to encode an element. @param args: The python data to be encoded. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A L{util.BufferedByteStream} object that contains the data. """
encoding = kwargs.pop('encoding', DEFAULT_ENCODING) encoder = get_encoder(encoding, **kwargs) [encoder.writeElement(el) for el in args] stream = encoder.stream stream.seek(0) return stream
<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_type(type_): """ Gets the declaration for the corresponding custom type. @raise KeyError: Unknown type. @see: L{add_type} and L{remove_type} """
if isinstance(type_, list): type_ = tuple(type_) for k, v in TYPE_MAP.iteritems(): if k == type_: return v raise KeyError("Unknown type %r" % (type_,))
<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_signature(self, base_url, payload=None): """ Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before creating the signature or receiver won't be able to re-create it. :param base_url: The url you'll using for your request. :param payload: The POST data that you'll be sending. """
url = urlparse(base_url) url_to_sign = "{path}?{query}".format(path=url.path, query=url.query) converted_payload = self._convert(payload) decoded_key = base64.urlsafe_b64decode(self.private_key.encode('utf-8')) signature = hmac.new(decoded_key, str.encode(url_to_sign + converted_payload), hashlib.sha256) return bytes.decode(base64.urlsafe_b64encode(signature.digest()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert(self, payload): """ Converts payload to a string. Complex objects are dumped to json """
if not isinstance(payload, six.string_types): payload = json.dumps(payload, cls=DefaultJSONEncoder, sort_keys=True) return str(payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(self, document): """Create functional data object from JSON document retrieved from database. Parameters document : JSON Json document in database Returns ------- FunctionalDataHandle Handle for functional data object """
identifier = str(document['_id']) active = document['active'] # The directory is not materilaized in database to allow moving the # base directory without having to update the database. directory = os.path.join(self.directory, identifier) timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f') properties = document['properties'] return FunctionalDataHandle(identifier, properties, directory, timestamp=timestamp, is_active=active)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_torrent(self, torrent_id): """Retrieves and parses the torrent page for a given `torrent_id`. :param torrent_id: the ID of the torrent to view :raises TorrentNotFoundError: if the torrent does not exist :returns: a :class:`TorrentPage` with a snapshot view of the torrent detail page """
params = { 'page': 'view', 'tid': torrent_id, } r = requests.get(self.base_url, params=params) content = self._get_page_content(r) # Check if the content div has any child elements if not len(content): # The "torrent not found" text in the page has some unicode junk # that we can safely ignore. text = str(content.text.encode('ascii', 'ignore')) if TORRENT_NOT_FOUND_TEXT in text: raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT) cell_td_elems = content.findall('.//td') name = cell_td_elems[3].text category_href = content\ .findall(".//td[@class='viewcategory']/a[2]")[0]\ .attrib['href'] category_value = category_href.split('cats=')[1] category = Category.lookup_category(category_value) # parse the submitter details submitter_a_elem = cell_td_elems[7].findall('a')[0] submitter_id = submitter_a_elem.attrib['href'].split('=')[1] submitter_name = submitter_a_elem.findall('span')[0].text submitter = User(submitter_id, submitter_name) tracker = cell_td_elems[11].text date_created = datetime.datetime.strptime( cell_td_elems[5].text, '%Y-%m-%d, %H:%M %Z') seeders = int(content.findall(".//span[@class='viewsn']")[0].text) leechers = int(content.findall(".//span[@class='viewln']")[0].text) downloads = int(content.findall(".//span[@class='viewdn']")[0].text) file_size = cell_td_elems[21].text # note that the tree returned by html5lib might not exactly match the # original contents of the description div description = ElementTree.tostring( content.findall(".//div[@class='viewdescription']")[0], encoding='utf8', method='html') return TorrentPage( torrent_id, name, submitter, category, tracker, date_created, seeders, leechers, downloads, file_size, description)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_torrent(self, torrent_id): """Gets the `.torrent` data for the given `torrent_id`. :param torrent_id: the ID of the torrent to download :raises TorrentNotFoundError: if the torrent does not exist :returns: :class:`Torrent` of the associated torrent """
params = { 'page': 'download', 'tid': torrent_id, } r = requests.get(self.base_url, params=params) if r.headers.get('content-type') != 'application/x-bittorrent': raise TorrentNotFoundError(TORRENT_NOT_FOUND_TEXT) torrent_data = r.content return Torrent(torrent_id, torrent_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 search(self, terms, category=Category.all_categories, page=1, sort_key=SearchSortKey.date, order_key=SearchOrderKey.descending): """Get a list of torrents that match the given search term :param terms: the `str` needle :param category: the desired :class:`Category` of the results :param page: the 1-based page to return the result :param sort_key: the :class:`SearchSortKey` of the results list :param order_key: the :class:`SearchOrderkey` of the results list :return: a :class:`SearchPage` of results """
params = { 'page': 'search', 'term': terms, 'cats': category.value, 'sort': sort_key.value, 'order': order_key.value, } r = requests.get(self.base_url, params=params) content = self._get_page_content(r) # first, get the total number of pages returned. this findall returns # two results (one from the top half of the page, one from the bottom), # so only take the first element. a_to_last_page = content.findall('.//div[@class="rightpages"]/a[2]') if not a_to_last_page: total_pages = 1 else: last_page_url = a_to_last_page[0].attrib['href'] offset = extract_url_query_parameter(last_page_url, "offset")[0] total_pages = int(offset) torrent_stubs = [] rows = (x for x in content.findall('.//table//tr') if 'tlistrow' in x.attrib.get('class', '')) for row in rows: cell_td_elems = row.findall('td') category_value = extract_url_query_parameter( cell_td_elems[0].find('a').attrib['href'], 'cats')[0] category = Category.lookup_category(category_value) torrent_id = extract_url_query_parameter( cell_td_elems[1].find('a').attrib['href'], "tid")[0] name = cell_td_elems[1].find('a').text file_size = cell_td_elems[3].text if cell_td_elems[4].text.isdigit(): seeders = int(cell_td_elems[4].text) else: seeders = None if cell_td_elems[5].text.isdigit(): leechers = int(cell_td_elems[5].text) else: leechers = None downloads = int(cell_td_elems[6].text) stub = TorrentStub(torrent_id, name, category, seeders, leechers, file_size, downloads) torrent_stubs.append(stub) return SearchResultPage( terms, category, sort_key, order_key, page, total_pages, torrent_stubs)
<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_format_pages_isbn(html_chunk): """ Parse format, number of pages and ISBN. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: tuple: (format, pages, isbn), all as string. """
ppi = get_first_content( html_chunk.find("div", {"class": "price-overflow"}) ) if not ppi: return None, None, None # all information this function should parse are at one line ppi = filter(lambda x: x.strip(), ppi.split("<br />"))[0] # parse isbn isbn = dhtmlparser.parseString(ppi) isbn = isbn.find("b") isbn = isbn[0].getContent() if isbn else None # parse pages and format pages = None book_format = None details = ppi.split("|") if len(details) >= 2: book_format = details[0].strip() pages = details[1].strip() return book_format, pages, isbn
<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_price(html_chunk): """ Parse price of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str/None: Price as string with currency or None if not found. """
price = get_first_content( html_chunk.find("div", {"class": "prices"}) ) if not price: return None # it is always in format Cena:\n150kč price = dhtmlparser.removeTags(price) price = price.split("\n")[-1] return price
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def workspaces(self, index=None): """return generator for all all workspace instances"""
c = self.centralWidget() if index is None: return (c.widget(n) for n in range(c.count())) else: return c.widget(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(func): """ Check if annotated function arguments validate according to spec """
call = PythonCall(func) @wraps(func) def decorator(*args, **kwargs): parameters = call.bind(args, kwargs) for arg_name, validator in func.__annotations__.items(): if not validator(parameters[arg_name]): raise TypeError( "Argument {!r} failed to validate".format(arg_name)) return call.apply(args, kwargs) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def expression_type(con, topx, ex): "take a BaseX descendant from sqparse2, return a type class from above" if isinstance(ex,sqparse2.Literal): if isinstance(ex.val,basestring): return STRING else: raise NotImplementedError('literal', type(ex.val)) elif isinstance(ex,sqparse2.AttrX): if ex.parent.name in con.db: # warning: what if it's not a table? what if it's aliased? return expression_type(con, topx, con.db[ex.parent.name].get_column(ex.attr.name).coltp) else: raise NotImplementedError(ex.parent) elif isinstance(ex,sqparse2.TypeX): return dict( integer=NUMBER, text=STRING, )[ex.type.lower()] else: raise NotImplementedError('unk type', type(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 call_cur(f): "decorator for opening a connection and passing a cursor to the function" @functools.wraps(f) def f2(self, *args, **kwargs): with self.withcur() as cur: return f(self, cur, *args, **kwargs) return f2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def description(self): "this is only a property so it can raise; make it an attr once it works" if self.lastx is None: return if type(self.lastx) not in (sqparse2.SelectX,sqparse2.UpdateX,sqparse2.InsertX): return if type(self.lastx) in (sqparse2.UpdateX,sqparse2.InsertX) and self.lastx.ret is None: return # at this point we know this is an operation that returns rows if type(self.lastx) in (sqparse2.UpdateX,sqparse2.InsertX): raise NotImplementedError('todo: Cursor.description for non-select') else: # select case return [description_from_colx(self.connection,self.lastx,colx) for colx in self.lastx.cols.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 partition(self, mapped_values): """Organize the mapped values by their key. Returns an unsorted sequence of tuples with a key and a sequence of values. """
partitioned_data = collections.defaultdict(list) for key, value in mapped_values: partitioned_data[key].append(value) return partitioned_data.items()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre(self, command, output_dir, kw): """ Prepare some context before install Added kwargs in ``kw`` will be accessible into paste template files """
# Build a random secret_key chars = u'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' kw['secret_key'] = ''.join([ choice(chars) for i in range(50) ]) # Paste version kw['epaster_template_name'] = u'emencia-paste-djangocms-3' kw['epaster_template_version'] = template_version
<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_mods(self, project_path, vars): """ Build the mod list to enable """
# Start with answers from interactive command mods = [var.name for var in self.vars if vars[var.name].lower() == 'yes'] mods = set(mods) # Base mods for name in self.mods_list: mods.add(name) # Conditionnal mods dependancies if 'accounts' in mods or 'contact_form' in mods: mods.add('crispy_forms') mods.add('recaptcha') return mods
<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, command, output_dir, vars): """ Do some tasks after install """
if command.simulate: return # Find the 'project/' dir in the created paste project project_path = join(getcwd(), vars['project'], 'project') # 1. Mods mods = self.get_mods(project_path, vars) # 2. Create symlinks for target, linkfile in self.get_symlinks(project_path, vars, mods): print "* Symlink TO:", target, 'INTO:', linkfile symlink(target, linkfile) # 3. Git first initialization call = Caller(vars['project']) call('git', 'init', '.') call('git', 'add', '.') call('git', 'commit', '-m', 'First commit')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iter_full_paths(path_list): """ Iterates over all paths that are in a directory and its subdirectory, returning fully-specified paths. """
for path in path_list: if not os.path.isdir(path): full_path = os.path.realpath(path) yield path else: for root, dirs, filenames in os.walk(path): for filename in filenames: full_path = os.path.realpath(os.path.join(root, filename)) yield full_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 c(self): """Caching client for not repeapting checks"""
if self._client is None: self._parse_settings() self._client = Rumetr(**self.settings) return self._client
<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_settings(self): """Gets upload options from the scrapy settings"""
if hasattr(self, 'settings'): # parse setting only one time return self.settings = { 'auth_key': self._check_required_setting('RUMETR_TOKEN'), 'developer': self._check_required_setting('RUMETR_DEVELOPER'), } self.settings.update(self._non_required_settings('RUMETR_API_HOST'))
<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_deadline(deadline): """Translate deadline date from human-acceptable format to the machine-acceptable"""
if '-' in deadline and len(deadline) == 10: return deadline if '.' in deadline and len(deadline) == 10: # russian format dd.mm.yyyy to yyyy-mm-dd dmy = deadline.split('.') if len(dmy) == 3 and all(v is not None for v in dmy): return '-'.join(reversed(dmy)) raise exceptions.RumetrUnparsableDeadline()
<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_files(the_path): """Given a path, returns whether the path has any files in it or any subfolders. Works recursively."""
the_path = Path(the_path) try: for _ in the_path.walkfiles(): return True return False except OSError as ex: if ex.errno == errno.ENOENT: # ignore return False else: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(cls, obj): """ Convert input data to tokens :type obj list|set|tuple """
tokens = {} try: token_iterator = cls.make_iterable(obj) _lang = cls.language_definition() tokens = {k: [] for k in _lang.argument_types} prev, current = None, next(token_iterator) while True: token = [None, None] arg_type = None for arg_type in _lang.argument_types: arg_start_seq = _lang.argument_types[arg_type] arg_delimiters = _lang.value_delimiters[arg_type] if prev is None and arg_start_seq is None: # just start to scan and got "default" token token[1] = current break elif arg_start_seq is None and prev[0] is None: # next default token token[1] = current break elif arg_start_seq is None and prev[0] is not None: # default token used after non-default tokens token[1] = current break elif arg_start_seq is None: # value of non-default token prev[1] = current token = None break elif current[:len(arg_start_seq)] == arg_start_seq: token[0] = current[len(arg_start_seq):] for delimiter in arg_delimiters: if delimiter == " ": continue if delimiter in token[0]: _delim = str(token[0]).partition(delimiter) token = [_delim[0], _delim[2]] break break if token: tokens[arg_type].append(token) prev, current = token, next(token_iterator) except StopIteration: return tokens
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, argv, tokenizer=DefaultTokenizer): """ Parse command line to out tree :type argv object :type tokenizer AbstractTokenizer """
args = tokenizer.tokenize(argv) _lang = tokenizer.language_definition() # # for param in self.__args: # if self._is_default_arg(param): # self.__out_tree[self.__default_arg_tag].append(param.strip()) # else: # param = param.lstrip("-").partition('=') # if len(param) == 3: # self.__parse_one_param(param) pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def action(method=None, **kwargs): """ Decorator that turns a function or controller method into an kervi action. it is possible to call the action in other kervi processes or modules. @action def my_action(p) call it via Actions["my_action"](10) @action(action_id="action_1", name="This is my action") def my_action(p) call it via Actions["action_1"](10) :Keyword Arguments: * *action_id* (``str``) -- The action_id is the id you use when you call the action. By default the action takes the name of function but you can override it with action_id. * *name* (``str``) -- Name to show in UI if the action is linked to a panel. """
def action_wrap(f): action_id = kwargs.get("action_id", f.__name__) name = kwargs.get("name", action_id) if not _is_method(f): # not "." in f.__qualname__: action = Action(f, action_id, name) Actions.add(action) return action else: qual_name = getattr(f, "__qualname__", None) owner_class = kwargs.get("controller_class", None) if owner_class: qual_name = owner_class + "." + f.__name__ if qual_name: Actions.add_unbound(qual_name, action_id, name) setattr(f, "set_interrupt", _SetInterrupt(action_id)) else: print("using upython? if yes you need to pass the name of the controller class via the controller_class parameter.") return f if method: return action_wrap(method) else: return action_wrap
<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(self, *args, **kwargs): """Copy this model element and contained elements if they exist."""
for slot in self.__slots__: attr = getattr(self, slot) if slot[0] == '_': # convert protected attribute name to public slot = slot[1:] if slot not in kwargs: kwargs[slot] = attr result = type(self)(*args, **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 update(self, other, copy=True, *args, **kwargs): """Update this element related to other element. :param other: same type than this. :param bool copy: copy other before update attributes. :param tuple args: copy args. :param dict kwargs: copy kwargs. :return: this"""
if other: # dirty hack for python2.6 if isinstance(other, self.__class__): if copy: other = other.copy(*args, **kwargs) for slot in other.__slots__: attr = getattr(other, slot) if attr is not None: setattr(self, slot, attr) else: raise TypeError( 'Wrong element to update with {0}: {1}'.format(self, other) ) return 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 __i(self, other, func): """Process input other with input func. :param ModelElement(s) other: other ModelElement(s) to process. :param func: function to apply on a ModelElement. :return: self. :raise: TypeError if other is not a ModelElement(s)."""
if isinstance(other, type(self)): other = tuple(other) elif isinstance(other, self.__contenttype__): other = (other, ) for melt in list(other): if not isinstance(melt, self.__contenttype__): raise TypeError('Wrong element {0}'.format(melt)) else: func(melt) return self