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 _get_args_to_parse(args, sys_argv): """Return the given arguments if it is not None else sys.argv if it contains something, an empty list otherwise. Args: args: argument to be parsed sys_argv: arguments of the command line i.e. sys.argv """
arguments = args if args is not None else sys_argv[1:] _LOG.debug("Parsing arguments: %s", arguments) return arguments
<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_parser_call_method(func): """Returns the method that is linked to the 'call' method of the parser Args: func: the decorated function Raises: ParseThisError if the decorated method is __init__, __init__ can only be decorated in a class decorated by parse_class """
func_name = func.__name__ parser = func.parser def inner_call(instance=None, args=None): """This is method attached to <parser>.call. Args: instance: the instance of the parser args: arguments to be parsed """ _LOG.debug("Calling %s.parser.call", func_name) # Defer this check in the method call so that __init__ can be # decorated in class decorated with parse_class if func_name == "__init__": raise ParseThisError(("To use 'create_parser' on the" "'__init__' you need to decorate the " "class with '@parse_class'")) namespace = parser.parse_args(_get_args_to_parse(args, sys.argv)) if instance is None: # If instance is None we are probably decorating a function not a # method and don't need the instance args_name = _get_args_name_from_parser(parser) return _call(func, args_name, namespace) return _call_method_from_namespace(instance, func_name, namespace) return inner_call
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_args_name_from_parser(parser): """Retrieve the name of the function argument linked to the given parser. Args: parser: a function parser """
# Retrieve the 'action' destination of the method parser i.e. its # argument name. The HelpAction is ignored. return [action.dest for action in parser._actions if not isinstance(action, argparse._HelpAction)]
<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(callable_obj, arg_names, namespace): """Actually calls the callable with the namespace parsed from the command line. Args: callable_obj: a callable object arg_names: name of the function arguments namespace: the namespace object parsed from the command line """
arguments = {arg_name: getattr(namespace, arg_name) for arg_name in arg_names} return callable_obj(**arguments)
<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_method_from_namespace(obj, method_name, namespace): """Call the method, retrieved from obj, with the correct arguments via the namespace Args: obj: any kind of object method_name: method to be called namespace: an argparse.Namespace object containing parsed command line arguments """
method = getattr(obj, method_name) method_parser = method.parser arg_names = _get_args_name_from_parser(method_parser) if method_name == "__init__": return _call(obj, arg_names, namespace) return _call(method, arg_names, namespace)
<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_url(profile, resource): """Get the URL for a resource. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource Returns: The full URL for the specified resource under the specified profile. """
repo = profile["repo"] url = GITHUB_API_BASE_URL + "repos/" + repo + "/git" + resource 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 post_merge_request(profile, payload): """Do a POST request to Github's API to merge. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. payload A dict of information to pass to Github's API as the payload for a merge request, something like this:: { "base": <base>, "head": <head>, "commit_message": <mesg>} Returns: The response returned by the ``requests`` library when it does the POST request. """
repo = profile["repo"] url = GITHUB_API_BASE_URL + "repos/" + repo + "/merges" headers = get_headers(profile) response = requests.post(url, json=payload, headers=headers) return response
<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_request(profile, resource): """Do a GET request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource Returns: The body of the response, converted from JSON into a Python dict. """
url = get_url(profile, resource) headers = get_headers(profile) response = requests.get(url, headers=headers) return 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 post_request(profile, resource, payload): """Do a POST request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource payload A dict of values to send as the payload of the POST request. The data will be JSON-encoded. Returns: The body of the response, converted from JSON into a Python dict. """
url = get_url(profile, resource) headers = get_headers(profile) response = requests.post(url, json=payload, headers=headers) return 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 delete_request(profile, resource): """Do a DELETE request to Github's API. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. resource Returns: The response returned by the ``requests`` library when it does the POST request. """
url = get_url(profile, resource) headers = get_headers(profile) return requests.delete(url, headers=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_updater(self): """ Get the update and reset the buffer. Return `None` if there is no update. """
if self._node is self._buffer: return None else: updater = (self._node, self._buffer) self._buffer = self._node return updater
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_graph(self): """ Produce a dependency graph based on a list of tasks produced by the parser. """
self._graph.add_nodes_from(self.tasks) for node1 in self._graph.nodes: for node2 in self._graph.nodes: for input_file in node1.inputs: for output_file in node2.outputs: if output_file == input_file: self._graph.add_edge(node2, node1) for order, task in enumerate(topological_sort(self._graph)): task.predecessors = self._graph.predecessors(task) task.order = order
<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_value(self, key, args, kwargs): """Get value only from mapping and possibly convert key to string."""
if (self.tolerant and not isinstance(key, basestring) and key not in kwargs): key = str(key) return kwargs[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 get_field(self, field_name, args, kwargs): """Create a special value when field missing and tolerant."""
try: obj, arg_used = super(FormatterWrapper, self).get_field( field_name, args, kwargs) except (KeyError, IndexError, AttributeError): if not self.tolerant: raise obj = MissingField(field_name) arg_used = field_name return obj, arg_used
<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_field(self, value, conversion): """When field missing, store conversion specifier."""
if isinstance(value, MissingField): if conversion is not None: value.conversion = conversion return value return super(FormatterWrapper, self).convert_field(value, conversion)
<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_field(self, value, format_spec): """When field missing, return original spec."""
if isinstance(value, MissingField): if format_spec is not None: value.format_spec = format_spec return str(value) return super(FormatterWrapper, self).format_field(value, format_spec)
<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_last_thread(self): """ Return the last modified thread """
cache_key = '_get_last_thread_cache' if not hasattr(self, cache_key): item = None res = self.thread_set.filter(visible=True).order_by('-modified')[0:1] if len(res)>0: item = res[0] setattr(self, cache_key, item) return getattr(self, cache_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 save(self, *args, **kwargs): """ Fill 'created' and 'modified' attributes on first create """
if self.created is None: self.created = tz_now() if self.modified is None: self.modified = self.created super(Thread, self).save(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_paginated_urlargs(self): """ Return url arguments to retrieve the Post in a paginated list """
position = self.get_paginated_position() if not position: return '#forum-post-{0}'.format(self.id) return '?page={0}#forum-post-{1}'.format(position, self.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 get_paginated_position(self): """ Return the Post position in the paginated list """
# If Post list is not paginated if not settings.FORUM_THREAD_DETAIL_PAGINATE: return 0 count = Post.objects.filter(thread=self.thread_id, created__lt=self.created).count() + 1 return int(math.ceil(count / float(settings.FORUM_THREAD_DETAIL_PAGINATE)))
<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(self, *args, **kwargs): """ Fill 'created' and 'modified' attributes on first create and allways update the thread's 'modified' attribute """
edited = not(self.created is None) if self.created is None: self.created = tz_now() # Update de la date de modif. du message if self.modified is None: self.modified = self.created else: self.modified = tz_now() super(Post, self).save(*args, **kwargs) # Update de la date de modif. du thread lors de la création du message if not edited: self.thread.modified = self.created self.thread.save()
<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(search="unsigned"): """ List all available plugins"""
plugins = [] for i in os.walk('/usr/lib/nagios/plugins'): for f in i[2]: plugins.append(f) return plugins
<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(plugin_name, *args, **kwargs): """ Run a specific plugin """
plugindir = nago.settings.get_option('plugin_dir') plugin = plugindir + "/" + plugin_name if not os.path.isfile(plugin): raise ValueError("Plugin %s not found" % plugin) command = [plugin] + list(args) p = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.PIPE,) stdout, stderr = p.communicate('through stdin to stdout') result = {} result['stdout'] = stdout result['stderr'] = stderr result['return_code'] = p.returncode 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_ctx(elt): """Get the right ctx related to input elt. In order to keep safe memory as much as possible, it is important to find the right context element. For example, instead of putting properties on a function at the level of an instance, it is important to save such property on the instance because the function.__dict__ is shared with instance class function, and so, if the instance is deleted from memory, the property is still present in the class memory. And so on, it is impossible to identify the right context in such case if all properties are saved with the same key in the same function which is the function. """
result = elt # by default, result is ctx # if elt is ctx and elt is a method, it is possible to find the best ctx if ismethod(elt): # get instance and class of the elt instance = get_method_self(elt) # if instance is not None, the right context is the instance if instance is not None: result = instance elif PY2: result = elt.im_class 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 free_cache(ctx, *elts): """Free properties bound to input cached elts. If empty, free the whole cache. """
for elt in elts: if isinstance(elt, Hashable): cache = __STATIC_ELEMENTS_CACHE__ else: cache = __UNHASHABLE_ELTS_CACHE__ elt = id(elt) if elt in cache: del cache[elt] if not elts: __STATIC_ELEMENTS_CACHE__.clear() __UNHASHABLE_ELTS_CACHE__.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ctx_elt_properties(elt, ctx=None, create=False): """Get elt properties related to a ctx. :param elt: property component elt. Not None methods or unhashable types. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :param bool create: create ctx elt properties if not exist. :return: dictionary of property by name embedded into ctx __dict__ or in shared __STATIC_ELEMENTS_CACHE__ or else in shared __UNHASHABLE_ELTS_CACHE__. None if no properties exists. :rtype: dict """
result = None if ctx is None: ctx = find_ctx(elt=elt) ctx_properties = None # in case of dynamic object, parse the ctx __dict__ ctx__dict__ = getattr(ctx, __DICT__, None) if ctx__dict__ is not None and isinstance(ctx__dict__, dict): # if properties exist in ctx__dict__ if __B3J0F__PROPERTIES__ in ctx__dict__: ctx_properties = ctx__dict__[__B3J0F__PROPERTIES__] elif create: # if create in worst case ctx_properties = ctx__dict__[__B3J0F__PROPERTIES__] = {} else: # in case of static object if isinstance(ctx, Hashable): # search among static elements cache = __STATIC_ELEMENTS_CACHE__ else: # or unhashable elements cache = __UNHASHABLE_ELTS_CACHE__ ctx = id(ctx) if not isinstance(elt, Hashable): elt = id(elt) # if ctx is in cache if ctx in cache: # get its properties ctx_properties = cache[ctx] elif create: # elif create, get an empty dict ctx_properties = cache[ctx] = {} # if ctx_properties is not None if ctx_properties is not None: # check if elt exist in ctx_properties if elt in ctx_properties: result = ctx_properties[elt] elif create: # create the right data if create if create: result = ctx_properties[elt] = {} 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 get_properties(elt, keys=None, ctx=None): """Get elt properties. :param elt: properties elt. Not None methods or unhashable types. :param keys: key(s) of properties to get from elt. If None, get all properties. :type keys: list or str :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of properties by elt and name. :rtype: list """
# initialize keys if str if isinstance(keys, string_types): keys = (keys,) result = _get_properties(elt, keys=keys, local=False, 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 get_property(elt, key, ctx=None): """Get elt key property. :param elt: property elt. Not None methods. :param key: property key to get from elt. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: list of property values by elt. :rtype: list """
result = [] properties = get_properties(elt=elt, ctx=ctx, keys=key) if key in properties: result = properties[key] 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 get_first_properties(elt, keys=None, ctx=None): """Get first properties related to one input key. :param elt: first property elt. Not None methods. :param list keys: property keys to get. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of first values of elt properties. """
# ensure keys is an iterable if not None if isinstance(keys, string_types): keys = (keys,) result = _get_properties(elt, keys=keys, first=True, 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 get_first_property(elt, key, default=None, ctx=None): """Get first property related to one input key. :param elt: first property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt. properties :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. """
result = default properties = _get_properties(elt, keys=(key,), ctx=ctx, first=True) # set value if key exists in properties if key in properties: result = properties[key] 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 get_local_property(elt, key, default=None, ctx=None): """Get one local property related to one input key or default value if key is not found. :param elt: local property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt properties. :param ctx: elt ctx from where get properties. Equals elt if None. It allows to get function properties related to a class or instance if related function is defined in base class. :return: dict of properties by name. :rtype: dict """
result = default local_properties = get_local_properties(elt=elt, keys=(key,), ctx=ctx) if key in local_properties: result = local_properties[key] 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 put(properties, ttl=None, ctx=None): """Decorator dedicated to put properties on an element. """
def put_on(elt): return put_properties(elt=elt, properties=properties, ttl=ttl, ctx=ctx) return put_on
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_properties(elt, keys=None, ctx=None): """Delete elt property. :param elt: properties elt to del. Not None methods. :param keys: property keys to delete from elt. If empty, delete all properties. """
# get the best context if ctx is None: ctx = find_ctx(elt=elt) elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=False) # if elt properties exist if elt_properties is not None: if keys is None: keys = list(elt_properties.keys()) else: keys = ensureiterable(keys, iterable=tuple, exclude=str) for key in keys: if key in elt_properties: del elt_properties[key] # delete property component if empty if not elt_properties: # case of dynamic object if isinstance(getattr(ctx, '__dict__', None), dict): try: if elt in ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__][elt] except TypeError: # if elt is unhashable elt = id(elt) if elt in ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__][elt] # if ctx_properties is empty, delete it if not ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__] # case of static object and hashable else: if isinstance(ctx, Hashable): cache = __STATIC_ELEMENTS_CACHE__ else: # case of static and unhashable object cache = __UNHASHABLE_ELTS_CACHE__ ctx = id(ctx) if not isinstance(elt, Hashable): elt = id(elt) # in case of static object if ctx in cache: del cache[ctx][elt] if not cache[ctx]: del cache[ctx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setdefault(elt, key, default, ctx=None): """ Get a local property and create default value if local property does not exist. :param elt: local proprety elt to get/create. Not None methods. :param str key: proprety name. :param default: property value to set if key no in local properties. :return: property value or default if property does not exist. """
result = default # get the best context if ctx is None: ctx = find_ctx(elt=elt) # get elt properties elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=True) # if key exists in elt properties if key in elt_properties: # result is elt_properties[key] result = elt_properties[key] else: # set default property value elt_properties[key] = default 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 get_jsonparsed_data(url): """Receive the content of ``url``, parse it as JSON and return the object. """
response = urlopen(url) data = response.read().decode('utf-8') return json.loads(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_corrected_stats(package, use_honeypot=True): """ Fetches statistics for `package` and then corrects them using a special honeypot. """
honeypot, __, __ = get_stats('python-bogus-project-honeypot') if not honeypot: raise RuntimeError("Could not get honeypot data") honeypot = honeypot['releases'] # Add a field used to store diff when choosing the best honey pot release # for some statistic for x in honeypot: x['diff'] = 0 stats, __, version = get_stats(package) if not stats: return # Denote release date diff and choose the honey pot release that's closest # to the one of each release releases = stats['releases'] for release in releases: # Sort by absolute difference honeypot.sort(key=lambda x: abs( (x['upload_time'] - release['upload_time']).total_seconds() )) # Multiple candidates honeypot_filtered = list(filter(lambda x: x['diff'] == honeypot[0]['diff'], honeypot)) average_downloads = sum([x['downloads'] for x in honeypot_filtered]) / len(honeypot_filtered) release['downloads'] = release['downloads'] - average_downloads # Re-calculate totals total_count = sum([x['downloads'] for x in releases]) return stats, total_count, 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 ensure_subclass(value, types): """ Ensure value is a subclass of types Traceback (most recent call last): TypeError: """
ensure_class(value) if not issubclass(value, types): raise TypeError( "expected subclass of {}, not {}".format( types, 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 ensure_instance(value, types): """ Ensure value is an instance of a certain type Traceback (most recent call last): TypeError: Traceback (most recent call last): TypeError: :attr types: Type of list of types """
if not isinstance(value, types): raise TypeError( "expected instance of {}, got {}".format( types, 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 iter_ensure_instance(iterable, types): """ Iterate over object and check each item type Traceback (most recent call last): TypeError: Traceback (most recent call last): TypeError: """
ensure_instance(iterable, Iterable) [ ensure_instance(item, types) for item in iterable ]
<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_bases(cls, *bases): """ Add bases to class False True """
assert inspect.isclass(cls), "Expected class object" for mixin in bases: assert inspect.isclass(mixin), "Expected class object for bases" new_bases = (bases + cls.__bases__) cls.__bases__ = new_bases
<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_dict_by_key(obj): """ Sort dict by its keys OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)]) """
sort_func = lambda x: x[0] return OrderedDict(sorted(obj.items(), key=sort_func))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_random_token(length=32): """ Generate random secure token 32 6 """
chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits) return ''.join(random.choice(chars) for _ in range(length))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default(*args, **kwargs): """ Return first argument which is "truthy" 1 123 None """
default = kwargs.get('default', None) for arg in args: if arg: return arg return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_int(value): """ Check if value is an int :type value: int, str, bytes, float, Decimal (True, True, True) (False, False, False) Traceback (most recent call last): TypeError: """
ensure_instance(value, (int, str, bytes, float, Decimal)) if isinstance(value, int): return True elif isinstance(value, float): return False elif isinstance(value, Decimal): return str(value).isdigit() elif isinstance(value, (str, bytes)): return value.isdigit() 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 coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'): """ Coerce value to bytes Traceback (most recent call last): TypeError: Cannot coerce to bytes """
PY2 = sys.version_info[0] == 2 if PY2: # pragma: nocover if x is None: return None if isinstance(x, (bytes, bytearray, buffer)): return bytes(x) if isinstance(x, unicode): return x.encode(charset, errors) raise TypeError('Cannot coerce to bytes') else: # pragma: nocover if x is None: return None if isinstance(x, (bytes, bytearray, memoryview)): return bytes(x) if isinstance(x, str): return x.encode(charset, errors) raise TypeError('Cannot coerce to bytes')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup(self): """Remove any created temp paths"""
for path in self.paths: if isinstance(path, tuple): os.close(path[0]) os.unlink(path[1]) else: shutil.rmtree(path) self.paths = []
<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_vertex_surrounding_multicolor(graph, vertex): """ Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present in those edges """
result = Multicolor() for edge in graph.get_edges_by_vertex(vertex): result += edge.multicolor 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 get_irregular_edge_by_vertex(graph, vertex): """ Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex """
for edge in graph.get_edges_by_vertex(vertex): if edge.is_irregular_edge: return edge return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None): """ This function actually does assembling being provided a graph, to play with a list of assembly points and a multicolor, which to assemble """
if verbose: print(">>Assembling for multicolor", [e.name for e in multicolor.multicolors.elements()], file=verbose_destination) for assembly in assemblies: v1, v2, (before, after, ex_data) = assembly iv1 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v1)) iv2 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v2)) kbreak = KBreak(start_edges=[(v1, iv1), (v2, iv2)], result_edges=[(v1, v2), (iv1, iv2)], multicolor=multicolor) if verbose: print("(", v1.name, ",", iv1.name, ")x(", v2.name, ",", iv2.name, ")", " score=", before - after, sep="", file=verbose_destination) graph.apply_kbreak(kbreak=kbreak, merge=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 error_map(func): """Wrap exceptions raised by requests. .. py:decorator:: error_map """
@six.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.RequestException as err: raise TVDBRequestException( err, response=getattr(err, 'response', None), request=getattr(err, 'request', None)) 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 create_message(username, message): """ Creates a standard message from a given user with the message Replaces newline with html break """
message = message.replace('\n', '<br/>') return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username)
<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(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """
if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, 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 _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """
if xer in primary: notifier = primary.pop(xer) notifier.shutdown()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeAll(self): """ Remove all selectables, and return a list of them. """
rv = self._removeAll(self._reads, self._writes) return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QtCore.QEventLoop.AllEvents, delay * 1000) if self.timeout() is None: timeout = 0.1 elif self.timeout() == 0: timeout = 0 else: timeout = self.timeout() self._timer.setInterval(timeout * 1000) self._timer.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addEvent(self, event, fd, action): """ Add a new win32 event to the event loop. """
self._events[event] = (fd, action)
<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_levenshtein(first, second): """\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string """
if not first: return len(second) if not second: return len(first) prev_distances = range(0, len(second) + 1) curr_distances = None # Find the minimum edit distance between each substring of 'first' and # the entirety of 'second'. The first column of each distance list is # the distance from the current string to the empty string. for first_idx, first_char in enumerate(first, start=1): # Keep only the previous and current rows of the # lookup table in memory curr_distances = [first_idx] for second_idx, second_char in enumerate(second, start=1): # Take the max of the neighbors compare = [ prev_distances[second_idx - 1], prev_distances[second_idx], curr_distances[second_idx - 1], ] distance = min(*compare) if first_char != second_char: distance += 1 curr_distances.append(distance) prev_distances = curr_distances return curr_distances[-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 all_matches(self, target, choices, group=False, include_rank=False): """\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. Otherwise, an iterator of all matches is returned. For example :: from howabout import all_matches choices = ['pot', 'cat', 'bat'] for group in all_matches('hat', choices, group=True): print(list(group)) # ['bat', 'cat'] # ['pot'] :param target: a string :param choices: a list or iterable of strings to compare with `target` string :param group: if `True`, group """
dist = self.get_distance # Keep everything here as an iterator in case we're given a lot of # choices matched = ((dist(target, choice), choice) for choice in choices) matched = sorted(matched) if group: for rank, choices in groupby(matched, key=lambda m: m[0]): yield map(lambda m: m[1], choices) else: for rank, choice in matched: yield choice
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def best_matches(self, target, choices): """\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param target: :param choices: :param group: """
all = self.all_matches try: matches = next(all(target, choices, group=True)) for match in matches: yield match except StopIteration: 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 best_match(self, target, choices): """\ Return the best match. """
all = self.all_matches try: best = next(all(target, choices, group=False)) return best except StopIteration: 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 agenerator(): """Arandom number generator"""
free_mem = psutil.virtual_memory().available mem_24 = 0.24 * free_mem mem_26 = 0.26 * free_mem a = MemEater(int(mem_24)) b = MemEater(int(mem_26)) sleep(5) return free_mem/1000/1000, psutil.virtual_memory().available/1000/1000
<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_signal(self, sig): """Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler. """
if not isinstance(sig, int): raise TypeError('sig must be an int, not {!r}'.format(sig)) if signal is None: raise RuntimeError('Signals are not supported') if not (1 <= sig < signal.NSIG): raise ValueError('sig {} out of range(1, {})'.format(sig, signal.NSIG)) if sys.platform == 'win32': raise RuntimeError('Signals are not really supported on Windows')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_version(self): """ Query the Cassandra server for the version. :returns: string -- the version tag """
def _vers(client): return client.describe_version() d = self._connection() d.addCallback(_vers) return 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 execute(self, query, args, consistency): """ Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: The arguments to substitute :type args: dict. :param consistency: The consistency level :type consistency: ConsistencyLevel In order to avoid unpleasant issues of CQL injection (Hey, just because there's no SQL doesn't mean that Little Bobby Tables won't mess things up for you like in XKCD #327) you probably want to use argument substitution instead of concatting strings together to build a query. Thus, like the official CQL driver for non-Twisted python that comes with the Cassandra distro, we do variable substitution. Example:: d = client.execute("UPDATE :table SET 'fff' = :val WHERE " "KEY = :key",{"val":1234, "key": "fff", "table": "blah"}) :returns: A Deferred that fires with either None, an int, or an on the CQL query. e.g. a UPDATE would return None, whereas a SELECT would return an int or some rows Example output:: [{"fff": 1222}] """
prep_query = prepare(query, args) def _execute(client): exec_d = client.execute_cql3_query(prep_query, ttypes.Compression.NONE, consistency) if self._disconnect_on_cancel: cancellable_d = Deferred(lambda d: self.disconnect()) exec_d.chainDeferred(cancellable_d) return cancellable_d else: return exec_d def _proc_results(result): if result.type == ttypes.CqlResultType.ROWS: return self._unmarshal_result(result.schema, result.rows, unmarshallers) elif result.type == ttypes.CqlResultType.INT: return result.num else: return None d = self._connection() d.addCallback(_execute) d.addCallback(_proc_results) return 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 getfiles(qfiles, dirname, names): """Get rule files in a directory"""
for name in names: fullname = os.path.join(dirname, name) if os.path.isfile(fullname) and \ fullname.endswith('.cf') or \ fullname.endswith('.post'): qfiles.put(fullname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_file(source, dest): """Deploy a file"""
date = datetime.utcnow().strftime('%Y-%m-%d') shandle = open(source) with open(dest, 'w') as handle: for line in shandle: if line == '# Updated: %date%\n': newline = '# Updated: %s\n' % date else: newline = line handle.write(newline) handle.flush() shandle.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 get_counter(counterfile): """Get the counter value"""
try: version_num = open(counterfile).read() version_num = int(version_num) + 1 except (ValueError, IOError): version_num = 1 create_file(counterfile, "%d" % version_num) except BaseException as msg: raise SaChannelUpdateError(msg) return version_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 update_dns(config, record, sa_version): "Update the DNS record" try: domain = config.get('domain_name', 'sa.baruwa.com.') dns_key = config.get('domain_key') dns_ip = config.get('domain_ip', '127.0.0.1') keyring = tsigkeyring.from_text({domain: dns_key}) transaction = update.Update( domain, keyring=keyring, keyalgorithm=tsig.HMAC_SHA512) txtrecord = '%s.%s' % (sa_version, domain) transaction.replace(txtrecord, 120, 'txt', record) query.tcp(transaction, dns_ip) return True except DNSException, msg: raise SaChannelUpdateDNSError(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 sign(config, s_filename): """sign the package"""
gpg_home = config.get('gpg_dir', '/var/lib/sachannelupdate/gnupg') gpg_pass = config.get('gpg_passphrase') gpg_keyid = config.get('gpg_keyid') gpg = GPG(gnupghome=gpg_home) try: plaintext = open(s_filename, 'rb') signature = gpg.sign_file( plaintext, keyid=gpg_keyid, passphrase=gpg_pass, detach=True) with open('%s.asc' % s_filename, 'wb') as handle: handle.write(str(signature)) finally: if 'plaintext' in locals(): plaintext.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 hash_file(tar_filename): """hash the file"""
hasher = sha1() with open(tar_filename, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) data = HASHTMPL % (hasher.hexdigest(), os.path.basename(tar_filename)) create_file('%s.sha1' % tar_filename, 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 upload(config, remote_loc, u_filename): """Upload the files"""
rcode = False try: sftp, transport = get_sftp_conn(config) remote_dir = get_remote_path(remote_loc) for part in ['sha1', 'asc']: local_file = '%s.%s' % (u_filename, part) remote_file = os.path.join(remote_dir, local_file) sftp.put(local_file, remote_file) sftp.put(remote_dir, os.path.join(remote_dir, u_filename)) rcode = True except BaseException: pass finally: if 'transport' in locals(): transport.close() return rcode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queue_files(dirpath, queue): """Add files in a directory to a queue"""
for root, _, files in os.walk(os.path.abspath(dirpath)): if not files: continue for filename in files: queue.put(os.path.join(root, filename))
<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_cf_files(path, queue): """Get rule files in a directory and put them in a queue"""
for root, _, files in os.walk(os.path.abspath(path)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if os.path.isfile(fullname) and fullname.endswith('.cf') or \ fullname.endswith('.post'): queue.put(fullname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup(dest, tardir, counterfile): """Remove existing rules"""
thefiles = Queue() # dest directory files queue_files(dest, thefiles) # tar directory files queue_files(tardir, thefiles) while not thefiles.empty(): d_file = thefiles.get() info("Deleting file: %s" % d_file) os.unlink(d_file) if os.path.exists(counterfile): info("Deleting the counter file %s" % counterfile) os.unlink(counterfile)
<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_required(config): """Validate the input"""
if config.get('domain_key') is None: raise CfgError("The domain_key option is required") if config.get('remote_loc') is None: raise CfgError("The remote_location option is required") if config.get('gpg_keyid') is None: raise CfgError("The gpg_keyid option is 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 _parse_result(result): """ Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( "FOUND", "Eicar-Test-Signature" ) } """
lines = filter(lambda x: x.strip(), result.splitlines()) # rm blank lines if not lines: return {} out = {} for line in lines: line = line.split(":") fn = line[0].strip() line = " ".join(line[1:]) line = line.rsplit(None, 1) status = line.pop().strip() out[fn] = (status, " ".join(line).strip()) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_file(path): """ Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: When the internal file doesn't exists. """
path = os.path.abspath(path) assert os.path.exists(path), "Unreachable file '%s'." % path result = sh.clamscan(path, no_summary=True, infected=True, _ok_code=[0, 1]) return _parse_result(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 connect(self): """Initializes a connection to the smtp server :return: True on success, False otherwise """
connection_method = 'SMTP_SSL' if self.ssl else 'SMTP' self._logger.debug('Trying to connect via {}'.format(connection_method)) smtp = getattr(smtplib, connection_method) if self.port: self._smtp = smtp(self.address, self.port) else: self._smtp = smtp(self.address) self._smtp.ehlo() if self.tls: self._smtp.starttls() self._smtp.ehlo() self._logger.info('Got smtp connection') if self.username and self.password: self._logger.info('Logging in') self._smtp.login(self.username, self.password) self._connected = 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 send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email :param sender: The server of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise """
if not self.connected: self._logger.error(('Server not connected, cannot send message, ' 'please connect() first and disconnect() when ' 'the connection is not needed any more')) return False try: message = Message(sender, recipients, cc, bcc, subject, body, attachments, content) self._smtp.sendmail(message.sender, message.recipients, message.as_string) result = True self._connected = False self._logger.debug('Done') except Exception: # noqa self._logger.exception('Something went wrong!') result = False 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 disconnect(self): """Disconnects from the remote smtp server :return: True on success, False otherwise """
if self.connected: try: self._smtp.close() self._connected = False result = True except Exception: # noqa self._logger.exception('Something went wrong!') result = False 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 send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email by connecting and disconnecting after the send :param sender: The sender of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise """
self._server.connect() self._server.send(sender, recipients, cc, bcc, subject, body, attachments, content) self._server.disconnect() 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 _setup_message(self): """Constructs the actual underlying message with provided values"""
if self.content == 'html': self._message = MIMEMultipart('alternative') part = MIMEText(self.body, 'html', 'UTF-8') else: self._message = MIMEMultipart() part = MIMEText(self.body, 'plain', 'UTF-8') self._message.preamble = 'Multipart massage.\n' self._message.attach(part) self._message['From'] = self.sender self._message['To'] = COMMASPACE.join(self.to) if self.cc: self._message['Cc'] = COMMASPACE.join(self.cc) self._message['Date'] = formatdate(localtime=True) self._message['Subject'] = self.subject for part in self._parts: self._message.attach(part)
<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_simple(email): """Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email address :raises: ValueError if value is not a valid email """
name, address = parseaddr(email) if not re.match('[^@]+@[^@]+\.[^@]+', address): raise ValueError('Invalid email :{email}'.format(email=email)) return 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 save_cache(cache): """ Save cahce to the disk. Args: cache (set): Set with cached data. """
with open(settings.DUP_FILTER_FILE, "w") as f: f.write( json.dumps(list(cache)) )
<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_cache(): """ Load cache from the disk. Return: set: Deserialized data from disk. """
if not os.path.exists(settings.DUP_FILTER_FILE): return set() with open(settings.DUP_FILTER_FILE) as f: return set( json.loads(f.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 filter_publication(publication, cache=_CACHE): """ Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which is used for lookups. Returns: obj/None: Depends whether the object is found in cache or not. """
if cache is None: cache = load_cache() if publication._get_hash() in cache: return None cache.update( [publication._get_hash()] ) save_cache(cache) return publication
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formfield(self, **kwargs): """ Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting. """
default = kwargs.get("widget", None) or AdminTextareaWidget if default is AdminTextareaWidget: from yacms.conf import settings richtext_widget_path = settings.RICHTEXT_WIDGET_CLASS try: widget_class = import_dotted_path(richtext_widget_path) except ImportError: raise ImproperlyConfigured(_("Could not import the value of " "settings.RICHTEXT_WIDGET_CLASS: " "%s" % richtext_widget_path)) kwargs["widget"] = widget_class() kwargs.setdefault("required", False) formfield = super(RichTextField, self).formfield(**kwargs) return formfield
<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(url): """Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object representing the web page """
text = urlopen(url).read() soup = BeautifulSoup(text) return Response(text=text, soup=soup)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mock_decorator(*a, **k): """ An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators. """
# This is a decorator without parameters, e.g. # # @login_required # def some_view(request): # ... # if a: # This could fail in the instance where a callable argument is passed # as a parameter to the decorator! if callable(a[0]): def wrapper(*args, **kwargs): return a[0](*args, **kwargs) return wrapper # This is a decorator with parameters, e.g. # # @render_template("index.html") # def some_view(request): # ... # def real_decorator(function): def wrapper(*args, **kwargs): return function(*args, **kwargs) return wrapper return real_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 tinsel(to_patch, module_name, decorator=mock_decorator): """ Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. By default a pass-through will be used. Returns: A wrapped test function, during the context of execution the specified path is patched. """
def fn_decorator(function): def wrapper(*args, **kwargs): with patch(to_patch, decorator): m = importlib.import_module(module_name) reload(m) function(*args, **kwargs) reload(m) return wrapper return fn_decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def anext(self): """Fetch the next value from the iterable."""
try: f = next(self._iter) except StopIteration as exc: raise StopAsyncIteration() from exc return await 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 _new_token(self, chars=None, line_no=None): """ Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no` Line number for token. Defaults to current line number. """
if not line_no: line_no = self._line_no if not chars: chars = self._token_chars if chars: # add new token self._tokens.append((line_no, ''.join(chars))) self._token_chars = []
<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_newline(self, char): """ Process a newline character. """
state = self._state # inside string, just append char to token if state == self.ST_STRING: self._token_chars.append(char) else: # otherwise, add new token self._new_token() self._line_no += 1 # update line counter # finished with comment if state == self.ST_COMMENT: self._state = self.ST_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 _process_string(self, char): """ Process a character as part of a string token. """
if char in self.QUOTES: # end of quoted string: # 1) quote must match original quote # 2) not escaped quote (e.g. "hey there" vs "hey there\") # 3) actual escape char prior (e.g. "hey there\\") if (char == self._last_quote and not self._escaped or self._double_escaped): # store token self._new_token() self._state = self.ST_TOKEN return # skip adding token char elif char == self.ESCAPE: # escape character: # double escaped if prior char was escape (e.g. "hey \\ there") if not self._double_escaped: self._double_escaped = self._escaped else: self._double_escaped = False self._token_chars.append(char)
<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_tokens(self, char): """ Process a token character. """
if (char in self.WHITESPACE or char == self.COMMENT_START or char in self.QUOTES or char in self.TOKENS): add_token = True # escaped chars, keep going if char == self.SPACE or char in self.TOKENS: if self._escaped: add_token = False # start of comment elif char == self.COMMENT_START: self._state = self.ST_COMMENT # start of quoted string elif char in self.QUOTES: if self._escaped: # escaped, keep going add_token = False else: self._state = self.ST_STRING self._last_quote = char # store for later quote matching if add_token: # store token self._new_token() if char in self.TOKENS: # store char as a new token self._new_token([char]) return # skip adding token char self._token_chars.append(char)
<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(self, stream): """ Tokenizes data from the provided string. ``stream`` ``File``-like object. """
self._tokens = [] self._reset_token() self._state = self.ST_TOKEN for chunk in iter(lambda: stream.read(8192), ''): for char in chunk: if char in self.NEWLINES: self._process_newline(char) else: state = self._state if state == self.ST_STRING: self._process_string(char) elif state == self.ST_TOKEN: self._process_tokens(char)
<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, filename): """ Reads the file specified and tokenizes the data for parsing. """
try: with open(filename, 'r') as _file: self._filename = filename self.readstream(_file) return True except IOError: self._filename = None 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 _escaped(self): """ Escape character is at end of accumulated token character list. """
chars = self._token_info['chars'] count = len(chars) # prev char is escape, keep going if count and chars[count - 1] == self.ESCAPE: chars.pop() # swallow escape char return True else: 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 checkResponse(request): ''' Returns if a request has an okay error code, otherwise raises InvalidRequest. ''' # Check the status code of the returned request if str(request.status_code)[0] not in ['2', '3']: w = str(request.text).split('\\r')[0][2:] raise InvalidRequest(w) 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 checkKey(self, key=None): ''' Checks that an API key is valid. :param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization. :returns: If the key is valid, this method will return ``True``. :rtype: `bool` :raises: :class:`brickfront.errors.InvalidApiKey` ''' # Get site url = Client.ENDPOINT.format('checkKey') if not key: key = self.apiKey params = { 'apiKey': key or self.apiKey } returned = get(url, params=params) self.checkResponse(returned) # Parse and return root = ET.fromstring(returned.text) if root.text == 'OK': return True raise InvalidApiKey('The provided API key `{}` was invalid.'.format(key))