text
stringlengths
81
112k
Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` def fetch_errors_from(self, path): """ Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: ...
Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` def fetch_node_from(self, path): """ Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorT...
Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary. def _insert_error(self, path, node): """ Adds an error or sub-tree to :attr:tree. ...
Recursively rewrites the error path to correctly represent logic errors def _rewrite_error_path(self, error, offset=0): """ Recursively rewrites the error path to correctly represent logic errors """ if error.is_logic_error: self._rewrite_logic_error_path(error, offset) ...
Dispatches a hook dictionary on a given piece of data. def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hoo...
This script is used to set, get or unset values from a .env file. 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
Display all the stored key/value. 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))
Store the given key/value. 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)
Retrieve the value for the given key. 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)
Removes the given key. 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)
Run command with environment variables present. def run(ctx, commandline): """Run command with environment variables present.""" file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) if not commandline: click.echo('No command given.') exit(1) ret = run_command(commandline, dot...
Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. def _is_installation_local(name): """Check whether the distribution is in the current Py...
Group locally installed packages based on given specifications. `packages` is a name-package mapping that are used as baseline to determine how the installed package should be grouped. Returns a 3-tuple of disjoint sets, all containing names of installed packages: * `uptodate`: These match the sp...
Prepare paths for distlib.wheel.Wheel to install into. def _build_paths(): """Prepare paths for distlib.wheel.Wheel to install into. """ paths = sysconfig.get_paths() return { "prefix": sys.prefix, "data": paths["data"], "scripts": paths["scripts"], "headers": paths["inc...
Dumps a TOMLDocument into a string. def dumps(data): # type: (_TOMLDocument) -> str """ Dumps a TOMLDocument into a string. """ if not isinstance(data, _TOMLDocument) and isinstance(data, dict): data = item(data) return data.as_string()
Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. def findall(self): """Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. """ from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles =...
Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. """ if not item.startswith(self.prefix): ...
Return sorted files in directory order def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split...
Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANIFEST.in`` files: http://docs.python.or...
Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns def _parse_directive(self, directive): """ Validate a directive. :param directive: The directive to validate. :return: A tuple of action, pattern...
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; co...
Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. ...
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). def _translate_pattern(self, pattern, anchor...
Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). def _glob_to_re(self, pattern): """Translate a shell-like glob pattern t...
Blocking expect def expect_loop(self, timeout=-1): """Blocking expect""" spawn = self.spawn if timeout is not None: end_time = time.time() + timeout try: incoming = spawn.buffer spawn._buffer = spawn.buffer_type() spawn._before = spawn.b...
Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it alre...
Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__ def extend(self, *args, **kwargs): """Generic import function for any type of header-like object. Adapted version of Mu...
Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist. def getlist(self, key, default=__marker): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = self._conta...
Iterate over all header lines, including duplicate ones. def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = self._container[key.lower()] for val in vals[1:]: yield vals[0], val
Iterate over all headers, merging duplicate ones together. def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = self._container[key.lower()] yield val[0], ', '.join(val[1:])
Read headers from a Python 2 httplib message object. def from_httplib(cls, message): # Python 2 """Read headers from a Python 2 httplib message object.""" # python2.7 does not expose a proper API for exporting multiheaders # efficiently. This function re-reads raw lines from the message ...
Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the...
Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return...
Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for co...
Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair ...
Convert a Morsel object into a Cookie containing the one k/v pair. def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: try: expires = int(time.time() + int(morsel['max-age'])) except ValueEr...
Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. :rtype: CookieJar ...
Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar def merge_cookies(cookiejar, cookies): """Add cookies to cookiejar and returns a merged CookieJar. :para...
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supp...
Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming co...
Utility method to list all the domains in the jar. def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains
Utility method to list all the paths in the jar. def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ domains = [] for cookie in iter(...
Updates this jar with cookies from another CookieJar or dict-like def update(self, other): """Updates this jar with cookies from another CookieJar or dict-like""" if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else:...
Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (...
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if...
Return a copy of this RequestsCookieJar. def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj
This returns a number, n constrained to the min and max bounds. def constrain (n, min, max): '''This returns a number, n constrained to the min and max bounds. ''' if n < min: return min if n > max: return max return n
This converts from the external coding system (as passed to the constructor) to the internal one (unicode). def _decode(self, s): '''This converts from the external coding system (as passed to the constructor) to the internal one (unicode). ''' if self.decoder is not None: r...
This returns a printable representation of the screen as a unicode string (which, under Python 3.x, is the same as 'str'). The end of each screen line is terminated by a newline. def _unicode(self): '''This returns a printable representation of the screen as a unicode string (which, und...
This returns a copy of the screen as a unicode string. This is similar to __str__/__unicode__ except that lines are not terminated with line feeds. def dump (self): '''This returns a copy of the screen as a unicode string. This is similar to __str__/__unicode__ except that lines are not...
This returns a copy of the screen as a unicode string with an ASCII text box around the screen border. This is similar to __str__/__unicode__ except that it adds a box. def pretty (self): '''This returns a copy of the screen as a unicode string with an ASCII text box around the screen b...
This moves the cursor down with scrolling. def lf (self): '''This moves the cursor down with scrolling. ''' old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up () self.erase_line()
Screen array starts at 1 index. def put_abs (self, r, c, ch): '''Screen array starts at 1 index.''' r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) if isinstance(ch, bytes): ch = self._decode(ch)[0] else: ch = ch[0] self.w[r-1][c-...
This puts a characters at the current cursor position. def put (self, ch): '''This puts a characters at the current cursor position. ''' if isinstance(ch, bytes): ch = self._decode(ch) self.put_abs (self.cur_r, self.cur_c, ch)
This inserts a character at (r,c). Everything under and to the right is shifted right one character. The last character of the line is lost. def insert_abs (self, r, c, ch): '''This inserts a character at (r,c). Everything under and to the right is shifted right one character. T...
This returns a list of lines representing the region. def get_region (self, rs,cs, re,ce): '''This returns a list of lines representing the region. ''' rs = constrain (rs, 1, self.rows) re = constrain (re, 1, self.rows) cs = constrain (cs, 1, self.cols) ce = constrain (...
This keeps the cursor within the screen area. def cursor_constrain (self): '''This keeps the cursor within the screen area. ''' self.cur_r = constrain (self.cur_r, 1, self.rows) self.cur_c = constrain (self.cur_c, 1, self.cols)
Save current cursor position. def cursor_save_attrs (self): # <ESC>7 '''Save current cursor position.''' self.cur_saved_r = self.cur_r self.cur_saved_c = self.cur_c
This keeps the scroll region within the screen region. def scroll_constrain (self): '''This keeps the scroll region within the screen region.''' if self.scroll_row_start <= 0: self.scroll_row_start = 1 if self.scroll_row_end > self.rows: self.scroll_row_end = self.rows
Enable scrolling from row {start} to row {end}. def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r '''Enable scrolling from row {start} to row {end}.''' self.scroll_row_start = rs self.scroll_row_end = re self.scroll_constrain()
Scroll display down one line. def scroll_down (self): # <ESC>D '''Scroll display down one line.''' # Screen is indexed from 1, but arrays are indexed from 0. s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s+1:e+1] = copy.deepcopy(self.w[s:e])
Erases from the current cursor position to the end of the current line. def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K '''Erases from the current cursor position to the end of the current line.''' self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols)
Erases from the current cursor position to the start of the current line. def erase_start_of_line (self): # <ESC>[1K '''Erases from the current cursor position to the start of the current line.''' self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c)
Erases the entire current line. def erase_line (self): # <ESC>[2K '''Erases the entire current line.''' self.fill_region (self.cur_r, 1, self.cur_r, self.cols)
Erases the screen from the current line down to the bottom of the screen. def erase_down (self): # <ESC>[0J -or- <ESC>[J '''Erases the screen from the current line down to the bottom of the screen.''' self.erase_end_of_line () self.fill_region (self.cur_r + 1, 1, self.rows, sel...
Erases the screen from the current line up to the top of the screen. def erase_up (self): # <ESC>[1J '''Erases the screen from the current line up to the top of the screen.''' self.erase_start_of_line () self.fill_region (self.cur_r-1, 1, 1, self.cols)
Pull a value from the dict and convert to int :param default_to_zero: If the value is None or empty, treat it as zero :param default: If the value is missing in the dict use this default def to_int(d, key, default_to_zero=False, default=None, required=True): """Pull a value from the dict and convert to in...
Parses ISO 8601 time zone specs into tzinfo offsets def parse_timezone(matches, default_timezone=UTC): """Parses ISO 8601 time zone specs into tzinfo offsets """ if matches["timezone"] == "Z": return UTC # This isn't strictly correct, but it's common to encounter dates without # timezones...
Parses ISO 8601 dates into datetime objects The timezone is parsed from the date string. However it is quite common to have dates without a timezone (not strictly correct). In this case the default timezone specified in default_timezone is used. This is UTC by default. :param datestring: The date ...
Signal handler, used to gracefully shut down the ``spinner`` instance when specified signal is received by the process running the ``spinner``. ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal`` function for more details. def default_handler(signum, frame, spinner): """Signal ha...
Signal handler, used to gracefully shut down the ``spinner`` instance when specified signal is received by the process running the ``spinner``. ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal`` function for more details. def fancy_handler(signum, frame, spinner): """Signal hand...
Re-map the characters in the string according to UTS46 processing. def uts46_remap(domain, std3_rules=True, transitional=False): """Re-map the characters in the string according to UTS46 processing.""" from .uts46data import uts46data output = u"" try: for pos, char in enumerate(domain): ...
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably...
Generate information for a bug report. def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', ...
>>> package = yarg.get('yarg') >>> v = "0.1.0" >>> r = package.release(v) >>> r.package_type u'wheel' def package_type(self): """ >>> package = yarg.get('yarg') >>> v = "0.1.0" >>> r = package.release(v) >>> r.packa...
Process a single character. Called by :meth:`write`. def process (self, c): """Process a single character. Called by :meth:`write`.""" if isinstance(c, bytes): c = self._decode(c) self.state.process(c)
Process text, writing it to the virtual screen while handling ANSI escape codes. def write (self, s): """Process text, writing it to the virtual screen while handling ANSI escape codes. """ if isinstance(s, bytes): s = self._decode(s) for c in s: ...
This puts a character at the current cursor position. The cursor position is moved forward with wrap-around, but no scrolling is done if the cursor hits the lower-right corner of the screen. def write_ch (self, ch): '''This puts a character at the current cursor position. The cursor pos...
Returns the default stream encoding if not found. def get_best_encoding(stream): """Returns the default stream encoding if not found.""" rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding() if is_ascii_encoding(rv): return 'utf-8' return rv
Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connec...
Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provid...
If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. def set_file_position(body, pos): """ If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. """ if pos is not None: ...
Attempt to rewind body to a certain position. Primarily used for request redirects and retries. :param body: File-like object that supports seek. :param int pos: Position to seek to in file. def rewind_body(body, body_pos): """ Attempt to rewind body to a certain position. Pri...
Deep-copy a value into JSON-safe types. def _copy_jsonsafe(value): """Deep-copy a value into JSON-safe types. """ if isinstance(value, six.string_types + (numbers.Number,)): return value if isinstance(value, collections_abc.Mapping): return {six.text_type(k): _copy_jsonsafe(v) for k, v ...
Helper for clearing all the keys in a database. Use with caution! def clear(self): """Helper for clearing all the keys in a database. Use with caution!""" for key in self.conn.keys(): self.conn.delete(key)
Be aware that this treats any sequence type with the equal members as equal. As it is used to identify equality of schemas, this can be considered okay as definitions are semantically equal regardless the container type. def mapping_to_frozenset(mapping): """ Be aware that this treats any s...
Dynamically create a :class:`~cerberus.Validator` subclass. Docstrings of mixin-classes will be added to the resulting class' one if ``__doc__`` is not in :obj:`namespace`. :param name: The name of the new class. :type name: :class:`str` :param bases: Class(es) with additional and overridin...
Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are doubled, so they are all ...
Returns a tuple of `frozenset`s of classes and attributes. def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
Whitelist *what*. :param what: What to whitelist. :type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s :rtype: :class:`callable` def include(*what): """ Whitelist *what*. :param what: What to whitelist. :type what: :class:`list` of :class:`type` or :class:`attr.Attri...
Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable` def exclude(*what): """ Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. ...
Return the ``attrs`` attribute values of *inst* as a dict. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose ret...
``asdict`` only works on attrs instances, this works on anything. def _asdict_anything(val, filter, dict_factory, retain_collection_types): """ ``asdict`` only works on attrs instances, this works on anything. """ if getattr(val.__class__, "__attrs_attrs__", None) is not None: # Attrs class. ...
Return the ``attrs`` attribute values of *inst* as a tuple. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose re...
Copy *inst* and apply *changes*. :param inst: Instance of a class with ``attrs`` attributes. :param changes: Keyword changes in the new copy. :return: A copy of inst with *changes* incorporated. :raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't be found on *cls*. ...
Create a new instance, based on *inst* with *changes* applied. :param inst: Instance of a class with ``attrs`` attributes. :param changes: Keyword changes in the new copy. :return: A copy of inst with *changes* incorporated. :raise TypeError: If *attr_name* couldn't be found in the class ``__...
Constructs a request to the PyPI server and returns a :class:`yarg.package.Package`. :param package_name: case sensitive name of the package on the PyPI server. :param pypi_server: (option) URL to the PyPI server. >>> import yarg >>> package = yarg.get('yarg') <Package yarg> def g...
Parse into a hierarchy of contexts. Contexts are connected through the parent variable. :param cli: command definition :param prog_name: the program that is running :param args: full list of args :return: the final context/command parsed def resolve_ctx(cli, prog_name, args): """ Parse into a h...
:param all_args: the full original list of args supplied :param cmd_param: the current command paramter :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and corresponds to this cmd_param. In other words whether this cmd_param option can still accept values def...