Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def proper_case_section(self, section): # Casing for section. changed_values = False unknown_names = [k for k in section.keys() if k not in set(self.proper_names)] # Replace each package with proper casing. for dep in unknown_...
[ "Verify proper casing is retrieved, when available, for each\n dependency in the section.\n " ]
Please provide a description of the function:def native_concat(nodes): head = list(islice(nodes, 2)) if not head: return None if len(head) == 1: out = head[0] else: out = u''.join([text_type(v) for v in chain(head, nodes)]) try: return literal_eval(out) ex...
[ "Return a native Python type from the list of compiled nodes. If the\n result is a single node, its value is returned. Otherwise, the nodes are\n concatenated as strings. If the result can be parsed with\n :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the\n string is returned.\n ...
Please provide a description of the function:def visit_Output(self, node, frame): if self.has_known_extends and frame.require_output_check: return finalize = self.environment.finalize finalize_context = getattr(finalize, 'contextfunction', False) finalize_eval = get...
[ "Same as :meth:`CodeGenerator.visit_Output`, but do not call\n ``to_string`` on output nodes in generated code.\n " ]
Please provide a description of the function:def load(self, *args, **kwargs): self.clear() self.updateall(*args, **kwargs) return self
[ "\n Clear all existing key:value items and import all key:value items from\n <mapping>. If multiple values exist for the same key in <mapping>, they\n are all be imported.\n\n Example:\n omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])\n omd.load([(4,4), (4,44), (5,...
Please provide a description of the function:def updateall(self, *args, **kwargs): self._update_updateall(False, *args, **kwargs) return self
[ "\n Update this dictionary with the items from <mapping>, replacing\n existing key:value items with shared keys before adding new key:value\n items.\n\n Example:\n omd = omdict([(1,1), (2,2)])\n omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)])\n omd.alli...
Please provide a description of the function:def _bin_update_items(self, items, replace_at_most_one, replacements, leftovers): for key, value in items: # If there are existing items with key <key> that have yet to be # marked for replacement, mark that ...
[ "\n <replacements and <leftovers> are modified directly, ala pass by\n reference.\n " ]
Please provide a description of the function:def getlist(self, key, default=[]): if key in self: return [node.value for node in self._map[key]] return default
[ "\n Returns: The list of values for <key> if <key> is in the dictionary,\n else <default>. If <default> is not provided, an empty list is\n returned.\n " ]
Please provide a description of the function:def setdefaultlist(self, key, defaultlist=[None]): if key in self: return self.getlist(key) self.addlist(key, defaultlist) return defaultlist
[ "\n Similar to setdefault() except <defaultlist> is a list of values to set\n for <key>. If <key> already exists, its existing list of values is\n returned.\n\n If <key> isn't a key and <defaultlist> is an empty list, [], no values\n are added for <key> and <key> will not be added...
Please provide a description of the function:def addlist(self, key, valuelist=[]): for value in valuelist: self.add(key, value) return self
[ "\n Add the values in <valuelist> to the list of values for <key>. If <key>\n is not in the dictionary, the values in <valuelist> become the values\n for <key>.\n\n Example:\n omd = omdict([(1,1)])\n omd.addlist(1, [11, 111])\n omd.allitems() == [(1, 1), (1, 11...
Please provide a description of the function:def setlist(self, key, values): if not values and key in self: self.pop(key) else: it = zip_longest( list(self._map.get(key, [])), values, fillvalue=_absent) for node, value in it: i...
[ "\n Sets <key>'s list of values to <values>. Existing items with key <key>\n are first replaced with new values from <values>. Any remaining old\n items that haven't been replaced with new values are deleted, and any\n new values from <values> that don't have corresponding items with <ke...
Please provide a description of the function:def removevalues(self, key, values): self.setlist(key, [v for v in self.getlist(key) if v not in values]) return self
[ "\n Removes all <values> from the values of <key>. If <key> has no\n remaining values after removevalues(), the key is popped.\n\n Example:\n omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)])\n omd.removevalues(1, [1, 111])\n omd.allitems() == [(1, 11)]\n\n Ret...
Please provide a description of the function:def poplist(self, key, default=_absent): if key in self: values = self.getlist(key) del self._map[key] for node, nodekey, nodevalue in self._items: if nodekey == key: self._items.removen...
[ "\n If <key> is in the dictionary, pop it and return its list of values. If\n <key> is not in the dictionary, return <default>. KeyError is raised if\n <default> is not provided and <key> is not in the dictionary.\n\n Example:\n omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)...
Please provide a description of the function:def popitem(self, fromall=False, last=True): if not self._items: raise KeyError('popitem(): %s is empty' % self.__class__.__name__) if fromall: node = self._items[-1 if last else 0] key = node.key retu...
[ "\n Pop and return a key:value item.\n\n If <fromall> is False, items()[0] is popped if <last> is False or\n items()[-1] is popped if <last> is True. All remaining items with the\n same key are removed.\n\n If <fromall> is True, allitems()[0] is popped if <last> is False or\n ...
Please provide a description of the function:def poplistitem(self, last=True): if not self._items: s = 'poplistitem(): %s is empty' % self.__class__.__name__ raise KeyError(s) key = self.keys()[-1 if last else 0] return key, self.poplist(key)
[ "\n Pop and return a key:valuelist item comprised of a key and that key's\n list of values. If <last> is False, a key:valuelist item comprised of\n keys()[0] and its list of values is popped and returned. If <last> is\n True, a key:valuelist item comprised of keys()[-1] and its list of\n...
Please provide a description of the function:def values(self, key=_absent): if key is not _absent and key in self._map: return self.getlist(key) return list(self.itervalues())
[ "\n Raises: KeyError if <key> is provided and not in the dictionary.\n Returns: List created from itervalues(<key>).If <key> is provided and\n is a dictionary key, only values of items with key <key> are\n returned.\n " ]
Please provide a description of the function:def iteritems(self, key=_absent): if key is not _absent: if key in self: items = [(node.key, node.value) for node in self._map[key]] return iter(items) raise KeyError(key) items = six.iteritems(...
[ "\n Parity with dict.iteritems() except the optional <key> parameter has\n been added. If <key> is provided, only items with the provided key are\n iterated over. KeyError is raised if <key> is provided and not in the\n dictionary.\n\n Example:\n omd = omdict([(1,1), (1,1...
Please provide a description of the function:def itervalues(self, key=_absent): if key is not _absent: if key in self: return iter([node.value for node in self._map[key]]) raise KeyError(key) return iter([nodes[0].value for nodes in six.itervalues(self._m...
[ "\n Parity with dict.itervalues() except the optional <key> parameter has\n been added. If <key> is provided, only values from items with the\n provided key are iterated over. KeyError is raised if <key> is provided\n and not in the dictionary.\n\n Example:\n omd = omdict...
Please provide a description of the function:def iterallitems(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3) omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111) ...
[]
Please provide a description of the function:def iterallvalues(self, key=_absent): ''' Example: omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)]) omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3 Returns: An iterator over the values of every item in the dictionary. ...
[]
Please provide a description of the function:def reverse(self): for key in six.iterkeys(self._map): self._map[key].reverse() self._items.reverse() return self
[ "\n Reverse the order of all items in the dictionary.\n\n Example:\n omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])\n omd.reverse()\n omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]\n\n Returns: <self>.\n " ]
Please provide a description of the function:def check_requirements(self, reqs): # type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]] missing = set() conflicting = set() if reqs: ws = WorkingSet(self._lib_dirs) for req in reqs: ...
[ "Return 2 sets:\n - conflicting requirements: set of (installed, wanted) reqs tuples\n - missing requirements: set of reqs\n " ]
Please provide a description of the function:def _unpack_args(args, nargs_spec): args = deque(args) nargs_spec = deque(nargs_spec) rv = [] spos = None def _fetch(c): try: if spos is None: return c.popleft() else: return c.pop() ...
[ "Given an iterable of arguments and an iterable of nargs specifications,\n it returns a tuple with all the unpacked arguments at the first index\n and all remaining arguments as the second.\n\n The nargs specification is the number of arguments that should be consumed\n or `-1` to indicate that this pos...
Please provide a description of the function:def split_arg_string(string): rv = [] for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)"' r'|\S+)\s*', string, re.S): arg = match.group().strip() if arg[...
[ "Given an argument string this attempts to split it into small parts." ]
Please provide a description of the function:def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None): if obj is None: obj = dest opts = [normalize_opt(opt, self.ctx) for opt in opts] option = Option(opts, dest, action=action, nargs=nar...
[ "Adds a new option named `dest` to the parser. The destination\n is not inferred (unlike with optparse) and needs to be explicitly\n provided. Action can be any of ``store``, ``store_const``,\n ``append``, ``appnd_const`` or ``count``.\n\n The `obj` can be used to identify the option i...
Please provide a description of the function:def add_argument(self, dest, nargs=1, obj=None): if obj is None: obj = dest self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))
[ "Adds a positional argument named `dest` to the parser.\n\n The `obj` can be used to identify the option in the order list\n that is returned from the parser.\n " ]
Please provide a description of the function:def parse_args(self, args): state = ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing:...
[ "Parses positional arguments and returns ``(values, args, order)``\n for the parsed options and arguments as well as the leftover\n arguments if there are any. The order is a list of objects as they\n appear on the command line. If arguments appear multiple times they\n will be memoriz...
Please provide a description of the function:def make_graph(dists, scheme='default'): scheme = get_scheme(scheme) graph = DependencyGraph() provided = {} # maps names to lists of (version, dist) tuples # first, build the graph and find out what's provided for dist in dists: graph.add_...
[ "Makes a dependency graph from the given distributions.\n\n :parameter dists: a list of distributions\n :type dists: list of :class:`distutils2.database.InstalledDistribution` and\n :class:`distutils2.database.EggInfoDistribution` instances\n :rtype: a :class:`DependencyGraph` instance\n ...
Please provide a description of the function:def get_dependent_dists(dists, dist): if dist not in dists: raise DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) dep = [dist] # dependent distributions ...
[ "Recursively generate a list of distributions from *dists* that are\n dependent on *dist*.\n\n :param dists: a list of distributions\n :param dist: a distribution, member of *dists* for which we are interested\n " ]
Please provide a description of the function:def get_required_dists(dists, dist): if dist not in dists: raise DistlibException('given distribution %r is not a member ' 'of the list' % dist.name) graph = make_graph(dists) req = [] # required distributions tod...
[ "Recursively generate a list of distributions from *dists* that are\n required by *dist*.\n\n :param dists: a list of distributions\n :param dist: a distribution, member of *dists* for which we are interested\n " ]
Please provide a description of the function:def make_dist(name, version, **kwargs): summary = kwargs.pop('summary', 'Placeholder for summary') md = Metadata(**kwargs) md.name = name md.version = version md.summary = summary or 'Placeholder for summary' return Distribution(md)
[ "\n A convenience method for making a dist given just a name and version.\n " ]
Please provide a description of the function:def clear(self): self.name.clear() self.path.clear() self.generated = False
[ "\n Clear the cache, setting it to its initial state.\n " ]
Please provide a description of the function:def add(self, dist): if dist.path not in self.path: self.path[dist.path] = dist self.name.setdefault(dist.key, []).append(dist)
[ "\n Add a distribution to the cache.\n :param dist: The distribution to add.\n " ]
Please provide a description of the function:def _generate_cache(self): gen_dist = not self._cache.generated gen_egg = self._include_egg and not self._cache_egg.generated if gen_dist or gen_egg: for dist in self._yield_distributions(): if isinstance(dist, Ins...
[ "\n Scan the path for distributions and populate the cache with\n those that are found.\n " ]
Please provide a description of the function:def distinfo_dirname(cls, name, version): name = name.replace('-', '_') return '-'.join([name, version]) + DISTINFO_EXT
[ "\n The *name* and *version* parameters are converted into their\n filename-escaped form, i.e. any ``'-'`` characters are replaced\n with ``'_'`` other than the one in ``'dist-info'`` and the one\n separating the name from the version number.\n\n :parameter name: is converted to a...
Please provide a description of the function:def get_distributions(self): if not self._cache_enabled: for dist in self._yield_distributions(): yield dist else: self._generate_cache() for dist in self._cache.path.values(): yiel...
[ "\n Provides an iterator that looks for distributions and returns\n :class:`InstalledDistribution` or\n :class:`EggInfoDistribution` instances for each one of them.\n\n :rtype: iterator of :class:`InstalledDistribution` and\n :class:`EggInfoDistribution` instances\n ...
Please provide a description of the function:def get_distribution(self, name): result = None name = name.lower() if not self._cache_enabled: for dist in self._yield_distributions(): if dist.key == name: result = dist br...
[ "\n Looks for a named distribution on the path.\n\n This function only returns the first result found, as no more than one\n value is expected. If nothing is found, ``None`` is returned.\n\n :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`\n or ``None``...
Please provide a description of the function:def provides_distribution(self, name, version=None): matcher = None if version is not None: try: matcher = self._scheme.matcher('%s (%s)' % (name, version)) except ValueError: raise DistlibExcep...
[ "\n Iterates over all distributions to find which distributions provide *name*.\n If a *version* is provided, it will be used to filter the results.\n\n This function only returns the first result found, since no more than\n one values are expected. If the directory is not found, returns...
Please provide a description of the function:def get_file_path(self, name, relative_path): dist = self.get_distribution(name) if dist is None: raise LookupError('no distribution named %r found' % name) return dist.get_resource_path(relative_path)
[ "\n Return the path to a resource file.\n " ]
Please provide a description of the function:def get_exported_entries(self, category, name=None): for dist in self.get_distributions(): r = dist.exports if category in r: d = r[category] if name is not None: if name in d: ...
[ "\n Return all of the exported entries in a particular category.\n\n :param category: The category to search for entries.\n :param name: If specified, only entries with that name are returned.\n " ]
Please provide a description of the function:def provides(self): plist = self.metadata.provides s = '%s (%s)' % (self.name, self.version) if s not in plist: plist.append(s) return plist
[ "\n A set of distribution names and versions provided by this distribution.\n :return: A set of \"name (version)\" strings.\n " ]
Please provide a description of the function:def matches_requirement(self, req): # Requirement may contain extras - parse to lose those # from what's passed to the matcher r = parse_requirement(req) scheme = get_scheme(self.metadata.scheme) try: matcher = sch...
[ "\n Say if this instance matches (fulfills) a requirement.\n :param req: The requirement to match.\n :rtype req: str\n :return: True if it matches, else False.\n " ]
Please provide a description of the function:def get_hash(self, data, hasher=None): if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%...
[ "\n Get the hash of some data, using a particular hash algorithm, if\n specified.\n\n :param data: The data to be hashed.\n :type data: bytes\n :param hasher: The name of a hash implementation, supported by hashlib,\n or ``None``. Examples of valid values are...
Please provide a description of the function:def _get_records(self): results = [] r = self.get_distinfo_resource('RECORD') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as record_reader: # Base location is parent dir of .dist...
[ "\n Get the list of installed files for the distribution\n :return: A list of tuples of path, hash and size. Note that hash and\n size might be ``None`` for some entries. The path is exactly\n as stored in the file (which is as in PEP 376).\n " ]
Please provide a description of the function:def exports(self): result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: result = self.read_exports() return result
[ "\n Return the information exported by this distribution.\n :return: A dictionary of exports, mapping an export category to a dict\n of :class:`ExportEntry` instances describing the individual\n export entries, and keyed by name.\n " ]
Please provide a description of the function:def read_exports(self): result = {} r = self.get_distinfo_resource(EXPORTS_FILENAME) if r: with contextlib.closing(r.as_stream()) as stream: result = read_exports(stream) return result
[ "\n Read exports data from a file in .ini format.\n\n :return: A dictionary of exports, mapping an export category to a list\n of :class:`ExportEntry` instances describing the individual\n export entries.\n " ]
Please provide a description of the function:def write_exports(self, exports): rf = self.get_distinfo_file(EXPORTS_FILENAME) with open(rf, 'w') as f: write_exports(exports, f)
[ "\n Write a dictionary of exports to a file in .ini format.\n :param exports: A dictionary of exports, mapping an export category to\n a list of :class:`ExportEntry` instances describing the\n individual export entries.\n " ]
Please provide a description of the function:def get_resource_path(self, relative_path): r = self.get_distinfo_resource('RESOURCES') with contextlib.closing(r.as_stream()) as stream: with CSVReader(stream=stream) as resources_reader: for relative, destination in reso...
[ "\n NOTE: This API may change in the future.\n\n Return the absolute path to a resource file with the given relative\n path.\n\n :param relative_path: The path, relative to .dist-info, of the resource\n of interest.\n :return: The absolute path where t...
Please provide a description of the function:def write_installed_files(self, paths, prefix, dry_run=False): prefix = os.path.join(prefix, '') base = os.path.dirname(self.path) base_under_prefix = base.startswith(prefix) base = os.path.join(base, '') record_path = self.ge...
[ "\n Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any\n existing ``RECORD`` file is silently overwritten.\n\n prefix is used to determine when to write absolute paths.\n " ]
Please provide a description of the function:def check_installed_files(self): mismatches = [] base = os.path.dirname(self.path) record_path = self.get_distinfo_file('RECORD') for path, hash_value, size in self.list_installed_files(): if not os.path.isabs(path): ...
[ "\n Checks that the hashes and sizes of the files in ``RECORD`` are\n matched by the files themselves. Returns a (possibly empty) list of\n mismatches. Each entry in the mismatch list will be a tuple consisting\n of the path, 'exists', 'size' or 'hash' according to what didn't match\n ...
Please provide a description of the function:def shared_locations(self): result = {} shared_path = os.path.join(self.path, 'SHARED') if os.path.isfile(shared_path): with codecs.open(shared_path, 'r', encoding='utf-8') as f: lines = f.read().splitlines() ...
[ "\n A dictionary of shared locations whose keys are in the set 'prefix',\n 'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.\n The corresponding value is the absolute path of that category for\n this distribution, and takes into account any paths selected by the\n ...
Please provide a description of the function:def write_shared_locations(self, paths, dry_run=False): shared_path = os.path.join(self.path, 'SHARED') logger.info('creating %s', shared_path) if dry_run: return None lines = [] for key in ('prefix', 'lib', 'heade...
[ "\n Write shared location information to the SHARED file in .dist-info.\n :param paths: A dictionary as described in the documentation for\n :meth:`shared_locations`.\n :param dry_run: If True, the action is logged but no file is actually\n written.\n :retur...
Please provide a description of the function:def get_distinfo_file(self, path): # Check if it is an absolute path # XXX use relpath, add tests if path.find(os.sep) >= 0: # it's an absolute path? distinfo_dirname, path = path.split(os.sep)[-2:] if distinfo_di...
[ "\n Returns a path located under the ``.dist-info`` directory. Returns a\n string representing the path.\n\n :parameter path: a ``'/'``-separated path relative to the\n ``.dist-info`` directory or an absolute path;\n If *path* is an absolute path ...
Please provide a description of the function:def list_distinfo_files(self): base = os.path.dirname(self.path) for path, checksum, size in self._get_records(): # XXX add separator or use real relpath algo if not os.path.isabs(path): path = os.path.join(bas...
[ "\n Iterates over the ``RECORD`` entries and returns paths for each line if\n the path is pointing to a file located in the ``.dist-info`` directory\n or one of its subdirectories.\n\n :returns: iterator of paths\n " ]
Please provide a description of the function:def check_installed_files(self): mismatches = [] record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): for path, _, _ in self.list_installed_files(): if path == record_path: ...
[ "\n Checks that the hashes and sizes of the files in ``RECORD`` are\n matched by the files themselves. Returns a (possibly empty) list of\n mismatches. Each entry in the mismatch list will be a tuple consisting\n of the path, 'exists', 'size' or 'hash' according to what didn't match\n ...
Please provide a description of the function:def list_installed_files(self): def _md5(path): f = open(path, 'rb') try: content = f.read() finally: f.close() return hashlib.md5(content).hexdigest() def _size(path):...
[ "\n Iterates over the ``installed-files.txt`` entries and returns a tuple\n ``(path, hash, size)`` for each line.\n\n :returns: a list of (path, hash, size)\n " ]
Please provide a description of the function:def list_distinfo_files(self, absolute=False): record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): skip = True with codecs.open(record_path, 'r', encoding='utf-8') as f: ...
[ "\n Iterates over the ``installed-files.txt`` entries and returns paths for\n each line if the path is pointing to a file located in the\n ``.egg-info`` directory or one of its subdirectories.\n\n :parameter absolute: If *absolute* is ``True``, each returned path is\n ...
Please provide a description of the function:def add_edge(self, x, y, label=None): self.adjacency_list[x].append((y, label)) # multiple edges are allowed, so be careful if x not in self.reverse_list[y]: self.reverse_list[y].append(x)
[ "Add an edge from distribution *x* to distribution *y* with the given\n *label*.\n\n :type x: :class:`distutils2.database.InstalledDistribution` or\n :class:`distutils2.database.EggInfoDistribution`\n :type y: :class:`distutils2.database.InstalledDistribution` or\n ...
Please provide a description of the function:def add_missing(self, distribution, requirement): logger.debug('%s missing %r', distribution, requirement) self.missing.setdefault(distribution, []).append(requirement)
[ "\n Add a missing *requirement* for the given *distribution*.\n\n :type distribution: :class:`distutils2.database.InstalledDistribution`\n or :class:`distutils2.database.EggInfoDistribution`\n :type requirement: ``str``\n " ]
Please provide a description of the function:def repr_node(self, dist, level=1): output = [self._repr_dist(dist)] for other, label in self.adjacency_list[dist]: dist = self._repr_dist(other) if label is not None: dist = '%s [%s]' % (dist, label) ...
[ "Prints only a subgraph" ]
Please provide a description of the function:def to_dot(self, f, skip_disconnected=True): disconnected = [] f.write("digraph dependencies {\n") for dist, adjs in self.adjacency_list.items(): if len(adjs) == 0 and not skip_disconnected: disconnected.append(di...
[ "Writes a DOT output for the graph to the provided file *f*.\n\n If *skip_disconnected* is set to ``True``, then all distributions\n that are not dependent on any other distribution are skipped.\n\n :type f: has to support ``file``-like operations\n :type skip_disconnected: ``bool``\n ...
Please provide a description of the function:def topological_sort(self): result = [] # Make a shallow copy of the adjacency list alist = {} for k, v in self.adjacency_list.items(): alist[k] = v[:] while True: # See what we can remove in this run ...
[ "\n Perform a topological sort of the graph.\n :return: A tuple, the first element of which is a topologically sorted\n list of distributions, and the second element of which is a\n list of distributions that cannot be sorted because they have\n circular...
Please provide a description of the function:def encode_unicode(f): @wraps(f) def wrapped(obj, error): def _encode(value): if isinstance(value, unicode): # noqa: F821 return value.encode('utf-8') return value error = copy(error) ...
[ "Cerberus error messages expect regular binary strings.\n If unicode is used in a ValidationError message can't be printed.\n\n This decorator ensures that if legacy Python is used unicode\n strings are encoded before passing to a function.\n ", "Helper encoding unicode strings into binary utf-8" ]
Please provide a description of the function:def definitions_errors(self): if not self.is_logic_error: return None result = defaultdict(list) for error in self.child_errors: i = error.schema_path[len(self.schema_path)] result[i].append(error) ...
[ " Dictionary with errors of an *of-rule mapped to the index of the\n definition it occurred in. Returns :obj:`None` if not applicable.\n " ]
Please provide a description of the function:def add(self, error): if not self._path_of_(error): self.errors.append(error) self.errors.sort() else: super(ErrorTree, self).add(error)
[ " Add an error to the tree.\n\n :param error: :class:`~cerberus.errors.ValidationError`\n " ]
Please provide a description of the function:def fetch_errors_from(self, path): node = self.fetch_node_from(path) if node is not None: return node.errors else: return ErrorList()
[ " Returns all errors for a particular path.\n\n :param path: :class:`tuple` of :term:`hashable` s.\n :rtype: :class:`~cerberus.errors.ErrorList`\n " ]
Please provide a description of the function:def fetch_node_from(self, path): context = self for key in path: context = context[key] if context is None: break return context
[ " Returns a node for a path.\n\n :param path: Tuple of :term:`hashable` s.\n :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None`\n " ]
Please provide a description of the function:def _insert_error(self, path, node): field = path[0] if len(path) == 1: if field in self.tree: subtree = self.tree[field].pop() self.tree[field] += [node, subtree] else: self.tre...
[ " Adds an error or sub-tree to :attr:tree.\n\n :param path: Path to the error.\n :type path: Tuple of strings and integers.\n :param node: An error message or a sub-tree.\n :type node: String or dictionary.\n " ]
Please provide a description of the function:def _rewrite_error_path(self, error, offset=0): if error.is_logic_error: self._rewrite_logic_error_path(error, offset) elif error.is_group_error: self._rewrite_group_error_path(error, offset)
[ "\n Recursively rewrites the error path to correctly represent logic errors\n " ]
Please provide a description of the function:def dispatch_hook(key, hooks, hook_data, **kwargs): hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) ...
[ "Dispatches a hook dictionary on a given piece of data." ]
Please provide a description of the function:def cli(ctx, file, quote): '''This script is used to set, get or unset values from a .env file.''' ctx.obj = {} ctx.obj['FILE'] = file ctx.obj['QUOTE'] = quote
[]
Please provide a description of the function:def list(ctx): '''Display all the stored key/value.''' file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) for k, v in dotenv_as_dict.items(): click.echo('%s=%s' % (k, v))
[]
Please provide a description of the function:def set(ctx, key, value): '''Store the given key/value.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key, value = set_key(file, key, value, quote) if success: click.echo('%s=%s' % (key, value)) else: exit(1)
[]
Please provide a description of the function:def get(ctx, key): '''Retrieve the value for the given key.''' file = ctx.obj['FILE'] stored_value = get_key(file, key) if stored_value: click.echo('%s=%s' % (key, stored_value)) else: exit(1)
[]
Please provide a description of the function:def unset(ctx, key): '''Removes the given key.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key = unset_key(file, key, quote) if success: click.echo("Successfully removed %s" % key) else: exit(1)
[]
Please provide a description of the function:def run(ctx, commandline): file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) if not commandline: click.echo('No command given.') exit(1) ret = run_command(commandline, dotenv_as_dict) exit(ret)
[ "Run command with environment variables present." ]
Please provide a description of the function:def _is_installation_local(name): loc = os.path.normcase(pkg_resources.working_set.by_key[name].location) pre = os.path.normcase(sys.prefix) return os.path.commonprefix([loc, pre]) == pre
[ "Check whether the distribution is in the current Python installation.\n\n This is used to distinguish packages seen by a virtual environment. A venv\n may be able to see global packages, but we don't want to mess with them.\n " ]
Please provide a description of the function:def _group_installed_names(packages): groupcoll = GroupCollection(set(), set(), set(), set()) for distro in pkg_resources.working_set: name = distro.key try: package = packages[name] except KeyError: groupcoll.unn...
[ "Group locally installed packages based on given specifications.\n\n `packages` is a name-package mapping that are used as baseline to\n determine how the installed package should be grouped.\n\n Returns a 3-tuple of disjoint sets, all containing names of installed\n packages:\n\n * `uptodate`: These...
Please provide a description of the function:def _build_paths(): paths = sysconfig.get_paths() return { "prefix": sys.prefix, "data": paths["data"], "scripts": paths["scripts"], "headers": paths["include"], "purelib": paths["purelib"], "platlib": paths["platl...
[ "Prepare paths for distlib.wheel.Wheel to install into.\n " ]
Please provide a description of the function:def dumps(data): # type: (_TOMLDocument) -> str if not isinstance(data, _TOMLDocument) and isinstance(data, dict): data = item(data) return data.as_string()
[ "\n Dumps a TOMLDocument into a string.\n " ]
Please provide a description of the function:def findall(self): from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles = allfiles = [] root = self.base stack = [root] pop = stack.pop push = stack.append while stack: root = pop() ...
[ "Find all files under the base and set ``allfiles`` to the absolute\n pathnames of files found.\n " ]
Please provide a description of the function:def add(self, item): if not item.startswith(self.prefix): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
[ "\n Add a file to the manifest.\n\n :param item: The pathname to add. This can be relative to the base.\n " ]
Please provide a description of the function:def sorted(self, wantdirs=False): def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in ('', '/') ...
[ "\n Return sorted files in directory order\n " ]
Please provide a description of the function:def process_directive(self, directive): # Parse the line: split it up, make sure the right number of words # is there, and return the relevant words. 'action' is always # defined: it's the first word of the line. Which of the other ...
[ "\n Process a directive which either adds some files from ``allfiles`` to\n ``files``, or removes some files from ``files``.\n\n :param directive: The directive to process. This should be in a format\n compatible with distutils ``MANIFEST.in`` files:\n\n ...
Please provide a description of the function:def _parse_directive(self, directive): words = directive.split() if len(words) == 1 and words[0] not in ('include', 'exclude', 'global-include', 'global-e...
[ "\n Validate a directive.\n :param directive: The directive to validate.\n :return: A tuple of action, patterns, thedir, dir_patterns\n " ]
Please provide a description of the function:def _include_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): # XXX docstring lying about what the special chars are? found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_reg...
[ "Select strings (presumably filenames) from 'self.files' that\n match 'pattern', a Unix-style wildcard (glob) pattern.\n\n Patterns are not quite the same as implemented by the 'fnmatch'\n module: '*' and '?' match non-special characters, where \"special\"\n is platform-dependent: slash...
Please provide a description of the function:def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) for f in list(self.files): if pattern_re...
[ "Remove strings (presumably filenames) from 'files' that match\n 'pattern'.\n\n Other parameters are the same as for 'include_pattern()', above.\n The list 'self.files' is modified in place. Return True if files are\n found.\n\n This API is public to allow e.g. exclusion of SCM su...
Please provide a description of the function:def _translate_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): if is_regex: if isinstance(pattern, str): return re.compile(pattern) else: return pattern ...
[ "Translate a shell-like wildcard pattern to a compiled regular\n expression.\n\n Return the compiled regex. If 'is_regex' true,\n then 'pattern' is directly compiled to a regex (if it's a string)\n or just returned as-is (assumes it's a regex object).\n " ]
Please provide a description of the function:def _glob_to_re(self, pattern): pattern_re = fnmatch.translate(pattern) # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, # and by extension ...
[ "Translate a shell-like glob pattern to a regular expression.\n\n Return a string containing the regex. Differs from\n 'fnmatch.translate()' in that '*' does not match \"special characters\"\n (which are platform-specific).\n " ]
Please provide a description of the function:def expect_loop(self, timeout=-1): spawn = self.spawn if timeout is not None: end_time = time.time() + timeout try: incoming = spawn.buffer spawn._buffer = spawn.buffer_type() spawn._before = ...
[ "Blocking expect" ]
Please provide a description of the function:def add(self, key, val): key_lower = key.lower() new_vals = [key, val] # Keep the common case aka no item present as fast as possible vals = self._container.setdefault(key_lower, new_vals) if new_vals is not vals: ...
[ "Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n " ]
Please provide a description of the function:def extend(self, *args, **kwargs): if len(args) > 1: raise TypeError("extend() takes at most 1 positional " "arguments ({0} given)".format(len(args))) other = args[0] if len(args) >= 1 else () if isins...
[ "Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n " ]
Please provide a description of the function:def getlist(self, key, default=__marker): try: vals = self._container[key.lower()] except KeyError: if default is self.__marker: return [] return default else: return vals[1:]
[ "Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist." ]
Please provide a description of the function:def iteritems(self): for key in self: vals = self._container[key.lower()] for val in vals[1:]: yield vals[0], val
[ "Iterate over all header lines, including duplicate ones." ]
Please provide a description of the function:def itermerged(self): for key in self: val = self._container[key.lower()] yield val[0], ', '.join(val[1:])
[ "Iterate over all headers, merging duplicate ones together." ]
Please provide a description of the function:def from_httplib(cls, message): # Python 2 # python2.7 does not expose a proper API for exporting multiheaders # efficiently. This function re-reads raw lines from the message # object and extracts the multiheaders properly. obs_fold...
[ "Read headers from a Python 2 httplib message object." ]
Please provide a description of the function:def extract_cookies_to_jar(jar, request, response): if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(requ...
[ "Extract the cookies from the response into a CookieJar.\n\n :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)\n :param request: our own requests.Request object\n :param response: urllib3.HTTPResponse object\n " ]
Please provide a description of the function:def get_cookie_header(jar, request): r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie')
[ "\n Produce an appropriate Cookie header string to be sent with `request`, or None.\n\n :rtype: str\n " ]
Please provide a description of the function:def remove_cookie_by_name(cookiejar, name, domain=None, path=None): clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is n...
[ "Unsets a cookie by name, by default over all domains and paths.\n\n Wraps CookieJar.clear(), is O(n).\n " ]
Please provide a description of the function:def create_cookie(name, value, **kwargs): result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, ...
[ "Make a cookie from underspecified parameters.\n\n By default, the pair of `name` and `value` will be set for the domain ''\n and sent on every request (this is sometimes called a \"supercookie\").\n " ]
Please provide a description of the function:def morsel_to_cookie(morsel): expires = None if morsel['max-age']: try: expires = int(time.time() + int(morsel['max-age'])) except ValueError: raise TypeError('max-age: %s must be integer' % morsel['max-age']) elif mo...
[ "Convert a Morsel object into a Cookie containing the one k/v pair." ]