id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
25,600
pypa/pipenv
pipenv/vendor/distlib/database.py
InstalledDistribution.get_distinfo_file
def get_distinfo_file(self, path): """ Returns a path located under the ``.dist-info`` directory. Returns a string representing the path. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` directory or an absolute path; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str """ # 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_dirname != self.path.split(os.sep)[-1]: raise DistlibException( 'dist-info file %r does not belong to the %r %s ' 'distribution' % (path, self.name, self.version)) # The file must be relative if path not in DIST_FILES: raise DistlibException('invalid path for a dist-info file: ' '%r at %r' % (path, self.path)) return os.path.join(self.path, path)
python
def get_distinfo_file(self, path): """ Returns a path located under the ``.dist-info`` directory. Returns a string representing the path. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` directory or an absolute path; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str """ # 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_dirname != self.path.split(os.sep)[-1]: raise DistlibException( 'dist-info file %r does not belong to the %r %s ' 'distribution' % (path, self.name, self.version)) # The file must be relative if path not in DIST_FILES: raise DistlibException('invalid path for a dist-info file: ' '%r at %r' % (path, self.path)) return os.path.join(self.path, path)
[ "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_dirname", "!=", "self", ".", "path", ".", "split", "(", "os", ".", "sep", ")", "[", "-", "1", "]", ":", "raise", "DistlibException", "(", "'dist-info file %r does not belong to the %r %s '", "'distribution'", "%", "(", "path", ",", "self", ".", "name", ",", "self", ".", "version", ")", ")", "# The file must be relative", "if", "path", "not", "in", "DIST_FILES", ":", "raise", "DistlibException", "(", "'invalid path for a dist-info file: '", "'%r at %r'", "%", "(", "path", ",", "self", ".", "path", ")", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "path", ")" ]
Returns a path located under the ``.dist-info`` directory. Returns a string representing the path. :parameter path: a ``'/'``-separated path relative to the ``.dist-info`` directory or an absolute path; If *path* is an absolute path and doesn't start with the ``.dist-info`` directory path, a :class:`DistlibException` is raised :type path: str :rtype: str
[ "Returns", "a", "path", "located", "under", "the", ".", "dist", "-", "info", "directory", ".", "Returns", "a", "string", "representing", "the", "path", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L804-L831
25,601
pypa/pipenv
pipenv/vendor/distlib/database.py
InstalledDistribution.list_distinfo_files
def list_distinfo_files(self): """ Iterates over the ``RECORD`` entries and returns paths for each line if the path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :returns: iterator of paths """ 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(base, path) if path.startswith(self.path): yield path
python
def list_distinfo_files(self): """ Iterates over the ``RECORD`` entries and returns paths for each line if the path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :returns: iterator of paths """ 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(base, path) if path.startswith(self.path): yield path
[ "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", "(", "base", ",", "path", ")", "if", "path", ".", "startswith", "(", "self", ".", "path", ")", ":", "yield", "path" ]
Iterates over the ``RECORD`` entries and returns paths for each line if the path is pointing to a file located in the ``.dist-info`` directory or one of its subdirectories. :returns: iterator of paths
[ "Iterates", "over", "the", "RECORD", "entries", "and", "returns", "paths", "for", "each", "line", "if", "the", "path", "is", "pointing", "to", "a", "file", "located", "in", "the", ".", "dist", "-", "info", "directory", "or", "one", "of", "its", "subdirectories", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L833-L847
25,602
pypa/pipenv
pipenv/vendor/distlib/database.py
EggInfoDistribution.list_distinfo_files
def list_distinfo_files(self, absolute=False): """ Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``True``, each returned path is transformed into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths """ 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: for line in f: line = line.strip() if line == './': skip = False continue if not skip: p = os.path.normpath(os.path.join(self.path, line)) if p.startswith(self.path): if absolute: yield p else: yield line
python
def list_distinfo_files(self, absolute=False): """ Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``True``, each returned path is transformed into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths """ 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: for line in f: line = line.strip() if line == './': skip = False continue if not skip: p = os.path.normpath(os.path.join(self.path, line)) if p.startswith(self.path): if absolute: yield p else: yield line
[ "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", ":", "for", "line", "in", "f", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", "==", "'./'", ":", "skip", "=", "False", "continue", "if", "not", "skip", ":", "p", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "line", ")", ")", "if", "p", ".", "startswith", "(", "self", ".", "path", ")", ":", "if", "absolute", ":", "yield", "p", "else", ":", "yield", "line" ]
Iterates over the ``installed-files.txt`` entries and returns paths for each line if the path is pointing to a file located in the ``.egg-info`` directory or one of its subdirectories. :parameter absolute: If *absolute* is ``True``, each returned path is transformed into a local absolute path. Otherwise the raw value from ``installed-files.txt`` is returned. :type absolute: boolean :returns: iterator of paths
[ "Iterates", "over", "the", "installed", "-", "files", ".", "txt", "entries", "and", "returns", "paths", "for", "each", "line", "if", "the", "path", "is", "pointing", "to", "a", "file", "located", "in", "the", ".", "egg", "-", "info", "directory", "or", "one", "of", "its", "subdirectories", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1041-L1068
25,603
pypa/pipenv
pipenv/vendor/distlib/database.py
DependencyGraph.repr_node
def repr_node(self, dist, level=1): """Prints only a subgraph""" 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) output.append(' ' * level + str(dist)) suboutput = self.repr_node(other, level + 1) subs = suboutput.split('\n') output.extend(subs[1:]) return '\n'.join(output)
python
def repr_node(self, dist, level=1): """Prints only a subgraph""" 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) output.append(' ' * level + str(dist)) suboutput = self.repr_node(other, level + 1) subs = suboutput.split('\n') output.extend(subs[1:]) return '\n'.join(output)
[ "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", ")", "output", ".", "append", "(", "' '", "*", "level", "+", "str", "(", "dist", ")", ")", "suboutput", "=", "self", ".", "repr_node", "(", "other", ",", "level", "+", "1", ")", "subs", "=", "suboutput", ".", "split", "(", "'\\n'", ")", "output", ".", "extend", "(", "subs", "[", "1", ":", "]", ")", "return", "'\\n'", ".", "join", "(", "output", ")" ]
Prints only a subgraph
[ "Prints", "only", "a", "subgraph" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1141-L1152
25,604
pypa/pipenv
pipenv/vendor/cerberus/errors.py
encode_unicode
def encode_unicode(f): """Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can't be printed. This decorator ensures that if legacy Python is used unicode strings are encoded before passing to a function. """ @wraps(f) def wrapped(obj, error): def _encode(value): """Helper encoding unicode strings into binary utf-8""" if isinstance(value, unicode): # noqa: F821 return value.encode('utf-8') return value error = copy(error) error.document_path = _encode(error.document_path) error.schema_path = _encode(error.schema_path) error.constraint = _encode(error.constraint) error.value = _encode(error.value) error.info = _encode(error.info) return f(obj, error) return wrapped if PYTHON_VERSION < 3 else f
python
def encode_unicode(f): """Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can't be printed. This decorator ensures that if legacy Python is used unicode strings are encoded before passing to a function. """ @wraps(f) def wrapped(obj, error): def _encode(value): """Helper encoding unicode strings into binary utf-8""" if isinstance(value, unicode): # noqa: F821 return value.encode('utf-8') return value error = copy(error) error.document_path = _encode(error.document_path) error.schema_path = _encode(error.schema_path) error.constraint = _encode(error.constraint) error.value = _encode(error.value) error.info = _encode(error.info) return f(obj, error) return wrapped if PYTHON_VERSION < 3 else f
[ "def", "encode_unicode", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "obj", ",", "error", ")", ":", "def", "_encode", "(", "value", ")", ":", "\"\"\"Helper encoding unicode strings into binary utf-8\"\"\"", "if", "isinstance", "(", "value", ",", "unicode", ")", ":", "# noqa: F821", "return", "value", ".", "encode", "(", "'utf-8'", ")", "return", "value", "error", "=", "copy", "(", "error", ")", "error", ".", "document_path", "=", "_encode", "(", "error", ".", "document_path", ")", "error", ".", "schema_path", "=", "_encode", "(", "error", ".", "schema_path", ")", "error", ".", "constraint", "=", "_encode", "(", "error", ".", "constraint", ")", "error", ".", "value", "=", "_encode", "(", "error", ".", "value", ")", "error", ".", "info", "=", "_encode", "(", "error", ".", "info", ")", "return", "f", "(", "obj", ",", "error", ")", "return", "wrapped", "if", "PYTHON_VERSION", "<", "3", "else", "f" ]
Cerberus error messages expect regular binary strings. If unicode is used in a ValidationError message can't be printed. This decorator ensures that if legacy Python is used unicode strings are encoded before passing to a function.
[ "Cerberus", "error", "messages", "expect", "regular", "binary", "strings", ".", "If", "unicode", "is", "used", "in", "a", "ValidationError", "message", "can", "t", "be", "printed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L407-L431
25,605
pypa/pipenv
pipenv/vendor/cerberus/errors.py
ErrorTree.add
def add(self, error): """ Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError` """ if not self._path_of_(error): self.errors.append(error) self.errors.sort() else: super(ErrorTree, self).add(error)
python
def add(self, error): """ Add an error to the tree. :param error: :class:`~cerberus.errors.ValidationError` """ if not self._path_of_(error): self.errors.append(error) self.errors.sort() else: super(ErrorTree, self).add(error)
[ "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. :param error: :class:`~cerberus.errors.ValidationError`
[ "Add", "an", "error", "to", "the", "tree", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L286-L295
25,606
pypa/pipenv
pipenv/vendor/cerberus/errors.py
ErrorTree.fetch_errors_from
def fetch_errors_from(self, path): """ Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` """ node = self.fetch_node_from(path) if node is not None: return node.errors else: return ErrorList()
python
def fetch_errors_from(self, path): """ Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` """ node = self.fetch_node_from(path) if node is not None: return node.errors else: return ErrorList()
[ "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. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList`
[ "Returns", "all", "errors", "for", "a", "particular", "path", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L297-L307
25,607
pypa/pipenv
pipenv/vendor/cerberus/errors.py
ErrorTree.fetch_node_from
def fetch_node_from(self, path): """ Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` """ context = self for key in path: context = context[key] if context is None: break return context
python
def fetch_node_from(self, path): """ Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` """ context = self for key in path: context = context[key] if context is None: break return context
[ "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. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None`
[ "Returns", "a", "node", "for", "a", "path", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L309-L320
25,608
pypa/pipenv
pipenv/vendor/cerberus/errors.py
BasicErrorHandler._rewrite_error_path
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) elif error.is_group_error: self._rewrite_group_error_path(error, offset)
python
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) elif error.is_group_error: self._rewrite_group_error_path(error, offset)
[ "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", ")" ]
Recursively rewrites the error path to correctly represent logic errors
[ "Recursively", "rewrites", "the", "error", "path", "to", "correctly", "represent", "logic", "errors" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L589-L596
25,609
pypa/pipenv
pipenv/vendor/dotenv/cli.py
cli
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
python
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
[ "def", "cli", "(", "ctx", ",", "file", ",", "quote", ")", ":", "ctx", ".", "obj", "=", "{", "}", "ctx", ".", "obj", "[", "'FILE'", "]", "=", "file", "ctx", ".", "obj", "[", "'QUOTE'", "]", "=", "quote" ]
This script is used to set, get or unset values from a .env file.
[ "This", "script", "is", "used", "to", "set", "get", "or", "unset", "values", "from", "a", ".", "env", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L24-L28
25,610
pypa/pipenv
pipenv/vendor/dotenv/cli.py
get
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)
python
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)
[ "def", "get", "(", "ctx", ",", "key", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "stored_value", "=", "get_key", "(", "file", ",", "key", ")", "if", "stored_value", ":", "click", ".", "echo", "(", "'%s=%s'", "%", "(", "key", ",", "stored_value", ")", ")", "else", ":", "exit", "(", "1", ")" ]
Retrieve the value for the given key.
[ "Retrieve", "the", "value", "for", "the", "given", "key", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L59-L66
25,611
pypa/pipenv
pipenv/vendor/dotenv/cli.py
unset
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)
python
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)
[ "def", "unset", "(", "ctx", ",", "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", ")" ]
Removes the given key.
[ "Removes", "the", "given", "key", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L72-L80
25,612
pypa/pipenv
pipenv/vendor/dotenv/cli.py
run
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, dotenv_as_dict) exit(ret)
python
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, dotenv_as_dict) exit(ret)
[ "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.
[ "Run", "command", "with", "environment", "variables", "present", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L86-L94
25,613
pypa/pipenv
pipenv/vendor/passa/models/synchronizers.py
_is_installation_local
def _is_installation_local(name): """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. """ 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
python
def _is_installation_local(name): """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. """ 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
[ "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. 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.
[ "Check", "whether", "the", "distribution", "is", "in", "the", "current", "Python", "installation", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/synchronizers.py#L20-L28
25,614
pypa/pipenv
pipenv/vendor/passa/models/synchronizers.py
_group_installed_names
def _group_installed_names(packages): """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 specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`. """ groupcoll = GroupCollection(set(), set(), set(), set()) for distro in pkg_resources.working_set: name = distro.key try: package = packages[name] except KeyError: groupcoll.unneeded.add(name) continue r = requirementslib.Requirement.from_pipfile(name, package) if not r.is_named: # Always mark non-named. I think pip does something similar? groupcoll.outdated.add(name) elif not _is_up_to_date(distro, r.get_version()): groupcoll.outdated.add(name) else: groupcoll.uptodate.add(name) return groupcoll
python
def _group_installed_names(packages): """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 specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`. """ groupcoll = GroupCollection(set(), set(), set(), set()) for distro in pkg_resources.working_set: name = distro.key try: package = packages[name] except KeyError: groupcoll.unneeded.add(name) continue r = requirementslib.Requirement.from_pipfile(name, package) if not r.is_named: # Always mark non-named. I think pip does something similar? groupcoll.outdated.add(name) elif not _is_up_to_date(distro, r.get_version()): groupcoll.outdated.add(name) else: groupcoll.uptodate.add(name) return groupcoll
[ "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", ".", "unneeded", ".", "add", "(", "name", ")", "continue", "r", "=", "requirementslib", ".", "Requirement", ".", "from_pipfile", "(", "name", ",", "package", ")", "if", "not", "r", ".", "is_named", ":", "# Always mark non-named. I think pip does something similar?", "groupcoll", ".", "outdated", ".", "add", "(", "name", ")", "elif", "not", "_is_up_to_date", "(", "distro", ",", "r", ".", "get_version", "(", ")", ")", ":", "groupcoll", ".", "outdated", ".", "add", "(", "name", ")", "else", ":", "groupcoll", ".", "uptodate", ".", "add", "(", "name", ")", "return", "groupcoll" ]
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 specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`.
[ "Group", "locally", "installed", "packages", "based", "on", "given", "specifications", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/synchronizers.py#L41-L74
25,615
pypa/pipenv
pipenv/vendor/tomlkit/api.py
dumps
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()
python
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()
[ "def", "dumps", "(", "data", ")", ":", "# type: (_TOMLDocument) -> str", "if", "not", "isinstance", "(", "data", ",", "_TOMLDocument", ")", "and", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "item", "(", "data", ")", "return", "data", ".", "as_string", "(", ")" ]
Dumps a TOMLDocument into a string.
[ "Dumps", "a", "TOMLDocument", "into", "a", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/api.py#L35-L42
25,616
pypa/pipenv
pipenv/vendor/distlib/manifest.py
Manifest.findall
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 = allfiles = [] root = self.base stack = [root] pop = stack.pop push = stack.append while stack: root = pop() names = os.listdir(root) for name in names: fullname = os.path.join(root, name) # Avoid excess stat calls -- just one will do, thank you! stat = os.stat(fullname) mode = stat.st_mode if S_ISREG(mode): allfiles.append(fsdecode(fullname)) elif S_ISDIR(mode) and not S_ISLNK(mode): push(fullname)
python
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 = allfiles = [] root = self.base stack = [root] pop = stack.pop push = stack.append while stack: root = pop() names = os.listdir(root) for name in names: fullname = os.path.join(root, name) # Avoid excess stat calls -- just one will do, thank you! stat = os.stat(fullname) mode = stat.st_mode if S_ISREG(mode): allfiles.append(fsdecode(fullname)) elif S_ISDIR(mode) and not S_ISLNK(mode): push(fullname)
[ "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", "(", ")", "names", "=", "os", ".", "listdir", "(", "root", ")", "for", "name", "in", "names", ":", "fullname", "=", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "# Avoid excess stat calls -- just one will do, thank you!", "stat", "=", "os", ".", "stat", "(", "fullname", ")", "mode", "=", "stat", ".", "st_mode", "if", "S_ISREG", "(", "mode", ")", ":", "allfiles", ".", "append", "(", "fsdecode", "(", "fullname", ")", ")", "elif", "S_ISDIR", "(", "mode", ")", "and", "not", "S_ISLNK", "(", "mode", ")", ":", "push", "(", "fullname", ")" ]
Find all files under the base and set ``allfiles`` to the absolute pathnames of files found.
[ "Find", "all", "files", "under", "the", "base", "and", "set", "allfiles", "to", "the", "absolute", "pathnames", "of", "files", "found", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L57-L82
25,617
pypa/pipenv
pipenv/vendor/distlib/manifest.py
Manifest.add
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): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
python
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): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
[ "def", "add", "(", "self", ",", "item", ")", ":", "if", "not", "item", ".", "startswith", "(", "self", ".", "prefix", ")", ":", "item", "=", "os", ".", "path", ".", "join", "(", "self", ".", "base", ",", "item", ")", "self", ".", "files", ".", "add", "(", "os", ".", "path", ".", "normpath", "(", "item", ")", ")" ]
Add a file to the manifest. :param item: The pathname to add. This can be relative to the base.
[ "Add", "a", "file", "to", "the", "manifest", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L84-L92
25,618
pypa/pipenv
pipenv/vendor/distlib/manifest.py
Manifest.sorted
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(d) assert parent not in ('', '/') add_dir(dirs, parent) result = set(self.files) # make a copy! if wantdirs: dirs = set() for f in result: add_dir(dirs, os.path.dirname(f)) result |= dirs return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
python
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(d) assert parent not in ('', '/') add_dir(dirs, parent) result = set(self.files) # make a copy! if wantdirs: dirs = set() for f in result: add_dir(dirs, os.path.dirname(f)) result |= dirs return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
[ "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", "(", "''", ",", "'/'", ")", "add_dir", "(", "dirs", ",", "parent", ")", "result", "=", "set", "(", "self", ".", "files", ")", "# make a copy!", "if", "wantdirs", ":", "dirs", "=", "set", "(", ")", "for", "f", "in", "result", ":", "add_dir", "(", "dirs", ",", "os", ".", "path", ".", "dirname", "(", "f", ")", ")", "result", "|=", "dirs", "return", "[", "os", ".", "path", ".", "join", "(", "*", "path_tuple", ")", "for", "path_tuple", "in", "sorted", "(", "os", ".", "path", ".", "split", "(", "path", ")", "for", "path", "in", "result", ")", "]" ]
Return sorted files in directory order
[ "Return", "sorted", "files", "in", "directory", "order" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L103-L123
25,619
pypa/pipenv
pipenv/vendor/distlib/manifest.py
Manifest.process_directive
def process_directive(self, directive): """ 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.org/distutils/sourcedist.html#commands """ # 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 # three are defined depends on the action; it'll be either # patterns, (dir and patterns), or (dirpattern). action, patterns, thedir, dirpattern = self._parse_directive(directive) # OK, now we know that the action is valid and we have the # right number of words on the line for that action -- so we # can proceed with minimal error-checking. if action == 'include': for pattern in patterns: if not self._include_pattern(pattern, anchor=True): logger.warning('no files found matching %r', pattern) elif action == 'exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=True) #if not found: # logger.warning('no previously-included files ' # 'found matching %r', pattern) elif action == 'global-include': for pattern in patterns: if not self._include_pattern(pattern, anchor=False): logger.warning('no files found matching %r ' 'anywhere in distribution', pattern) elif action == 'global-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=False) #if not found: # logger.warning('no previously-included files ' # 'matching %r found anywhere in ' # 'distribution', pattern) elif action == 'recursive-include': for pattern in patterns: if not self._include_pattern(pattern, prefix=thedir): logger.warning('no files found matching %r ' 'under directory %r', pattern, thedir) elif action == 'recursive-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, prefix=thedir) #if not found: # logger.warning('no previously-included files ' # 'matching %r found under directory %r', # pattern, thedir) elif action == 'graft': if not self._include_pattern(None, prefix=dirpattern): logger.warning('no directories found matching %r', dirpattern) elif action == 'prune': if not self._exclude_pattern(None, prefix=dirpattern): logger.warning('no previously-included directories found ' 'matching %r', dirpattern) else: # pragma: no cover # This should never happen, as it should be caught in # _parse_template_line raise DistlibException( 'invalid action %r' % action)
python
def process_directive(self, directive): """ 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.org/distutils/sourcedist.html#commands """ # 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 # three are defined depends on the action; it'll be either # patterns, (dir and patterns), or (dirpattern). action, patterns, thedir, dirpattern = self._parse_directive(directive) # OK, now we know that the action is valid and we have the # right number of words on the line for that action -- so we # can proceed with minimal error-checking. if action == 'include': for pattern in patterns: if not self._include_pattern(pattern, anchor=True): logger.warning('no files found matching %r', pattern) elif action == 'exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=True) #if not found: # logger.warning('no previously-included files ' # 'found matching %r', pattern) elif action == 'global-include': for pattern in patterns: if not self._include_pattern(pattern, anchor=False): logger.warning('no files found matching %r ' 'anywhere in distribution', pattern) elif action == 'global-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=False) #if not found: # logger.warning('no previously-included files ' # 'matching %r found anywhere in ' # 'distribution', pattern) elif action == 'recursive-include': for pattern in patterns: if not self._include_pattern(pattern, prefix=thedir): logger.warning('no files found matching %r ' 'under directory %r', pattern, thedir) elif action == 'recursive-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, prefix=thedir) #if not found: # logger.warning('no previously-included files ' # 'matching %r found under directory %r', # pattern, thedir) elif action == 'graft': if not self._include_pattern(None, prefix=dirpattern): logger.warning('no directories found matching %r', dirpattern) elif action == 'prune': if not self._exclude_pattern(None, prefix=dirpattern): logger.warning('no previously-included directories found ' 'matching %r', dirpattern) else: # pragma: no cover # This should never happen, as it should be caught in # _parse_template_line raise DistlibException( 'invalid action %r' % action)
[ "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", "# three are defined depends on the action; it'll be either", "# patterns, (dir and patterns), or (dirpattern).", "action", ",", "patterns", ",", "thedir", ",", "dirpattern", "=", "self", ".", "_parse_directive", "(", "directive", ")", "# OK, now we know that the action is valid and we have the", "# right number of words on the line for that action -- so we", "# can proceed with minimal error-checking.", "if", "action", "==", "'include'", ":", "for", "pattern", "in", "patterns", ":", "if", "not", "self", ".", "_include_pattern", "(", "pattern", ",", "anchor", "=", "True", ")", ":", "logger", ".", "warning", "(", "'no files found matching %r'", ",", "pattern", ")", "elif", "action", "==", "'exclude'", ":", "for", "pattern", "in", "patterns", ":", "found", "=", "self", ".", "_exclude_pattern", "(", "pattern", ",", "anchor", "=", "True", ")", "#if not found:", "# logger.warning('no previously-included files '", "# 'found matching %r', pattern)", "elif", "action", "==", "'global-include'", ":", "for", "pattern", "in", "patterns", ":", "if", "not", "self", ".", "_include_pattern", "(", "pattern", ",", "anchor", "=", "False", ")", ":", "logger", ".", "warning", "(", "'no files found matching %r '", "'anywhere in distribution'", ",", "pattern", ")", "elif", "action", "==", "'global-exclude'", ":", "for", "pattern", "in", "patterns", ":", "found", "=", "self", ".", "_exclude_pattern", "(", "pattern", ",", "anchor", "=", "False", ")", "#if not found:", "# logger.warning('no previously-included files '", "# 'matching %r found anywhere in '", "# 'distribution', pattern)", "elif", "action", "==", "'recursive-include'", ":", "for", "pattern", "in", "patterns", ":", "if", "not", "self", ".", "_include_pattern", "(", "pattern", ",", "prefix", "=", "thedir", ")", ":", "logger", ".", "warning", "(", "'no files found matching %r '", "'under directory %r'", ",", "pattern", ",", "thedir", ")", "elif", "action", "==", "'recursive-exclude'", ":", "for", "pattern", "in", "patterns", ":", "found", "=", "self", ".", "_exclude_pattern", "(", "pattern", ",", "prefix", "=", "thedir", ")", "#if not found:", "# logger.warning('no previously-included files '", "# 'matching %r found under directory %r',", "# pattern, thedir)", "elif", "action", "==", "'graft'", ":", "if", "not", "self", ".", "_include_pattern", "(", "None", ",", "prefix", "=", "dirpattern", ")", ":", "logger", ".", "warning", "(", "'no directories found matching %r'", ",", "dirpattern", ")", "elif", "action", "==", "'prune'", ":", "if", "not", "self", ".", "_exclude_pattern", "(", "None", ",", "prefix", "=", "dirpattern", ")", ":", "logger", ".", "warning", "(", "'no previously-included directories found '", "'matching %r'", ",", "dirpattern", ")", "else", ":", "# pragma: no cover", "# This should never happen, as it should be caught in", "# _parse_template_line", "raise", "DistlibException", "(", "'invalid action %r'", "%", "action", ")" ]
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.org/distutils/sourcedist.html#commands
[ "Process", "a", "directive", "which", "either", "adds", "some", "files", "from", "allfiles", "to", "files", "or", "removes", "some", "files", "from", "files", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L130-L203
25,620
pypa/pipenv
pipenv/vendor/distlib/manifest.py
Manifest._glob_to_re
def _glob_to_re(self, pattern): """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). """ 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 they shouldn't match such "special characters" under # any OS. So change all non-escaped dots in the RE to match any # character except the special characters (currently: just os.sep). sep = os.sep if os.sep == '\\': # we're using a regex to manipulate a regex, so we need # to escape the backslash twice sep = r'\\\\' escaped = r'\1[^%s]' % sep pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re) return pattern_re
python
def _glob_to_re(self, pattern): """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). """ 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 they shouldn't match such "special characters" under # any OS. So change all non-escaped dots in the RE to match any # character except the special characters (currently: just os.sep). sep = os.sep if os.sep == '\\': # we're using a regex to manipulate a regex, so we need # to escape the backslash twice sep = r'\\\\' escaped = r'\1[^%s]' % sep pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re) return pattern_re
[ "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 they shouldn't match such \"special characters\" under", "# any OS. So change all non-escaped dots in the RE to match any", "# character except the special characters (currently: just os.sep).", "sep", "=", "os", ".", "sep", "if", "os", ".", "sep", "==", "'\\\\'", ":", "# we're using a regex to manipulate a regex, so we need", "# to escape the backslash twice", "sep", "=", "r'\\\\\\\\'", "escaped", "=", "r'\\1[^%s]'", "%", "sep", "pattern_re", "=", "re", ".", "sub", "(", "r'((?<!\\\\)(\\\\\\\\)*)\\.'", ",", "escaped", ",", "pattern_re", ")", "return", "pattern_re" ]
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).
[ "Translate", "a", "shell", "-", "like", "glob", "pattern", "to", "a", "regular", "expression", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L372-L393
25,621
pypa/pipenv
pipenv/vendor/requests/cookies.py
extract_cookies_to_jar
def extract_cookies_to_jar(jar, request, response): """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 """ if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req)
python
def extract_cookies_to_jar(jar, request, response): """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 """ if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req)
[ "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", "(", "request", ")", "# pull out the HTTPMessage with the headers and put it in the mock:", "res", "=", "MockResponse", "(", "response", ".", "_original_response", ".", "msg", ")", "jar", ".", "extract_cookies", "(", "res", ",", "req", ")" ]
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
[ "Extract", "the", "cookies", "from", "the", "response", "into", "a", "CookieJar", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L118-L132
25,622
pypa/pipenv
pipenv/vendor/requests/cookies.py
get_cookie_header
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 r.get_new_headers().get('Cookie')
python
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 r.get_new_headers().get('Cookie')
[ "def", "get_cookie_header", "(", "jar", ",", "request", ")", ":", "r", "=", "MockRequest", "(", "request", ")", "jar", ".", "add_cookie_header", "(", "r", ")", "return", "r", ".", "get_new_headers", "(", ")", ".", "get", "(", "'Cookie'", ")" ]
Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str
[ "Produce", "an", "appropriate", "Cookie", "header", "string", "to", "be", "sent", "with", "request", "or", "None", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L135-L143
25,623
pypa/pipenv
pipenv/vendor/requests/cookies.py
remove_cookie_by_name
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 cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name)
python
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 cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name)
[ "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", "not", "None", "and", "path", "!=", "cookie", ".", "path", ":", "continue", "clearables", ".", "append", "(", "(", "cookie", ".", "domain", ",", "cookie", ".", "path", ",", "cookie", ".", "name", ")", ")", "for", "domain", ",", "path", ",", "name", "in", "clearables", ":", "cookiejar", ".", "clear", "(", "domain", ",", "path", ",", "name", ")" ]
Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n).
[ "Unsets", "a", "cookie", "by", "name", "by", "default", "over", "all", "domains", "and", "paths", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L146-L162
25,624
pypa/pipenv
pipenv/vendor/requests/cookies.py
merge_cookies
def merge_cookies(cookiejar, cookies): """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 """ if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError('You can only merge into CookieJar') if isinstance(cookies, dict): cookiejar = cookiejar_from_dict( cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
python
def merge_cookies(cookiejar, cookies): """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 """ if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError('You can only merge into CookieJar') if isinstance(cookies, dict): cookiejar = cookiejar_from_dict( cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
[ "def", "merge_cookies", "(", "cookiejar", ",", "cookies", ")", ":", "if", "not", "isinstance", "(", "cookiejar", ",", "cookielib", ".", "CookieJar", ")", ":", "raise", "ValueError", "(", "'You can only merge into CookieJar'", ")", "if", "isinstance", "(", "cookies", ",", "dict", ")", ":", "cookiejar", "=", "cookiejar_from_dict", "(", "cookies", ",", "cookiejar", "=", "cookiejar", ",", "overwrite", "=", "False", ")", "elif", "isinstance", "(", "cookies", ",", "cookielib", ".", "CookieJar", ")", ":", "try", ":", "cookiejar", ".", "update", "(", "cookies", ")", "except", "AttributeError", ":", "for", "cookie_in_jar", "in", "cookies", ":", "cookiejar", ".", "set_cookie", "(", "cookie_in_jar", ")", "return", "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
[ "Add", "cookies", "to", "cookiejar", "and", "returns", "a", "merged", "CookieJar", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L529-L549
25,625
pypa/pipenv
pipenv/vendor/requests/cookies.py
RequestsCookieJar.list_domains
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
python
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
[ "def", "list_domains", "(", "self", ")", ":", "domains", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "domain", "not", "in", "domains", ":", "domains", ".", "append", "(", "cookie", ".", "domain", ")", "return", "domains" ]
Utility method to list all the domains in the jar.
[ "Utility", "method", "to", "list", "all", "the", "domains", "in", "the", "jar", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L270-L276
25,626
pypa/pipenv
pipenv/vendor/requests/cookies.py
RequestsCookieJar.list_paths
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
python
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
[ "def", "list_paths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "path", "not", "in", "paths", ":", "paths", ".", "append", "(", "cookie", ".", "path", ")", "return", "paths" ]
Utility method to list all the paths in the jar.
[ "Utility", "method", "to", "list", "all", "the", "paths", "in", "the", "jar", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L278-L284
25,627
pypa/pipenv
pipenv/vendor/requests/cookies.py
RequestsCookieJar.multiple_domains
def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: return True domains.append(cookie.domain) return False
python
def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: return True domains.append(cookie.domain) return False
[ "def", "multiple_domains", "(", "self", ")", ":", "domains", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "domain", "is", "not", "None", "and", "cookie", ".", "domain", "in", "domains", ":", "return", "True", "domains", ".", "append", "(", "cookie", ".", "domain", ")", "return", "False" ]
Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool
[ "Returns", "True", "if", "there", "are", "multiple", "domains", "in", "the", "jar", ".", "Returns", "False", "otherwise", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L286-L297
25,628
pypa/pipenv
pipenv/vendor/requests/cookies.py
RequestsCookieJar.update
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: super(RequestsCookieJar, self).update(other)
python
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: super(RequestsCookieJar, self).update(other)
[ "def", "update", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "cookielib", ".", "CookieJar", ")", ":", "for", "cookie", "in", "other", ":", "self", ".", "set_cookie", "(", "copy", ".", "copy", "(", "cookie", ")", ")", "else", ":", "super", "(", "RequestsCookieJar", ",", "self", ")", ".", "update", "(", "other", ")" ]
Updates this jar with cookies from another CookieJar or dict-like
[ "Updates", "this", "jar", "with", "cookies", "from", "another", "CookieJar", "or", "dict", "-", "like" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L348-L354
25,629
pypa/pipenv
pipenv/vendor/requests/cookies.py
RequestsCookieJar._find
def _find(self, name, domain=None, path=None): """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: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
python
def _find(self, name, domain=None, path=None): """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: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
[ "def", "_find", "(", "self", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "name", "==", "name", ":", "if", "domain", "is", "None", "or", "cookie", ".", "domain", "==", "domain", ":", "if", "path", "is", "None", "or", "cookie", ".", "path", "==", "path", ":", "return", "cookie", ".", "value", "raise", "KeyError", "(", "'name=%r, domain=%r, path=%r'", "%", "(", "name", ",", "domain", ",", "path", ")", ")" ]
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: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value
[ "Requests", "uses", "this", "method", "internally", "to", "get", "cookie", "values", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L356-L374
25,630
pypa/pipenv
pipenv/vendor/requests/cookies.py
RequestsCookieJar.copy
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
python
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
[ "def", "copy", "(", "self", ")", ":", "new_cj", "=", "RequestsCookieJar", "(", ")", "new_cj", ".", "set_policy", "(", "self", ".", "get_policy", "(", ")", ")", "new_cj", ".", "update", "(", "self", ")", "return", "new_cj" ]
Return a copy of this RequestsCookieJar.
[ "Return", "a", "copy", "of", "this", "RequestsCookieJar", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L414-L419
25,631
pypa/pipenv
pipenv/vendor/pexpect/screen.py
constrain
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
python
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
[ "def", "constrain", "(", "n", ",", "min", ",", "max", ")", ":", "if", "n", "<", "min", ":", "return", "min", "if", "n", ">", "max", ":", "return", "max", "return", "n" ]
This returns a number, n constrained to the min and max bounds.
[ "This", "returns", "a", "number", "n", "constrained", "to", "the", "min", "and", "max", "bounds", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L60-L68
25,632
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.lf
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()
python
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()
[ "def", "lf", "(", "self", ")", ":", "old_r", "=", "self", ".", "cur_r", "self", ".", "cursor_down", "(", ")", "if", "old_r", "==", "self", ".", "cur_r", ":", "self", ".", "scroll_up", "(", ")", "self", ".", "erase_line", "(", ")" ]
This moves the cursor down with scrolling.
[ "This", "moves", "the", "cursor", "down", "with", "scrolling", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L176-L184
25,633
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.put_abs
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-1] = ch
python
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-1] = ch
[ "def", "put_abs", "(", "self", ",", "r", ",", "c", ",", "ch", ")", ":", "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", "-", "1", "]", "=", "ch" ]
Screen array starts at 1 index.
[ "Screen", "array", "starts", "at", "1", "index", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L200-L209
25,634
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.put
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)
python
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)
[ "def", "put", "(", "self", ",", "ch", ")", ":", "if", "isinstance", "(", "ch", ",", "bytes", ")", ":", "ch", "=", "self", ".", "_decode", "(", "ch", ")", "self", ".", "put_abs", "(", "self", ".", "cur_r", ",", "self", ".", "cur_c", ",", "ch", ")" ]
This puts a characters at the current cursor position.
[ "This", "puts", "a", "characters", "at", "the", "current", "cursor", "position", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L211-L218
25,635
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.get_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 (ce, 1, self.cols) if rs > re: rs, re = re, rs if cs > ce: cs, ce = ce, cs sc = [] for r in range (rs, re+1): line = u'' for c in range (cs, ce + 1): ch = self.get_abs (r,c) line = line + ch sc.append (line) return sc
python
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 (ce, 1, self.cols) if rs > re: rs, re = re, rs if cs > ce: cs, ce = ce, cs sc = [] for r in range (rs, re+1): line = u'' for c in range (cs, ce + 1): ch = self.get_abs (r,c) line = line + ch sc.append (line) return sc
[ "def", "get_region", "(", "self", ",", "rs", ",", "cs", ",", "re", ",", "ce", ")", ":", "rs", "=", "constrain", "(", "rs", ",", "1", ",", "self", ".", "rows", ")", "re", "=", "constrain", "(", "re", ",", "1", ",", "self", ".", "rows", ")", "cs", "=", "constrain", "(", "cs", ",", "1", ",", "self", ".", "cols", ")", "ce", "=", "constrain", "(", "ce", ",", "1", ",", "self", ".", "cols", ")", "if", "rs", ">", "re", ":", "rs", ",", "re", "=", "re", ",", "rs", "if", "cs", ">", "ce", ":", "cs", ",", "ce", "=", "ce", ",", "cs", "sc", "=", "[", "]", "for", "r", "in", "range", "(", "rs", ",", "re", "+", "1", ")", ":", "line", "=", "u''", "for", "c", "in", "range", "(", "cs", ",", "ce", "+", "1", ")", ":", "ch", "=", "self", ".", "get_abs", "(", "r", ",", "c", ")", "line", "=", "line", "+", "ch", "sc", ".", "append", "(", "line", ")", "return", "sc" ]
This returns a list of lines representing the region.
[ "This", "returns", "a", "list", "of", "lines", "representing", "the", "region", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L252-L271
25,636
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.cursor_constrain
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)
python
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)
[ "def", "cursor_constrain", "(", "self", ")", ":", "self", ".", "cur_r", "=", "constrain", "(", "self", ".", "cur_r", ",", "1", ",", "self", ".", "rows", ")", "self", ".", "cur_c", "=", "constrain", "(", "self", ".", "cur_c", ",", "1", ",", "self", ".", "cols", ")" ]
This keeps the cursor within the screen area.
[ "This", "keeps", "the", "cursor", "within", "the", "screen", "area", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L273-L278
25,637
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.cursor_save_attrs
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
python
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
[ "def", "cursor_save_attrs", "(", "self", ")", ":", "# <ESC>7", "self", ".", "cur_saved_r", "=", "self", ".", "cur_r", "self", ".", "cur_saved_c", "=", "self", ".", "cur_c" ]
Save current cursor position.
[ "Save", "current", "cursor", "position", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L328-L332
25,638
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.scroll_constrain
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
python
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
[ "def", "scroll_constrain", "(", "self", ")", ":", "if", "self", ".", "scroll_row_start", "<=", "0", ":", "self", ".", "scroll_row_start", "=", "1", "if", "self", ".", "scroll_row_end", ">", "self", ".", "rows", ":", "self", ".", "scroll_row_end", "=", "self", ".", "rows" ]
This keeps the scroll region within the screen region.
[ "This", "keeps", "the", "scroll", "region", "within", "the", "screen", "region", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L339-L345
25,639
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.scroll_down
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])
python
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])
[ "def", "scroll_down", "(", "self", ")", ":", "# <ESC>D", "# 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", "]", ")" ]
Scroll display down one line.
[ "Scroll", "display", "down", "one", "line", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L360-L366
25,640
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.erase_end_of_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)
python
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)
[ "def", "erase_end_of_line", "(", "self", ")", ":", "# <ESC>[0K -or- <ESC>[K", "self", ".", "fill_region", "(", "self", ".", "cur_r", ",", "self", ".", "cur_c", ",", "self", ".", "cur_r", ",", "self", ".", "cols", ")" ]
Erases from the current cursor position to the end of the current line.
[ "Erases", "from", "the", "current", "cursor", "position", "to", "the", "end", "of", "the", "current", "line", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L376-L380
25,641
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.erase_start_of_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)
python
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)
[ "def", "erase_start_of_line", "(", "self", ")", ":", "# <ESC>[1K", "self", ".", "fill_region", "(", "self", ".", "cur_r", ",", "1", ",", "self", ".", "cur_r", ",", "self", ".", "cur_c", ")" ]
Erases from the current cursor position to the start of the current line.
[ "Erases", "from", "the", "current", "cursor", "position", "to", "the", "start", "of", "the", "current", "line", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L382-L386
25,642
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.erase_line
def erase_line (self): # <ESC>[2K '''Erases the entire current line.''' self.fill_region (self.cur_r, 1, self.cur_r, self.cols)
python
def erase_line (self): # <ESC>[2K '''Erases the entire current line.''' self.fill_region (self.cur_r, 1, self.cur_r, self.cols)
[ "def", "erase_line", "(", "self", ")", ":", "# <ESC>[2K", "self", ".", "fill_region", "(", "self", ".", "cur_r", ",", "1", ",", "self", ".", "cur_r", ",", "self", ".", "cols", ")" ]
Erases the entire current line.
[ "Erases", "the", "entire", "current", "line", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L388-L391
25,643
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.erase_down
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, self.cols)
python
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, self.cols)
[ "def", "erase_down", "(", "self", ")", ":", "# <ESC>[0J -or- <ESC>[J", "self", ".", "erase_end_of_line", "(", ")", "self", ".", "fill_region", "(", "self", ".", "cur_r", "+", "1", ",", "1", ",", "self", ".", "rows", ",", "self", ".", "cols", ")" ]
Erases the screen from the current line down to the bottom of the screen.
[ "Erases", "the", "screen", "from", "the", "current", "line", "down", "to", "the", "bottom", "of", "the", "screen", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L393-L398
25,644
pypa/pipenv
pipenv/vendor/pexpect/screen.py
screen.erase_up
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)
python
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)
[ "def", "erase_up", "(", "self", ")", ":", "# <ESC>[1J", "self", ".", "erase_start_of_line", "(", ")", "self", ".", "fill_region", "(", "self", ".", "cur_r", "-", "1", ",", "1", ",", "1", ",", "self", ".", "cols", ")" ]
Erases the screen from the current line up to the top of the screen.
[ "Erases", "the", "screen", "from", "the", "current", "line", "up", "to", "the", "top", "of", "the", "screen", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L400-L405
25,645
pypa/pipenv
pipenv/vendor/iso8601/iso8601.py
to_int
def to_int(d, key, default_to_zero=False, default=None, required=True): """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 """ value = d.get(key) or default if (value in ["", None]) and default_to_zero: return 0 if value is None: if required: raise ParseError("Unable to read %s from %s" % (key, d)) else: return int(value)
python
def to_int(d, key, default_to_zero=False, default=None, required=True): """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 """ value = d.get(key) or default if (value in ["", None]) and default_to_zero: return 0 if value is None: if required: raise ParseError("Unable to read %s from %s" % (key, d)) else: return int(value)
[ "def", "to_int", "(", "d", ",", "key", ",", "default_to_zero", "=", "False", ",", "default", "=", "None", ",", "required", "=", "True", ")", ":", "value", "=", "d", ".", "get", "(", "key", ")", "or", "default", "if", "(", "value", "in", "[", "\"\"", ",", "None", "]", ")", "and", "default_to_zero", ":", "return", "0", "if", "value", "is", "None", ":", "if", "required", ":", "raise", "ParseError", "(", "\"Unable to read %s from %s\"", "%", "(", "key", ",", "d", ")", ")", "else", ":", "return", "int", "(", "value", ")" ]
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
[ "Pull", "a", "value", "from", "the", "dict", "and", "convert", "to", "int" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/iso8601/iso8601.py#L137-L151
25,646
pypa/pipenv
pipenv/vendor/iso8601/iso8601.py
parse_date
def parse_date(datestring, default_timezone=UTC): """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 to parse as a string :param default_timezone: A datetime tzinfo instance to use when no timezone is specified in the datestring. If this is set to None then a naive datetime object is returned. :returns: A datetime.datetime instance :raises: ParseError when there is a problem parsing the date or constructing the datetime instance. """ if not isinstance(datestring, _basestring): raise ParseError("Expecting a string %r" % datestring) m = ISO8601_REGEX.match(datestring) if not m: raise ParseError("Unable to parse date string %r" % datestring) groups = m.groupdict() tz = parse_timezone(groups, default_timezone=default_timezone) groups["second_fraction"] = int(Decimal("0.%s" % (groups["second_fraction"] or 0)) * Decimal("1000000.0")) try: return datetime.datetime( year=to_int(groups, "year"), month=to_int(groups, "month", default=to_int(groups, "monthdash", required=False, default=1)), day=to_int(groups, "day", default=to_int(groups, "daydash", required=False, default=1)), hour=to_int(groups, "hour", default_to_zero=True), minute=to_int(groups, "minute", default_to_zero=True), second=to_int(groups, "second", default_to_zero=True), microsecond=groups["second_fraction"], tzinfo=tz, ) except Exception as e: raise ParseError(e)
python
def parse_date(datestring, default_timezone=UTC): """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 to parse as a string :param default_timezone: A datetime tzinfo instance to use when no timezone is specified in the datestring. If this is set to None then a naive datetime object is returned. :returns: A datetime.datetime instance :raises: ParseError when there is a problem parsing the date or constructing the datetime instance. """ if not isinstance(datestring, _basestring): raise ParseError("Expecting a string %r" % datestring) m = ISO8601_REGEX.match(datestring) if not m: raise ParseError("Unable to parse date string %r" % datestring) groups = m.groupdict() tz = parse_timezone(groups, default_timezone=default_timezone) groups["second_fraction"] = int(Decimal("0.%s" % (groups["second_fraction"] or 0)) * Decimal("1000000.0")) try: return datetime.datetime( year=to_int(groups, "year"), month=to_int(groups, "month", default=to_int(groups, "monthdash", required=False, default=1)), day=to_int(groups, "day", default=to_int(groups, "daydash", required=False, default=1)), hour=to_int(groups, "hour", default_to_zero=True), minute=to_int(groups, "minute", default_to_zero=True), second=to_int(groups, "second", default_to_zero=True), microsecond=groups["second_fraction"], tzinfo=tz, ) except Exception as e: raise ParseError(e)
[ "def", "parse_date", "(", "datestring", ",", "default_timezone", "=", "UTC", ")", ":", "if", "not", "isinstance", "(", "datestring", ",", "_basestring", ")", ":", "raise", "ParseError", "(", "\"Expecting a string %r\"", "%", "datestring", ")", "m", "=", "ISO8601_REGEX", ".", "match", "(", "datestring", ")", "if", "not", "m", ":", "raise", "ParseError", "(", "\"Unable to parse date string %r\"", "%", "datestring", ")", "groups", "=", "m", ".", "groupdict", "(", ")", "tz", "=", "parse_timezone", "(", "groups", ",", "default_timezone", "=", "default_timezone", ")", "groups", "[", "\"second_fraction\"", "]", "=", "int", "(", "Decimal", "(", "\"0.%s\"", "%", "(", "groups", "[", "\"second_fraction\"", "]", "or", "0", ")", ")", "*", "Decimal", "(", "\"1000000.0\"", ")", ")", "try", ":", "return", "datetime", ".", "datetime", "(", "year", "=", "to_int", "(", "groups", ",", "\"year\"", ")", ",", "month", "=", "to_int", "(", "groups", ",", "\"month\"", ",", "default", "=", "to_int", "(", "groups", ",", "\"monthdash\"", ",", "required", "=", "False", ",", "default", "=", "1", ")", ")", ",", "day", "=", "to_int", "(", "groups", ",", "\"day\"", ",", "default", "=", "to_int", "(", "groups", ",", "\"daydash\"", ",", "required", "=", "False", ",", "default", "=", "1", ")", ")", ",", "hour", "=", "to_int", "(", "groups", ",", "\"hour\"", ",", "default_to_zero", "=", "True", ")", ",", "minute", "=", "to_int", "(", "groups", ",", "\"minute\"", ",", "default_to_zero", "=", "True", ")", ",", "second", "=", "to_int", "(", "groups", ",", "\"second\"", ",", "default_to_zero", "=", "True", ")", ",", "microsecond", "=", "groups", "[", "\"second_fraction\"", "]", ",", "tzinfo", "=", "tz", ",", ")", "except", "Exception", "as", "e", ":", "raise", "ParseError", "(", "e", ")" ]
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 to parse as a string :param default_timezone: A datetime tzinfo instance to use when no timezone is specified in the datestring. If this is set to None then a naive datetime object is returned. :returns: A datetime.datetime instance :raises: ParseError when there is a problem parsing the date or constructing the datetime instance.
[ "Parses", "ISO", "8601", "dates", "into", "datetime", "objects" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/iso8601/iso8601.py#L174-L214
25,647
pypa/pipenv
pipenv/vendor/idna/core.py
uts46_remap
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): code_point = ord(char) uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1] status = uts46row[1] replacement = uts46row[2] if len(uts46row) == 3 else None if (status == "V" or (status == "D" and not transitional) or (status == "3" and not std3_rules and replacement is None)): output += char elif replacement is not None and (status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional)): output += replacement elif status != "I": raise IndexError() return unicodedata.normalize("NFC", output) except IndexError: raise InvalidCodepoint( "Codepoint {0} not allowed at position {1} in {2}".format( _unot(code_point), pos + 1, repr(domain)))
python
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): code_point = ord(char) uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1] status = uts46row[1] replacement = uts46row[2] if len(uts46row) == 3 else None if (status == "V" or (status == "D" and not transitional) or (status == "3" and not std3_rules and replacement is None)): output += char elif replacement is not None and (status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional)): output += replacement elif status != "I": raise IndexError() return unicodedata.normalize("NFC", output) except IndexError: raise InvalidCodepoint( "Codepoint {0} not allowed at position {1} in {2}".format( _unot(code_point), pos + 1, repr(domain)))
[ "def", "uts46_remap", "(", "domain", ",", "std3_rules", "=", "True", ",", "transitional", "=", "False", ")", ":", "from", ".", "uts46data", "import", "uts46data", "output", "=", "u\"\"", "try", ":", "for", "pos", ",", "char", "in", "enumerate", "(", "domain", ")", ":", "code_point", "=", "ord", "(", "char", ")", "uts46row", "=", "uts46data", "[", "code_point", "if", "code_point", "<", "256", "else", "bisect", ".", "bisect_left", "(", "uts46data", ",", "(", "code_point", ",", "\"Z\"", ")", ")", "-", "1", "]", "status", "=", "uts46row", "[", "1", "]", "replacement", "=", "uts46row", "[", "2", "]", "if", "len", "(", "uts46row", ")", "==", "3", "else", "None", "if", "(", "status", "==", "\"V\"", "or", "(", "status", "==", "\"D\"", "and", "not", "transitional", ")", "or", "(", "status", "==", "\"3\"", "and", "not", "std3_rules", "and", "replacement", "is", "None", ")", ")", ":", "output", "+=", "char", "elif", "replacement", "is", "not", "None", "and", "(", "status", "==", "\"M\"", "or", "(", "status", "==", "\"3\"", "and", "not", "std3_rules", ")", "or", "(", "status", "==", "\"D\"", "and", "transitional", ")", ")", ":", "output", "+=", "replacement", "elif", "status", "!=", "\"I\"", ":", "raise", "IndexError", "(", ")", "return", "unicodedata", ".", "normalize", "(", "\"NFC\"", ",", "output", ")", "except", "IndexError", ":", "raise", "InvalidCodepoint", "(", "\"Codepoint {0} not allowed at position {1} in {2}\"", ".", "format", "(", "_unot", "(", "code_point", ")", ",", "pos", "+", "1", ",", "repr", "(", "domain", ")", ")", ")" ]
Re-map the characters in the string according to UTS46 processing.
[ "Re", "-", "map", "the", "characters", "in", "the", "string", "according", "to", "UTS46", "processing", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/idna/core.py#L312-L337
25,648
pypa/pipenv
pipenv/vendor/requests/help.py
_implementation
def _implementation(): """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 doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == 'CPython': implementation_version = platform.python_version() elif implementation == 'PyPy': implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': implementation_version = ''.join([ implementation_version, sys.pypy_version_info.releaselevel ]) elif implementation == 'Jython': implementation_version = platform.python_version() # Complete Guess elif implementation == 'IronPython': implementation_version = platform.python_version() # Complete Guess else: implementation_version = 'Unknown' return {'name': implementation, 'version': implementation_version}
python
def _implementation(): """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 doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == 'CPython': implementation_version = platform.python_version() elif implementation == 'PyPy': implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': implementation_version = ''.join([ implementation_version, sys.pypy_version_info.releaselevel ]) elif implementation == 'Jython': implementation_version = platform.python_version() # Complete Guess elif implementation == 'IronPython': implementation_version = platform.python_version() # Complete Guess else: implementation_version = 'Unknown' return {'name': implementation, 'version': implementation_version}
[ "def", "_implementation", "(", ")", ":", "implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "implementation", "==", "'CPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "elif", "implementation", "==", "'PyPy'", ":", "implementation_version", "=", "'%s.%s.%s'", "%", "(", "sys", ".", "pypy_version_info", ".", "major", ",", "sys", ".", "pypy_version_info", ".", "minor", ",", "sys", ".", "pypy_version_info", ".", "micro", ")", "if", "sys", ".", "pypy_version_info", ".", "releaselevel", "!=", "'final'", ":", "implementation_version", "=", "''", ".", "join", "(", "[", "implementation_version", ",", "sys", ".", "pypy_version_info", ".", "releaselevel", "]", ")", "elif", "implementation", "==", "'Jython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "# Complete Guess", "elif", "implementation", "==", "'IronPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "# Complete Guess", "else", ":", "implementation_version", "=", "'Unknown'", "return", "{", "'name'", ":", "implementation", ",", "'version'", ":", "implementation_version", "}" ]
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 doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms.
[ "Return", "a", "dict", "with", "the", "Python", "implementation", "and", "version", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/help.py#L26-L56
25,649
pypa/pipenv
pipenv/vendor/requests/help.py
info
def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } implementation_info = _implementation() urllib3_info = {'version': urllib3.__version__} chardet_info = {'version': chardet.__version__} pyopenssl_info = { 'version': None, 'openssl_version': '', } if OpenSSL: pyopenssl_info = { 'version': OpenSSL.__version__, 'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER, } cryptography_info = { 'version': getattr(cryptography, '__version__', ''), } idna_info = { 'version': getattr(idna, '__version__', ''), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = { 'version': '%x' % system_ssl if system_ssl is not None else '' } return { 'platform': platform_info, 'implementation': implementation_info, 'system_ssl': system_ssl_info, 'using_pyopenssl': pyopenssl is not None, 'pyOpenSSL': pyopenssl_info, 'urllib3': urllib3_info, 'chardet': chardet_info, 'cryptography': cryptography_info, 'idna': idna_info, 'requests': { 'version': requests_version, }, }
python
def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } implementation_info = _implementation() urllib3_info = {'version': urllib3.__version__} chardet_info = {'version': chardet.__version__} pyopenssl_info = { 'version': None, 'openssl_version': '', } if OpenSSL: pyopenssl_info = { 'version': OpenSSL.__version__, 'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER, } cryptography_info = { 'version': getattr(cryptography, '__version__', ''), } idna_info = { 'version': getattr(idna, '__version__', ''), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = { 'version': '%x' % system_ssl if system_ssl is not None else '' } return { 'platform': platform_info, 'implementation': implementation_info, 'system_ssl': system_ssl_info, 'using_pyopenssl': pyopenssl is not None, 'pyOpenSSL': pyopenssl_info, 'urllib3': urllib3_info, 'chardet': chardet_info, 'cryptography': cryptography_info, 'idna': idna_info, 'requests': { 'version': requests_version, }, }
[ "def", "info", "(", ")", ":", "try", ":", "platform_info", "=", "{", "'system'", ":", "platform", ".", "system", "(", ")", ",", "'release'", ":", "platform", ".", "release", "(", ")", ",", "}", "except", "IOError", ":", "platform_info", "=", "{", "'system'", ":", "'Unknown'", ",", "'release'", ":", "'Unknown'", ",", "}", "implementation_info", "=", "_implementation", "(", ")", "urllib3_info", "=", "{", "'version'", ":", "urllib3", ".", "__version__", "}", "chardet_info", "=", "{", "'version'", ":", "chardet", ".", "__version__", "}", "pyopenssl_info", "=", "{", "'version'", ":", "None", ",", "'openssl_version'", ":", "''", ",", "}", "if", "OpenSSL", ":", "pyopenssl_info", "=", "{", "'version'", ":", "OpenSSL", ".", "__version__", ",", "'openssl_version'", ":", "'%x'", "%", "OpenSSL", ".", "SSL", ".", "OPENSSL_VERSION_NUMBER", ",", "}", "cryptography_info", "=", "{", "'version'", ":", "getattr", "(", "cryptography", ",", "'__version__'", ",", "''", ")", ",", "}", "idna_info", "=", "{", "'version'", ":", "getattr", "(", "idna", ",", "'__version__'", ",", "''", ")", ",", "}", "system_ssl", "=", "ssl", ".", "OPENSSL_VERSION_NUMBER", "system_ssl_info", "=", "{", "'version'", ":", "'%x'", "%", "system_ssl", "if", "system_ssl", "is", "not", "None", "else", "''", "}", "return", "{", "'platform'", ":", "platform_info", ",", "'implementation'", ":", "implementation_info", ",", "'system_ssl'", ":", "system_ssl_info", ",", "'using_pyopenssl'", ":", "pyopenssl", "is", "not", "None", ",", "'pyOpenSSL'", ":", "pyopenssl_info", ",", "'urllib3'", ":", "urllib3_info", ",", "'chardet'", ":", "chardet_info", ",", "'cryptography'", ":", "cryptography_info", ",", "'idna'", ":", "idna_info", ",", "'requests'", ":", "{", "'version'", ":", "requests_version", ",", "}", ",", "}" ]
Generate information for a bug report.
[ "Generate", "information", "for", "a", "bug", "report", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/help.py#L59-L110
25,650
pypa/pipenv
pipenv/vendor/pexpect/ANSI.py
ANSI.write
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: self.process(c)
python
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: self.process(c)
[ "def", "write", "(", "self", ",", "s", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "s", "=", "self", ".", "_decode", "(", "s", ")", "for", "c", "in", "s", ":", "self", ".", "process", "(", "c", ")" ]
Process text, writing it to the virtual screen while handling ANSI escape codes.
[ "Process", "text", "writing", "it", "to", "the", "virtual", "screen", "while", "handling", "ANSI", "escape", "codes", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/ANSI.py#L291-L298
25,651
pypa/pipenv
pipenv/vendor/pexpect/ANSI.py
ANSI.write_ch
def write_ch (self, ch): '''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. ''' if isinstance(ch, bytes): ch = self._decode(ch) #\r and \n both produce a call to cr() and lf(), respectively. ch = ch[0] if ch == u'\r': self.cr() return if ch == u'\n': self.crlf() return if ch == chr(screen.BS): self.cursor_back() return self.put_abs(self.cur_r, self.cur_c, ch) old_r = self.cur_r old_c = self.cur_c self.cursor_forward() if old_c == self.cur_c: self.cursor_down() if old_r != self.cur_r: self.cursor_home (self.cur_r, 1) else: self.scroll_up () self.cursor_home (self.cur_r, 1) self.erase_line()
python
def write_ch (self, ch): '''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. ''' if isinstance(ch, bytes): ch = self._decode(ch) #\r and \n both produce a call to cr() and lf(), respectively. ch = ch[0] if ch == u'\r': self.cr() return if ch == u'\n': self.crlf() return if ch == chr(screen.BS): self.cursor_back() return self.put_abs(self.cur_r, self.cur_c, ch) old_r = self.cur_r old_c = self.cur_c self.cursor_forward() if old_c == self.cur_c: self.cursor_down() if old_r != self.cur_r: self.cursor_home (self.cur_r, 1) else: self.scroll_up () self.cursor_home (self.cur_r, 1) self.erase_line()
[ "def", "write_ch", "(", "self", ",", "ch", ")", ":", "if", "isinstance", "(", "ch", ",", "bytes", ")", ":", "ch", "=", "self", ".", "_decode", "(", "ch", ")", "#\\r and \\n both produce a call to cr() and lf(), respectively.", "ch", "=", "ch", "[", "0", "]", "if", "ch", "==", "u'\\r'", ":", "self", ".", "cr", "(", ")", "return", "if", "ch", "==", "u'\\n'", ":", "self", ".", "crlf", "(", ")", "return", "if", "ch", "==", "chr", "(", "screen", ".", "BS", ")", ":", "self", ".", "cursor_back", "(", ")", "return", "self", ".", "put_abs", "(", "self", ".", "cur_r", ",", "self", ".", "cur_c", ",", "ch", ")", "old_r", "=", "self", ".", "cur_r", "old_c", "=", "self", ".", "cur_c", "self", ".", "cursor_forward", "(", ")", "if", "old_c", "==", "self", ".", "cur_c", ":", "self", ".", "cursor_down", "(", ")", "if", "old_r", "!=", "self", ".", "cur_r", ":", "self", ".", "cursor_home", "(", "self", ".", "cur_r", ",", "1", ")", "else", ":", "self", ".", "scroll_up", "(", ")", "self", ".", "cursor_home", "(", "self", ".", "cur_r", ",", "1", ")", "self", ".", "erase_line", "(", ")" ]
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.
[ "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", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/ANSI.py#L303-L334
25,652
pypa/pipenv
pipenv/vendor/click/_compat.py
get_best_encoding
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
python
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
[ "def", "get_best_encoding", "(", "stream", ")", ":", "rv", "=", "getattr", "(", "stream", ",", "'encoding'", ",", "None", ")", "or", "sys", ".", "getdefaultencoding", "(", ")", "if", "is_ascii_encoding", "(", "rv", ")", ":", "return", "'utf-8'", "return", "rv" ]
Returns the default stream encoding if not found.
[ "Returns", "the", "default", "stream", "encoding", "if", "not", "found", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_compat.py#L45-L50
25,653
pypa/pipenv
pipenv/vendor/backports/shutil_get_terminal_size/get_terminal_size.py
get_terminal_size
def get_terminal_size(fallback=(80, 24)): """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 connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. """ # Try the environment first try: columns = int(os.environ["COLUMNS"]) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ["LINES"]) except (KeyError, ValueError): lines = 0 # Only query if necessary if columns <= 0 or lines <= 0: try: size = _get_terminal_size(sys.__stdout__.fileno()) except (NameError, OSError): size = terminal_size(*fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return terminal_size(columns, lines)
python
def get_terminal_size(fallback=(80, 24)): """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 connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. """ # Try the environment first try: columns = int(os.environ["COLUMNS"]) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ["LINES"]) except (KeyError, ValueError): lines = 0 # Only query if necessary if columns <= 0 or lines <= 0: try: size = _get_terminal_size(sys.__stdout__.fileno()) except (NameError, OSError): size = terminal_size(*fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return terminal_size(columns, lines)
[ "def", "get_terminal_size", "(", "fallback", "=", "(", "80", ",", "24", ")", ")", ":", "# Try the environment first", "try", ":", "columns", "=", "int", "(", "os", ".", "environ", "[", "\"COLUMNS\"", "]", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "columns", "=", "0", "try", ":", "lines", "=", "int", "(", "os", ".", "environ", "[", "\"LINES\"", "]", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "lines", "=", "0", "# Only query if necessary", "if", "columns", "<=", "0", "or", "lines", "<=", "0", ":", "try", ":", "size", "=", "_get_terminal_size", "(", "sys", ".", "__stdout__", ".", "fileno", "(", ")", ")", "except", "(", "NameError", ",", "OSError", ")", ":", "size", "=", "terminal_size", "(", "*", "fallback", ")", "if", "columns", "<=", "0", ":", "columns", "=", "size", ".", "columns", "if", "lines", "<=", "0", ":", "lines", "=", "size", ".", "lines", "return", "terminal_size", "(", "columns", ",", "lines", ")" ]
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 connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size.
[ "Get", "the", "size", "of", "the", "terminal", "window", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/shutil_get_terminal_size/get_terminal_size.py#L58-L100
25,654
pypa/pipenv
pipenv/vendor/urllib3/util/request.py
set_file_position
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: rewind_body(body, pos) elif getattr(body, 'tell', None) is not None: try: pos = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body. pos = _FAILEDTELL return pos
python
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: rewind_body(body, pos) elif getattr(body, 'tell', None) is not None: try: pos = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body. pos = _FAILEDTELL return pos
[ "def", "set_file_position", "(", "body", ",", "pos", ")", ":", "if", "pos", "is", "not", "None", ":", "rewind_body", "(", "body", ",", "pos", ")", "elif", "getattr", "(", "body", ",", "'tell'", ",", "None", ")", "is", "not", "None", ":", "try", ":", "pos", "=", "body", ".", "tell", "(", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "# This differentiates from None, allowing us to catch", "# a failed `tell()` later when trying to rewind the body.", "pos", "=", "_FAILEDTELL", "return", "pos" ]
If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use.
[ "If", "a", "position", "is", "provided", "move", "file", "to", "that", "point", ".", "Otherwise", "we", "ll", "attempt", "to", "record", "a", "position", "for", "future", "use", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/request.py#L77-L92
25,655
pypa/pipenv
pipenv/vendor/urllib3/util/request.py
rewind_body
def rewind_body(body, body_pos): """ 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. """ body_seek = getattr(body, 'seek', None) if body_seek is not None and isinstance(body_pos, integer_types): try: body_seek(body_pos) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect/retry.") elif body_pos is _FAILEDTELL: raise UnrewindableBodyError("Unable to record file position for rewinding " "request body during a redirect/retry.") else: raise ValueError("body_pos must be of type integer, " "instead it was %s." % type(body_pos))
python
def rewind_body(body, body_pos): """ 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. """ body_seek = getattr(body, 'seek', None) if body_seek is not None and isinstance(body_pos, integer_types): try: body_seek(body_pos) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect/retry.") elif body_pos is _FAILEDTELL: raise UnrewindableBodyError("Unable to record file position for rewinding " "request body during a redirect/retry.") else: raise ValueError("body_pos must be of type integer, " "instead it was %s." % type(body_pos))
[ "def", "rewind_body", "(", "body", ",", "body_pos", ")", ":", "body_seek", "=", "getattr", "(", "body", ",", "'seek'", ",", "None", ")", "if", "body_seek", "is", "not", "None", "and", "isinstance", "(", "body_pos", ",", "integer_types", ")", ":", "try", ":", "body_seek", "(", "body_pos", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "raise", "UnrewindableBodyError", "(", "\"An error occurred when rewinding request \"", "\"body for redirect/retry.\"", ")", "elif", "body_pos", "is", "_FAILEDTELL", ":", "raise", "UnrewindableBodyError", "(", "\"Unable to record file position for rewinding \"", "\"request body during a redirect/retry.\"", ")", "else", ":", "raise", "ValueError", "(", "\"body_pos must be of type integer, \"", "\"instead it was %s.\"", "%", "type", "(", "body_pos", ")", ")" ]
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.
[ "Attempt", "to", "rewind", "body", "to", "a", "certain", "position", ".", "Primarily", "used", "for", "request", "redirects", "and", "retries", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/request.py#L95-L118
25,656
pypa/pipenv
pipenv/vendor/plette/lockfiles.py
_copy_jsonsafe
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 in value.items()} if isinstance(value, collections_abc.Iterable): return [_copy_jsonsafe(v) for v in value] if value is None: # This doesn't happen often for us. return None return six.text_type(value)
python
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 in value.items()} if isinstance(value, collections_abc.Iterable): return [_copy_jsonsafe(v) for v in value] if value is None: # This doesn't happen often for us. return None return six.text_type(value)
[ "def", "_copy_jsonsafe", "(", "value", ")", ":", "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", "in", "value", ".", "items", "(", ")", "}", "if", "isinstance", "(", "value", ",", "collections_abc", ".", "Iterable", ")", ":", "return", "[", "_copy_jsonsafe", "(", "v", ")", "for", "v", "in", "value", "]", "if", "value", "is", "None", ":", "# This doesn't happen often for us.", "return", "None", "return", "six", ".", "text_type", "(", "value", ")" ]
Deep-copy a value into JSON-safe types.
[ "Deep", "-", "copy", "a", "value", "into", "JSON", "-", "safe", "types", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/plette/lockfiles.py#L53-L64
25,657
pypa/pipenv
pipenv/patched/notpip/_vendor/cachecontrol/caches/redis_cache.py
RedisCache.clear
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)
python
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)
[ "def", "clear", "(", "self", ")", ":", "for", "key", "in", "self", ".", "conn", ".", "keys", "(", ")", ":", "self", ".", "conn", ".", "delete", "(", "key", ")" ]
Helper for clearing all the keys in a database. Use with caution!
[ "Helper", "for", "clearing", "all", "the", "keys", "in", "a", "database", ".", "Use", "with", "caution!" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/caches/redis_cache.py#L25-L29
25,658
pypa/pipenv
pipenv/vendor/attr/filters.py
_split_what
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)), )
python
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)), )
[ "def", "_split_what", "(", "what", ")", ":", "return", "(", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isclass", "(", "cls", ")", ")", ",", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isinstance", "(", "cls", ",", "Attribute", ")", ")", ",", ")" ]
Returns a tuple of `frozenset`s of classes and attributes.
[ "Returns", "a", "tuple", "of", "frozenset", "s", "of", "classes", "and", "attributes", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/filters.py#L11-L18
25,659
pypa/pipenv
pipenv/vendor/attr/_funcs.py
_asdict_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. rv = asdict(val, True, filter, dict_factory, retain_collection_types) elif isinstance(val, (tuple, list, set)): cf = val.__class__ if retain_collection_types is True else list rv = cf( [ _asdict_anything( i, filter, dict_factory, retain_collection_types ) for i in val ] ) elif isinstance(val, dict): df = dict_factory rv = df( ( _asdict_anything(kk, filter, df, retain_collection_types), _asdict_anything(vv, filter, df, retain_collection_types), ) for kk, vv in iteritems(val) ) else: rv = val return rv
python
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. rv = asdict(val, True, filter, dict_factory, retain_collection_types) elif isinstance(val, (tuple, list, set)): cf = val.__class__ if retain_collection_types is True else list rv = cf( [ _asdict_anything( i, filter, dict_factory, retain_collection_types ) for i in val ] ) elif isinstance(val, dict): df = dict_factory rv = df( ( _asdict_anything(kk, filter, df, retain_collection_types), _asdict_anything(vv, filter, df, retain_collection_types), ) for kk, vv in iteritems(val) ) else: rv = val return rv
[ "def", "_asdict_anything", "(", "val", ",", "filter", ",", "dict_factory", ",", "retain_collection_types", ")", ":", "if", "getattr", "(", "val", ".", "__class__", ",", "\"__attrs_attrs__\"", ",", "None", ")", "is", "not", "None", ":", "# Attrs class.", "rv", "=", "asdict", "(", "val", ",", "True", ",", "filter", ",", "dict_factory", ",", "retain_collection_types", ")", "elif", "isinstance", "(", "val", ",", "(", "tuple", ",", "list", ",", "set", ")", ")", ":", "cf", "=", "val", ".", "__class__", "if", "retain_collection_types", "is", "True", "else", "list", "rv", "=", "cf", "(", "[", "_asdict_anything", "(", "i", ",", "filter", ",", "dict_factory", ",", "retain_collection_types", ")", "for", "i", "in", "val", "]", ")", "elif", "isinstance", "(", "val", ",", "dict", ")", ":", "df", "=", "dict_factory", "rv", "=", "df", "(", "(", "_asdict_anything", "(", "kk", ",", "filter", ",", "df", ",", "retain_collection_types", ")", ",", "_asdict_anything", "(", "vv", ",", "filter", ",", "df", ",", "retain_collection_types", ")", ",", ")", "for", "kk", ",", "vv", "in", "iteritems", "(", "val", ")", ")", "else", ":", "rv", "=", "val", "return", "rv" ]
``asdict`` only works on attrs instances, this works on anything.
[ "asdict", "only", "works", "on", "attrs", "instances", "this", "works", "on", "anything", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_funcs.py#L85-L113
25,660
pypa/pipenv
pipenv/vendor/distlib/markers.py
interpret
def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: expr, rest = parse_marker(marker) except Exception as e: raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e)) if rest and rest[0] != '#': raise SyntaxError('unexpected trailing data in marker: %s: %s' % (marker, rest)) context = dict(DEFAULT_CONTEXT) if execution_context: context.update(execution_context) return evaluator.evaluate(expr, context)
python
def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: expr, rest = parse_marker(marker) except Exception as e: raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e)) if rest and rest[0] != '#': raise SyntaxError('unexpected trailing data in marker: %s: %s' % (marker, rest)) context = dict(DEFAULT_CONTEXT) if execution_context: context.update(execution_context) return evaluator.evaluate(expr, context)
[ "def", "interpret", "(", "marker", ",", "execution_context", "=", "None", ")", ":", "try", ":", "expr", ",", "rest", "=", "parse_marker", "(", "marker", ")", "except", "Exception", "as", "e", ":", "raise", "SyntaxError", "(", "'Unable to interpret marker syntax: %s: %s'", "%", "(", "marker", ",", "e", ")", ")", "if", "rest", "and", "rest", "[", "0", "]", "!=", "'#'", ":", "raise", "SyntaxError", "(", "'unexpected trailing data in marker: %s: %s'", "%", "(", "marker", ",", "rest", ")", ")", "context", "=", "dict", "(", "DEFAULT_CONTEXT", ")", "if", "execution_context", ":", "context", ".", "update", "(", "execution_context", ")", "return", "evaluator", ".", "evaluate", "(", "expr", ",", "context", ")" ]
Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping
[ "Interpret", "a", "marker", "and", "return", "a", "result", "depending", "on", "environment", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/markers.py#L113-L131
25,661
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._merge_ws
def _merge_ws(self, item, container): # type: (Item, Container) -> bool """ Merges the given Item with the last one currently in the given Container if both are whitespace items. Returns True if the items were merged. """ last = container.last_item() if not last: return False if not isinstance(item, Whitespace) or not isinstance(last, Whitespace): return False start = self._idx - (len(last.s) + len(item.s)) container.body[-1] = ( container.body[-1][0], Whitespace(self._src[start : self._idx]), ) return True
python
def _merge_ws(self, item, container): # type: (Item, Container) -> bool """ Merges the given Item with the last one currently in the given Container if both are whitespace items. Returns True if the items were merged. """ last = container.last_item() if not last: return False if not isinstance(item, Whitespace) or not isinstance(last, Whitespace): return False start = self._idx - (len(last.s) + len(item.s)) container.body[-1] = ( container.body[-1][0], Whitespace(self._src[start : self._idx]), ) return True
[ "def", "_merge_ws", "(", "self", ",", "item", ",", "container", ")", ":", "# type: (Item, Container) -> bool", "last", "=", "container", ".", "last_item", "(", ")", "if", "not", "last", ":", "return", "False", "if", "not", "isinstance", "(", "item", ",", "Whitespace", ")", "or", "not", "isinstance", "(", "last", ",", "Whitespace", ")", ":", "return", "False", "start", "=", "self", ".", "_idx", "-", "(", "len", "(", "last", ".", "s", ")", "+", "len", "(", "item", ".", "s", ")", ")", "container", ".", "body", "[", "-", "1", "]", "=", "(", "container", ".", "body", "[", "-", "1", "]", "[", "0", "]", ",", "Whitespace", "(", "self", ".", "_src", "[", "start", ":", "self", ".", "_idx", "]", ")", ",", ")", "return", "True" ]
Merges the given Item with the last one currently in the given Container if both are whitespace items. Returns True if the items were merged.
[ "Merges", "the", "given", "Item", "with", "the", "last", "one", "currently", "in", "the", "given", "Container", "if", "both", "are", "whitespace", "items", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L158-L178
25,662
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._is_child
def _is_child(self, parent, child): # type: (str, str) -> bool """ Returns whether a key is strictly a child of another key. AoT siblings are not considered children of one another. """ parent_parts = tuple(self._split_table_name(parent)) child_parts = tuple(self._split_table_name(child)) if parent_parts == child_parts: return False return parent_parts == child_parts[: len(parent_parts)]
python
def _is_child(self, parent, child): # type: (str, str) -> bool """ Returns whether a key is strictly a child of another key. AoT siblings are not considered children of one another. """ parent_parts = tuple(self._split_table_name(parent)) child_parts = tuple(self._split_table_name(child)) if parent_parts == child_parts: return False return parent_parts == child_parts[: len(parent_parts)]
[ "def", "_is_child", "(", "self", ",", "parent", ",", "child", ")", ":", "# type: (str, str) -> bool", "parent_parts", "=", "tuple", "(", "self", ".", "_split_table_name", "(", "parent", ")", ")", "child_parts", "=", "tuple", "(", "self", ".", "_split_table_name", "(", "child", ")", ")", "if", "parent_parts", "==", "child_parts", ":", "return", "False", "return", "parent_parts", "==", "child_parts", "[", ":", "len", "(", "parent_parts", ")", "]" ]
Returns whether a key is strictly a child of another key. AoT siblings are not considered children of one another.
[ "Returns", "whether", "a", "key", "is", "strictly", "a", "child", "of", "another", "key", ".", "AoT", "siblings", "are", "not", "considered", "children", "of", "one", "another", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L180-L191
25,663
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._parse_item
def _parse_item(self): # type: () -> Optional[Tuple[Optional[Key], Item]] """ Attempts to parse the next item and returns it, along with its key if the item is value-like. """ self.mark() with self._state as state: while True: c = self._current if c == "\n": # Found a newline; Return all whitespace found up to this point. self.inc() return None, Whitespace(self.extract()) elif c in " \t\r": # Skip whitespace. if not self.inc(): return None, Whitespace(self.extract()) elif c == "#": # Found a comment, parse it indent = self.extract() cws, comment, trail = self._parse_comment_trail() return None, Comment(Trivia(indent, cws, comment, trail)) elif c == "[": # Found a table, delegate to the calling function. return else: # Begining of a KV pair. # Return to beginning of whitespace so it gets included # as indentation for the KV about to be parsed. state.restore = True break return self._parse_key_value(True)
python
def _parse_item(self): # type: () -> Optional[Tuple[Optional[Key], Item]] """ Attempts to parse the next item and returns it, along with its key if the item is value-like. """ self.mark() with self._state as state: while True: c = self._current if c == "\n": # Found a newline; Return all whitespace found up to this point. self.inc() return None, Whitespace(self.extract()) elif c in " \t\r": # Skip whitespace. if not self.inc(): return None, Whitespace(self.extract()) elif c == "#": # Found a comment, parse it indent = self.extract() cws, comment, trail = self._parse_comment_trail() return None, Comment(Trivia(indent, cws, comment, trail)) elif c == "[": # Found a table, delegate to the calling function. return else: # Begining of a KV pair. # Return to beginning of whitespace so it gets included # as indentation for the KV about to be parsed. state.restore = True break return self._parse_key_value(True)
[ "def", "_parse_item", "(", "self", ")", ":", "# type: () -> Optional[Tuple[Optional[Key], Item]]", "self", ".", "mark", "(", ")", "with", "self", ".", "_state", "as", "state", ":", "while", "True", ":", "c", "=", "self", ".", "_current", "if", "c", "==", "\"\\n\"", ":", "# Found a newline; Return all whitespace found up to this point.", "self", ".", "inc", "(", ")", "return", "None", ",", "Whitespace", "(", "self", ".", "extract", "(", ")", ")", "elif", "c", "in", "\" \\t\\r\"", ":", "# Skip whitespace.", "if", "not", "self", ".", "inc", "(", ")", ":", "return", "None", ",", "Whitespace", "(", "self", ".", "extract", "(", ")", ")", "elif", "c", "==", "\"#\"", ":", "# Found a comment, parse it", "indent", "=", "self", ".", "extract", "(", ")", "cws", ",", "comment", ",", "trail", "=", "self", ".", "_parse_comment_trail", "(", ")", "return", "None", ",", "Comment", "(", "Trivia", "(", "indent", ",", "cws", ",", "comment", ",", "trail", ")", ")", "elif", "c", "==", "\"[\"", ":", "# Found a table, delegate to the calling function.", "return", "else", ":", "# Begining of a KV pair.", "# Return to beginning of whitespace so it gets included", "# as indentation for the KV about to be parsed.", "state", ".", "restore", "=", "True", "break", "return", "self", ".", "_parse_key_value", "(", "True", ")" ]
Attempts to parse the next item and returns it, along with its key if the item is value-like.
[ "Attempts", "to", "parse", "the", "next", "item", "and", "returns", "it", "along", "with", "its", "key", "if", "the", "item", "is", "value", "-", "like", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L236-L270
25,664
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._parse_quoted_key
def _parse_quoted_key(self): # type: () -> Key """ Parses a key enclosed in either single or double quotes. """ quote_style = self._current key_type = None dotted = False for t in KeyType: if t.value == quote_style: key_type = t break if key_type is None: raise RuntimeError("Should not have entered _parse_quoted_key()") self.inc() self.mark() while self._current != quote_style and self.inc(): pass key = self.extract() if self._current == ".": self.inc() dotted = True key += "." + self._parse_key().as_string() key_type = KeyType.Bare else: self.inc() return Key(key, key_type, "", dotted)
python
def _parse_quoted_key(self): # type: () -> Key """ Parses a key enclosed in either single or double quotes. """ quote_style = self._current key_type = None dotted = False for t in KeyType: if t.value == quote_style: key_type = t break if key_type is None: raise RuntimeError("Should not have entered _parse_quoted_key()") self.inc() self.mark() while self._current != quote_style and self.inc(): pass key = self.extract() if self._current == ".": self.inc() dotted = True key += "." + self._parse_key().as_string() key_type = KeyType.Bare else: self.inc() return Key(key, key_type, "", dotted)
[ "def", "_parse_quoted_key", "(", "self", ")", ":", "# type: () -> Key", "quote_style", "=", "self", ".", "_current", "key_type", "=", "None", "dotted", "=", "False", "for", "t", "in", "KeyType", ":", "if", "t", ".", "value", "==", "quote_style", ":", "key_type", "=", "t", "break", "if", "key_type", "is", "None", ":", "raise", "RuntimeError", "(", "\"Should not have entered _parse_quoted_key()\"", ")", "self", ".", "inc", "(", ")", "self", ".", "mark", "(", ")", "while", "self", ".", "_current", "!=", "quote_style", "and", "self", ".", "inc", "(", ")", ":", "pass", "key", "=", "self", ".", "extract", "(", ")", "if", "self", ".", "_current", "==", "\".\"", ":", "self", ".", "inc", "(", ")", "dotted", "=", "True", "key", "+=", "\".\"", "+", "self", ".", "_parse_key", "(", ")", ".", "as_string", "(", ")", "key_type", "=", "KeyType", ".", "Bare", "else", ":", "self", ".", "inc", "(", ")", "return", "Key", "(", "key", ",", "key_type", ",", "\"\"", ",", "dotted", ")" ]
Parses a key enclosed in either single or double quotes.
[ "Parses", "a", "key", "enclosed", "in", "either", "single", "or", "double", "quotes", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L381-L412
25,665
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._parse_bare_key
def _parse_bare_key(self): # type: () -> Key """ Parses a bare key. """ key_type = None dotted = False self.mark() while self._current.is_bare_key_char() and self.inc(): pass key = self.extract() if self._current == ".": self.inc() dotted = True key += "." + self._parse_key().as_string() key_type = KeyType.Bare return Key(key, key_type, "", dotted)
python
def _parse_bare_key(self): # type: () -> Key """ Parses a bare key. """ key_type = None dotted = False self.mark() while self._current.is_bare_key_char() and self.inc(): pass key = self.extract() if self._current == ".": self.inc() dotted = True key += "." + self._parse_key().as_string() key_type = KeyType.Bare return Key(key, key_type, "", dotted)
[ "def", "_parse_bare_key", "(", "self", ")", ":", "# type: () -> Key", "key_type", "=", "None", "dotted", "=", "False", "self", ".", "mark", "(", ")", "while", "self", ".", "_current", ".", "is_bare_key_char", "(", ")", "and", "self", ".", "inc", "(", ")", ":", "pass", "key", "=", "self", ".", "extract", "(", ")", "if", "self", ".", "_current", "==", "\".\"", ":", "self", ".", "inc", "(", ")", "dotted", "=", "True", "key", "+=", "\".\"", "+", "self", ".", "_parse_key", "(", ")", ".", "as_string", "(", ")", "key_type", "=", "KeyType", ".", "Bare", "return", "Key", "(", "key", ",", "key_type", ",", "\"\"", ",", "dotted", ")" ]
Parses a bare key.
[ "Parses", "a", "bare", "key", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L414-L433
25,666
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._parse_value
def _parse_value(self): # type: () -> Item """ Attempts to parse a value at the current position. """ self.mark() c = self._current trivia = Trivia() if c == StringType.SLB.value: return self._parse_basic_string() elif c == StringType.SLL.value: return self._parse_literal_string() elif c == BoolType.TRUE.value[0]: return self._parse_true() elif c == BoolType.FALSE.value[0]: return self._parse_false() elif c == "[": return self._parse_array() elif c == "{": return self._parse_inline_table() elif c in "+-" or self._peek(4) in { "+inf", "-inf", "inf", "+nan", "-nan", "nan", }: # Number while self._current not in " \t\n\r#,]}" and self.inc(): pass raw = self.extract() item = self._parse_number(raw, trivia) if item is not None: return item raise self.parse_error(InvalidNumberError) elif c in string.digits: # Integer, Float, Date, Time or DateTime while self._current not in " \t\n\r#,]}" and self.inc(): pass raw = self.extract() m = RFC_3339_LOOSE.match(raw) if m: if m.group(1) and m.group(5): # datetime try: return DateTime(parse_rfc3339(raw), trivia, raw) except ValueError: raise self.parse_error(InvalidDateTimeError) if m.group(1): try: return Date(parse_rfc3339(raw), trivia, raw) except ValueError: raise self.parse_error(InvalidDateError) if m.group(5): try: return Time(parse_rfc3339(raw), trivia, raw) except ValueError: raise self.parse_error(InvalidTimeError) item = self._parse_number(raw, trivia) if item is not None: return item raise self.parse_error(InvalidNumberError) else: raise self.parse_error(UnexpectedCharError, c)
python
def _parse_value(self): # type: () -> Item """ Attempts to parse a value at the current position. """ self.mark() c = self._current trivia = Trivia() if c == StringType.SLB.value: return self._parse_basic_string() elif c == StringType.SLL.value: return self._parse_literal_string() elif c == BoolType.TRUE.value[0]: return self._parse_true() elif c == BoolType.FALSE.value[0]: return self._parse_false() elif c == "[": return self._parse_array() elif c == "{": return self._parse_inline_table() elif c in "+-" or self._peek(4) in { "+inf", "-inf", "inf", "+nan", "-nan", "nan", }: # Number while self._current not in " \t\n\r#,]}" and self.inc(): pass raw = self.extract() item = self._parse_number(raw, trivia) if item is not None: return item raise self.parse_error(InvalidNumberError) elif c in string.digits: # Integer, Float, Date, Time or DateTime while self._current not in " \t\n\r#,]}" and self.inc(): pass raw = self.extract() m = RFC_3339_LOOSE.match(raw) if m: if m.group(1) and m.group(5): # datetime try: return DateTime(parse_rfc3339(raw), trivia, raw) except ValueError: raise self.parse_error(InvalidDateTimeError) if m.group(1): try: return Date(parse_rfc3339(raw), trivia, raw) except ValueError: raise self.parse_error(InvalidDateError) if m.group(5): try: return Time(parse_rfc3339(raw), trivia, raw) except ValueError: raise self.parse_error(InvalidTimeError) item = self._parse_number(raw, trivia) if item is not None: return item raise self.parse_error(InvalidNumberError) else: raise self.parse_error(UnexpectedCharError, c)
[ "def", "_parse_value", "(", "self", ")", ":", "# type: () -> Item", "self", ".", "mark", "(", ")", "c", "=", "self", ".", "_current", "trivia", "=", "Trivia", "(", ")", "if", "c", "==", "StringType", ".", "SLB", ".", "value", ":", "return", "self", ".", "_parse_basic_string", "(", ")", "elif", "c", "==", "StringType", ".", "SLL", ".", "value", ":", "return", "self", ".", "_parse_literal_string", "(", ")", "elif", "c", "==", "BoolType", ".", "TRUE", ".", "value", "[", "0", "]", ":", "return", "self", ".", "_parse_true", "(", ")", "elif", "c", "==", "BoolType", ".", "FALSE", ".", "value", "[", "0", "]", ":", "return", "self", ".", "_parse_false", "(", ")", "elif", "c", "==", "\"[\"", ":", "return", "self", ".", "_parse_array", "(", ")", "elif", "c", "==", "\"{\"", ":", "return", "self", ".", "_parse_inline_table", "(", ")", "elif", "c", "in", "\"+-\"", "or", "self", ".", "_peek", "(", "4", ")", "in", "{", "\"+inf\"", ",", "\"-inf\"", ",", "\"inf\"", ",", "\"+nan\"", ",", "\"-nan\"", ",", "\"nan\"", ",", "}", ":", "# Number", "while", "self", ".", "_current", "not", "in", "\" \\t\\n\\r#,]}\"", "and", "self", ".", "inc", "(", ")", ":", "pass", "raw", "=", "self", ".", "extract", "(", ")", "item", "=", "self", ".", "_parse_number", "(", "raw", ",", "trivia", ")", "if", "item", "is", "not", "None", ":", "return", "item", "raise", "self", ".", "parse_error", "(", "InvalidNumberError", ")", "elif", "c", "in", "string", ".", "digits", ":", "# Integer, Float, Date, Time or DateTime", "while", "self", ".", "_current", "not", "in", "\" \\t\\n\\r#,]}\"", "and", "self", ".", "inc", "(", ")", ":", "pass", "raw", "=", "self", ".", "extract", "(", ")", "m", "=", "RFC_3339_LOOSE", ".", "match", "(", "raw", ")", "if", "m", ":", "if", "m", ".", "group", "(", "1", ")", "and", "m", ".", "group", "(", "5", ")", ":", "# datetime", "try", ":", "return", "DateTime", "(", "parse_rfc3339", "(", "raw", ")", ",", "trivia", ",", "raw", ")", "except", "ValueError", ":", "raise", "self", ".", "parse_error", "(", "InvalidDateTimeError", ")", "if", "m", ".", "group", "(", "1", ")", ":", "try", ":", "return", "Date", "(", "parse_rfc3339", "(", "raw", ")", ",", "trivia", ",", "raw", ")", "except", "ValueError", ":", "raise", "self", ".", "parse_error", "(", "InvalidDateError", ")", "if", "m", ".", "group", "(", "5", ")", ":", "try", ":", "return", "Time", "(", "parse_rfc3339", "(", "raw", ")", ",", "trivia", ",", "raw", ")", "except", "ValueError", ":", "raise", "self", ".", "parse_error", "(", "InvalidTimeError", ")", "item", "=", "self", ".", "_parse_number", "(", "raw", ",", "trivia", ")", "if", "item", "is", "not", "None", ":", "return", "item", "raise", "self", ".", "parse_error", "(", "InvalidNumberError", ")", "else", ":", "raise", "self", ".", "parse_error", "(", "UnexpectedCharError", ",", "c", ")" ]
Attempts to parse a value at the current position.
[ "Attempts", "to", "parse", "a", "value", "at", "the", "current", "position", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L469-L542
25,667
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._parse_aot
def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT """ Parses all siblings of the provided table first and bundles them into an AoT. """ payload = [first] self._aot_stack.append(name_first) while not self.end(): is_aot_next, name_next = self._peek_table() if is_aot_next and name_next == name_first: _, table = self._parse_table(name_first) payload.append(table) else: break self._aot_stack.pop() return AoT(payload, parsed=True)
python
def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT """ Parses all siblings of the provided table first and bundles them into an AoT. """ payload = [first] self._aot_stack.append(name_first) while not self.end(): is_aot_next, name_next = self._peek_table() if is_aot_next and name_next == name_first: _, table = self._parse_table(name_first) payload.append(table) else: break self._aot_stack.pop() return AoT(payload, parsed=True)
[ "def", "_parse_aot", "(", "self", ",", "first", ",", "name_first", ")", ":", "# type: (Table, str) -> AoT", "payload", "=", "[", "first", "]", "self", ".", "_aot_stack", ".", "append", "(", "name_first", ")", "while", "not", "self", ".", "end", "(", ")", ":", "is_aot_next", ",", "name_next", "=", "self", ".", "_peek_table", "(", ")", "if", "is_aot_next", "and", "name_next", "==", "name_first", ":", "_", ",", "table", "=", "self", ".", "_parse_table", "(", "name_first", ")", "payload", ".", "append", "(", "table", ")", "else", ":", "break", "self", ".", "_aot_stack", ".", "pop", "(", ")", "return", "AoT", "(", "payload", ",", "parsed", "=", "True", ")" ]
Parses all siblings of the provided table first and bundles them into an AoT.
[ "Parses", "all", "siblings", "of", "the", "provided", "table", "first", "and", "bundles", "them", "into", "an", "AoT", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L1037-L1054
25,668
pypa/pipenv
pipenv/vendor/tomlkit/parser.py
Parser._peek
def _peek(self, n): # type: (int) -> str """ Peeks ahead n characters. n is the max number of characters that will be peeked. """ # we always want to restore after exiting this scope with self._state(restore=True): buf = "" for _ in range(n): if self._current not in " \t\n\r#,]}": buf += self._current self.inc() continue break return buf
python
def _peek(self, n): # type: (int) -> str """ Peeks ahead n characters. n is the max number of characters that will be peeked. """ # we always want to restore after exiting this scope with self._state(restore=True): buf = "" for _ in range(n): if self._current not in " \t\n\r#,]}": buf += self._current self.inc() continue break return buf
[ "def", "_peek", "(", "self", ",", "n", ")", ":", "# type: (int) -> str", "# we always want to restore after exiting this scope", "with", "self", ".", "_state", "(", "restore", "=", "True", ")", ":", "buf", "=", "\"\"", "for", "_", "in", "range", "(", "n", ")", ":", "if", "self", ".", "_current", "not", "in", "\" \\t\\n\\r#,]}\"", ":", "buf", "+=", "self", ".", "_current", "self", ".", "inc", "(", ")", "continue", "break", "return", "buf" ]
Peeks ahead n characters. n is the max number of characters that will be peeked.
[ "Peeks", "ahead", "n", "characters", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/parser.py#L1056-L1072
25,669
pypa/pipenv
pipenv/vendor/urllib3/util/url.py
split_first
def split_first(s, delims): """ Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims. """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, '', None return s[:min_idx], s[min_idx + 1:], min_delim
python
def split_first(s, delims): """ Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims. """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, '', None return s[:min_idx], s[min_idx + 1:], min_delim
[ "def", "split_first", "(", "s", ",", "delims", ")", ":", "min_idx", "=", "None", "min_delim", "=", "None", "for", "d", "in", "delims", ":", "idx", "=", "s", ".", "find", "(", "d", ")", "if", "idx", "<", "0", ":", "continue", "if", "min_idx", "is", "None", "or", "idx", "<", "min_idx", ":", "min_idx", "=", "idx", "min_delim", "=", "d", "if", "min_idx", "is", "None", "or", "min_idx", "<", "0", ":", "return", "s", ",", "''", ",", "None", "return", "s", "[", ":", "min_idx", "]", ",", "s", "[", "min_idx", "+", "1", ":", "]", ",", "min_delim" ]
Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims.
[ "Given", "a", "string", "and", "an", "iterable", "of", "delimiters", "split", "on", "the", "first", "found", "delimiter", ".", "Return", "two", "split", "parts", "and", "the", "matched", "delimiter", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L99-L129
25,670
pypa/pipenv
pipenv/vendor/urllib3/util/url.py
Url.request_uri
def request_uri(self): """Absolute path including the query string.""" uri = self.path or '/' if self.query is not None: uri += '?' + self.query return uri
python
def request_uri(self): """Absolute path including the query string.""" uri = self.path or '/' if self.query is not None: uri += '?' + self.query return uri
[ "def", "request_uri", "(", "self", ")", ":", "uri", "=", "self", ".", "path", "or", "'/'", "if", "self", ".", "query", "is", "not", "None", ":", "uri", "+=", "'?'", "+", "self", ".", "query", "return", "uri" ]
Absolute path including the query string.
[ "Absolute", "path", "including", "the", "query", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L39-L46
25,671
pypa/pipenv
pipenv/vendor/urllib3/util/url.py
Url.netloc
def netloc(self): """Network location including host and port""" if self.port: return '%s:%d' % (self.host, self.port) return self.host
python
def netloc(self): """Network location including host and port""" if self.port: return '%s:%d' % (self.host, self.port) return self.host
[ "def", "netloc", "(", "self", ")", ":", "if", "self", ".", "port", ":", "return", "'%s:%d'", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", "return", "self", ".", "host" ]
Network location including host and port
[ "Network", "location", "including", "host", "and", "port" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L49-L53
25,672
pypa/pipenv
pipenv/vendor/urllib3/util/url.py
Url.url
def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = '' # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + '://' if auth is not None: url += auth + '@' if host is not None: url += host if port is not None: url += ':' + str(port) if path is not None: url += path if query is not None: url += '?' + query if fragment is not None: url += '#' + fragment return url
python
def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = '' # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + '://' if auth is not None: url += auth + '@' if host is not None: url += host if port is not None: url += ':' + str(port) if path is not None: url += path if query is not None: url += '?' + query if fragment is not None: url += '#' + fragment return url
[ "def", "url", "(", "self", ")", ":", "scheme", ",", "auth", ",", "host", ",", "port", ",", "path", ",", "query", ",", "fragment", "=", "self", "url", "=", "''", "# We use \"is not None\" we want things to happen with empty strings (or 0 port)", "if", "scheme", "is", "not", "None", ":", "url", "+=", "scheme", "+", "'://'", "if", "auth", "is", "not", "None", ":", "url", "+=", "auth", "+", "'@'", "if", "host", "is", "not", "None", ":", "url", "+=", "host", "if", "port", "is", "not", "None", ":", "url", "+=", "':'", "+", "str", "(", "port", ")", "if", "path", "is", "not", "None", ":", "url", "+=", "path", "if", "query", "is", "not", "None", ":", "url", "+=", "'?'", "+", "query", "if", "fragment", "is", "not", "None", ":", "url", "+=", "'#'", "+", "fragment", "return", "url" ]
Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment'
[ "Convert", "self", "into", "a", "url" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/url.py#L56-L93
25,673
pypa/pipenv
pipenv/patched/notpip/_vendor/html5lib/treeadapters/genshi.py
to_genshi
def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes """ text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "EmptyTag"): if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) for attr, value in token["data"].items()]) yield (START, (QName(name), attrs), (None, -1, -1)) if type == "EmptyTag": type = "EndTag" if type == "EndTag": if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] yield END, QName(name), (None, -1, -1) elif type == "Comment": yield COMMENT, token["data"], (None, -1, -1) elif type == "Doctype": yield DOCTYPE, (token["name"], token["publicId"], token["systemId"]), (None, -1, -1) else: pass # FIXME: What to do? if text: yield TEXT, "".join(text), (None, -1, -1)
python
def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes """ text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "EmptyTag"): if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) for attr, value in token["data"].items()]) yield (START, (QName(name), attrs), (None, -1, -1)) if type == "EmptyTag": type = "EndTag" if type == "EndTag": if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] yield END, QName(name), (None, -1, -1) elif type == "Comment": yield COMMENT, token["data"], (None, -1, -1) elif type == "Doctype": yield DOCTYPE, (token["name"], token["publicId"], token["systemId"]), (None, -1, -1) else: pass # FIXME: What to do? if text: yield TEXT, "".join(text), (None, -1, -1)
[ "def", "to_genshi", "(", "walker", ")", ":", "text", "=", "[", "]", "for", "token", "in", "walker", ":", "type", "=", "token", "[", "\"type\"", "]", "if", "type", "in", "(", "\"Characters\"", ",", "\"SpaceCharacters\"", ")", ":", "text", ".", "append", "(", "token", "[", "\"data\"", "]", ")", "elif", "text", ":", "yield", "TEXT", ",", "\"\"", ".", "join", "(", "text", ")", ",", "(", "None", ",", "-", "1", ",", "-", "1", ")", "text", "=", "[", "]", "if", "type", "in", "(", "\"StartTag\"", ",", "\"EmptyTag\"", ")", ":", "if", "token", "[", "\"namespace\"", "]", ":", "name", "=", "\"{%s}%s\"", "%", "(", "token", "[", "\"namespace\"", "]", ",", "token", "[", "\"name\"", "]", ")", "else", ":", "name", "=", "token", "[", "\"name\"", "]", "attrs", "=", "Attrs", "(", "[", "(", "QName", "(", "\"{%s}%s\"", "%", "attr", "if", "attr", "[", "0", "]", "is", "not", "None", "else", "attr", "[", "1", "]", ")", ",", "value", ")", "for", "attr", ",", "value", "in", "token", "[", "\"data\"", "]", ".", "items", "(", ")", "]", ")", "yield", "(", "START", ",", "(", "QName", "(", "name", ")", ",", "attrs", ")", ",", "(", "None", ",", "-", "1", ",", "-", "1", ")", ")", "if", "type", "==", "\"EmptyTag\"", ":", "type", "=", "\"EndTag\"", "if", "type", "==", "\"EndTag\"", ":", "if", "token", "[", "\"namespace\"", "]", ":", "name", "=", "\"{%s}%s\"", "%", "(", "token", "[", "\"namespace\"", "]", ",", "token", "[", "\"name\"", "]", ")", "else", ":", "name", "=", "token", "[", "\"name\"", "]", "yield", "END", ",", "QName", "(", "name", ")", ",", "(", "None", ",", "-", "1", ",", "-", "1", ")", "elif", "type", "==", "\"Comment\"", ":", "yield", "COMMENT", ",", "token", "[", "\"data\"", "]", ",", "(", "None", ",", "-", "1", ",", "-", "1", ")", "elif", "type", "==", "\"Doctype\"", ":", "yield", "DOCTYPE", ",", "(", "token", "[", "\"name\"", "]", ",", "token", "[", "\"publicId\"", "]", ",", "token", "[", "\"systemId\"", "]", ")", ",", "(", "None", ",", "-", "1", ",", "-", "1", ")", "else", ":", "pass", "# FIXME: What to do?", "if", "text", ":", "yield", "TEXT", ",", "\"\"", ".", "join", "(", "text", ")", ",", "(", "None", ",", "-", "1", ",", "-", "1", ")" ]
Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes
[ "Convert", "a", "tree", "to", "a", "genshi", "tree" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treeadapters/genshi.py#L7-L54
25,674
pypa/pipenv
pipenv/vendor/pipreqs/pipreqs.py
parse_requirements
def parse_requirements(file_): """Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments. """ modules = [] delim = ["<", ">", "=", "!", "~"] # https://www.python.org/dev/peps/pep-0508/#complete-grammar try: f = open_func(file_, "r") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: data = [x.strip() for x in f.readlines() if x != "\n"] finally: f.close() data = [x for x in data if x[0].isalpha()] for x in data: if not any([y in x for y in delim]): # Check for modules w/o a specifier. modules.append({"name": x, "version": None}) for y in x: if y in delim: module = x.split(y) module_name = module[0] module_version = module[-1].replace("=", "") module = {"name": module_name, "version": module_version} if module not in modules: modules.append(module) break return modules
python
def parse_requirements(file_): """Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments. """ modules = [] delim = ["<", ">", "=", "!", "~"] # https://www.python.org/dev/peps/pep-0508/#complete-grammar try: f = open_func(file_, "r") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: data = [x.strip() for x in f.readlines() if x != "\n"] finally: f.close() data = [x for x in data if x[0].isalpha()] for x in data: if not any([y in x for y in delim]): # Check for modules w/o a specifier. modules.append({"name": x, "version": None}) for y in x: if y in delim: module = x.split(y) module_name = module[0] module_version = module[-1].replace("=", "") module = {"name": module_name, "version": module_version} if module not in modules: modules.append(module) break return modules
[ "def", "parse_requirements", "(", "file_", ")", ":", "modules", "=", "[", "]", "delim", "=", "[", "\"<\"", ",", "\">\"", ",", "\"=\"", ",", "\"!\"", ",", "\"~\"", "]", "# https://www.python.org/dev/peps/pep-0508/#complete-grammar", "try", ":", "f", "=", "open_func", "(", "file_", ",", "\"r\"", ")", "except", "OSError", ":", "logging", ".", "error", "(", "\"Failed on file: {}\"", ".", "format", "(", "file_", ")", ")", "raise", "else", ":", "data", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "f", ".", "readlines", "(", ")", "if", "x", "!=", "\"\\n\"", "]", "finally", ":", "f", ".", "close", "(", ")", "data", "=", "[", "x", "for", "x", "in", "data", "if", "x", "[", "0", "]", ".", "isalpha", "(", ")", "]", "for", "x", "in", "data", ":", "if", "not", "any", "(", "[", "y", "in", "x", "for", "y", "in", "delim", "]", ")", ":", "# Check for modules w/o a specifier.", "modules", ".", "append", "(", "{", "\"name\"", ":", "x", ",", "\"version\"", ":", "None", "}", ")", "for", "y", "in", "x", ":", "if", "y", "in", "delim", ":", "module", "=", "x", ".", "split", "(", "y", ")", "module_name", "=", "module", "[", "0", "]", "module_version", "=", "module", "[", "-", "1", "]", ".", "replace", "(", "\"=\"", ",", "\"\"", ")", "module", "=", "{", "\"name\"", ":", "module_name", ",", "\"version\"", ":", "module_version", "}", "if", "module", "not", "in", "modules", ":", "modules", ".", "append", "(", "module", ")", "break", "return", "modules" ]
Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments.
[ "Parse", "a", "requirements", "formatted", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L231-L277
25,675
pypa/pipenv
pipenv/vendor/pipreqs/pipreqs.py
compare_modules
def compare_modules(file_, imports): """Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file. """ modules = parse_requirements(file_) imports = [imports[i]["name"] for i in range(len(imports))] modules = [modules[i]["name"] for i in range(len(modules))] modules_not_imported = set(modules) - set(imports) return modules_not_imported
python
def compare_modules(file_, imports): """Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file. """ modules = parse_requirements(file_) imports = [imports[i]["name"] for i in range(len(imports))] modules = [modules[i]["name"] for i in range(len(modules))] modules_not_imported = set(modules) - set(imports) return modules_not_imported
[ "def", "compare_modules", "(", "file_", ",", "imports", ")", ":", "modules", "=", "parse_requirements", "(", "file_", ")", "imports", "=", "[", "imports", "[", "i", "]", "[", "\"name\"", "]", "for", "i", "in", "range", "(", "len", "(", "imports", ")", ")", "]", "modules", "=", "[", "modules", "[", "i", "]", "[", "\"name\"", "]", "for", "i", "in", "range", "(", "len", "(", "modules", ")", ")", "]", "modules_not_imported", "=", "set", "(", "modules", ")", "-", "set", "(", "imports", ")", "return", "modules_not_imported" ]
Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file.
[ "Compare", "modules", "in", "a", "file", "to", "imported", "modules", "in", "a", "project", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L280-L297
25,676
pypa/pipenv
pipenv/vendor/pipreqs/pipreqs.py
diff
def diff(file_, imports): """Display the difference between modules in a file and imported modules.""" modules_not_imported = compare_modules(file_, imports) logging.info("The following modules are in {} but do not seem to be imported: " "{}".format(file_, ", ".join(x for x in modules_not_imported)))
python
def diff(file_, imports): """Display the difference between modules in a file and imported modules.""" modules_not_imported = compare_modules(file_, imports) logging.info("The following modules are in {} but do not seem to be imported: " "{}".format(file_, ", ".join(x for x in modules_not_imported)))
[ "def", "diff", "(", "file_", ",", "imports", ")", ":", "modules_not_imported", "=", "compare_modules", "(", "file_", ",", "imports", ")", "logging", ".", "info", "(", "\"The following modules are in {} but do not seem to be imported: \"", "\"{}\"", ".", "format", "(", "file_", ",", "\", \"", ".", "join", "(", "x", "for", "x", "in", "modules_not_imported", ")", ")", ")" ]
Display the difference between modules in a file and imported modules.
[ "Display", "the", "difference", "between", "modules", "in", "a", "file", "and", "imported", "modules", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L300-L305
25,677
pypa/pipenv
pipenv/vendor/pipreqs/pipreqs.py
clean
def clean(file_, imports): """Remove modules that aren't imported in project from file.""" modules_not_imported = compare_modules(file_, imports) re_remove = re.compile("|".join(modules_not_imported)) to_write = [] try: f = open_func(file_, "r+") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: for i in f.readlines(): if re_remove.match(i) is None: to_write.append(i) f.seek(0) f.truncate() for i in to_write: f.write(i) finally: f.close() logging.info("Successfully cleaned up requirements in " + file_)
python
def clean(file_, imports): """Remove modules that aren't imported in project from file.""" modules_not_imported = compare_modules(file_, imports) re_remove = re.compile("|".join(modules_not_imported)) to_write = [] try: f = open_func(file_, "r+") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: for i in f.readlines(): if re_remove.match(i) is None: to_write.append(i) f.seek(0) f.truncate() for i in to_write: f.write(i) finally: f.close() logging.info("Successfully cleaned up requirements in " + file_)
[ "def", "clean", "(", "file_", ",", "imports", ")", ":", "modules_not_imported", "=", "compare_modules", "(", "file_", ",", "imports", ")", "re_remove", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "modules_not_imported", ")", ")", "to_write", "=", "[", "]", "try", ":", "f", "=", "open_func", "(", "file_", ",", "\"r+\"", ")", "except", "OSError", ":", "logging", ".", "error", "(", "\"Failed on file: {}\"", ".", "format", "(", "file_", ")", ")", "raise", "else", ":", "for", "i", "in", "f", ".", "readlines", "(", ")", ":", "if", "re_remove", ".", "match", "(", "i", ")", "is", "None", ":", "to_write", ".", "append", "(", "i", ")", "f", ".", "seek", "(", "0", ")", "f", ".", "truncate", "(", ")", "for", "i", "in", "to_write", ":", "f", ".", "write", "(", "i", ")", "finally", ":", "f", ".", "close", "(", ")", "logging", ".", "info", "(", "\"Successfully cleaned up requirements in \"", "+", "file_", ")" ]
Remove modules that aren't imported in project from file.
[ "Remove", "modules", "that", "aren", "t", "imported", "in", "project", "from", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L307-L330
25,678
pypa/pipenv
pipenv/patched/notpip/_internal/utils/deprecation.py
deprecated
def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire message out. message = "DEPRECATION: " + reason if replacement is not None: message += " A possible replacement is {}.".format(replacement) if issue is not None: url = "https://github.com/pypa/pip/issues/" + str(issue) message += " You can find discussion regarding this at {}.".format(url) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
python
def deprecated(reason, replacement, gone_in, issue=None): # type: (str, Optional[str], Optional[str], Optional[int]) -> None """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site. """ # Construct a nice message. # This is purposely eagerly formatted as we want it to appear as if someone # typed this entire message out. message = "DEPRECATION: " + reason if replacement is not None: message += " A possible replacement is {}.".format(replacement) if issue is not None: url = "https://github.com/pypa/pip/issues/" + str(issue) message += " You can find discussion regarding this at {}.".format(url) # Raise as an error if it has to be removed. if gone_in is not None and parse(current_version) >= parse(gone_in): raise PipDeprecationWarning(message) warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)
[ "def", "deprecated", "(", "reason", ",", "replacement", ",", "gone_in", ",", "issue", "=", "None", ")", ":", "# type: (str, Optional[str], Optional[str], Optional[int]) -> None", "# Construct a nice message.", "# This is purposely eagerly formatted as we want it to appear as if someone", "# typed this entire message out.", "message", "=", "\"DEPRECATION: \"", "+", "reason", "if", "replacement", "is", "not", "None", ":", "message", "+=", "\" A possible replacement is {}.\"", ".", "format", "(", "replacement", ")", "if", "issue", "is", "not", "None", ":", "url", "=", "\"https://github.com/pypa/pip/issues/\"", "+", "str", "(", "issue", ")", "message", "+=", "\" You can find discussion regarding this at {}.\"", ".", "format", "(", "url", ")", "# Raise as an error if it has to be removed.", "if", "gone_in", "is", "not", "None", "and", "parse", "(", "current_version", ")", ">=", "parse", "(", "gone_in", ")", ":", "raise", "PipDeprecationWarning", "(", "message", ")", "warnings", ".", "warn", "(", "message", ",", "category", "=", "PipDeprecationWarning", ",", "stacklevel", "=", "2", ")" ]
Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has been deprecated. replacement: Textual suggestion shown to the user about what alternative functionality they can use. gone_in: The version of pip does this functionality should get removed in. Raises errors if pip's current version is greater than or equal to this. issue: Issue number on the tracker that would serve as a useful place for users to find related discussion and provide feedback. Always pass replacement, gone_in and issue as keyword arguments for clarity at the call site.
[ "Helper", "to", "deprecate", "existing", "functionality", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/deprecation.py#L55-L90
25,679
pypa/pipenv
pipenv/vendor/passa/models/metadata.py
set_metadata
def set_metadata(candidates, traces, dependencies, pythons): """Add "metadata" to candidates based on the dependency tree. Metadata for a candidate includes markers and a specifier for Python version requirements. :param candidates: A key-candidate mapping. Candidates in the mapping will have their markers set. :param traces: A graph trace (produced by `traces.trace_graph`) providing information about dependency relationships between candidates. :param dependencies: A key-collection mapping containing what dependencies each candidate in `candidates` requested. :param pythons: A key-str mapping containing Requires-Python information of each candidate. Keys in mappings and entries in the trace are identifiers of a package, as implemented by the `identify` method of the resolver's provider. The candidates are modified in-place. """ metasets_mapping = _calculate_metasets_mapping( dependencies, pythons, copy.deepcopy(traces), ) for key, candidate in candidates.items(): candidate.markers = _format_metasets(metasets_mapping[key])
python
def set_metadata(candidates, traces, dependencies, pythons): """Add "metadata" to candidates based on the dependency tree. Metadata for a candidate includes markers and a specifier for Python version requirements. :param candidates: A key-candidate mapping. Candidates in the mapping will have their markers set. :param traces: A graph trace (produced by `traces.trace_graph`) providing information about dependency relationships between candidates. :param dependencies: A key-collection mapping containing what dependencies each candidate in `candidates` requested. :param pythons: A key-str mapping containing Requires-Python information of each candidate. Keys in mappings and entries in the trace are identifiers of a package, as implemented by the `identify` method of the resolver's provider. The candidates are modified in-place. """ metasets_mapping = _calculate_metasets_mapping( dependencies, pythons, copy.deepcopy(traces), ) for key, candidate in candidates.items(): candidate.markers = _format_metasets(metasets_mapping[key])
[ "def", "set_metadata", "(", "candidates", ",", "traces", ",", "dependencies", ",", "pythons", ")", ":", "metasets_mapping", "=", "_calculate_metasets_mapping", "(", "dependencies", ",", "pythons", ",", "copy", ".", "deepcopy", "(", "traces", ")", ",", ")", "for", "key", ",", "candidate", "in", "candidates", ".", "items", "(", ")", ":", "candidate", ".", "markers", "=", "_format_metasets", "(", "metasets_mapping", "[", "key", "]", ")" ]
Add "metadata" to candidates based on the dependency tree. Metadata for a candidate includes markers and a specifier for Python version requirements. :param candidates: A key-candidate mapping. Candidates in the mapping will have their markers set. :param traces: A graph trace (produced by `traces.trace_graph`) providing information about dependency relationships between candidates. :param dependencies: A key-collection mapping containing what dependencies each candidate in `candidates` requested. :param pythons: A key-str mapping containing Requires-Python information of each candidate. Keys in mappings and entries in the trace are identifiers of a package, as implemented by the `identify` method of the resolver's provider. The candidates are modified in-place.
[ "Add", "metadata", "to", "candidates", "based", "on", "the", "dependency", "tree", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/metadata.py#L145-L169
25,680
pypa/pipenv
pipenv/vendor/click/decorators.py
pass_context
def pass_context(f): """Marks a callback as wanting to receive the current context object as first argument. """ def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
python
def pass_context(f): """Marks a callback as wanting to receive the current context object as first argument. """ def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
[ "def", "pass_context", "(", "f", ")", ":", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "get_current_context", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "update_wrapper", "(", "new_func", ",", "f", ")" ]
Marks a callback as wanting to receive the current context object as first argument.
[ "Marks", "a", "callback", "as", "wanting", "to", "receive", "the", "current", "context", "object", "as", "first", "argument", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L12-L18
25,681
pypa/pipenv
pipenv/vendor/click/decorators.py
password_option
def password_option(*param_decls, **attrs): """Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): pass """ def decorator(f): attrs.setdefault('prompt', True) attrs.setdefault('confirmation_prompt', True) attrs.setdefault('hide_input', True) return option(*(param_decls or ('--password',)), **attrs)(f) return decorator
python
def password_option(*param_decls, **attrs): """Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): pass """ def decorator(f): attrs.setdefault('prompt', True) attrs.setdefault('confirmation_prompt', True) attrs.setdefault('hide_input', True) return option(*(param_decls or ('--password',)), **attrs)(f) return decorator
[ "def", "password_option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "def", "decorator", "(", "f", ")", ":", "attrs", ".", "setdefault", "(", "'prompt'", ",", "True", ")", "attrs", ".", "setdefault", "(", "'confirmation_prompt'", ",", "True", ")", "attrs", ".", "setdefault", "(", "'hide_input'", ",", "True", ")", "return", "option", "(", "*", "(", "param_decls", "or", "(", "'--password'", ",", ")", ")", ",", "*", "*", "attrs", ")", "(", "f", ")", "return", "decorator" ]
Shortcut for password prompts. This is equivalent to decorating a function with :func:`option` with the following parameters:: @click.command() @click.option('--password', prompt=True, confirmation_prompt=True, hide_input=True) def changeadmin(password): pass
[ "Shortcut", "for", "password", "prompts", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L208-L225
25,682
pypa/pipenv
pipenv/patched/notpip/_internal/utils/outdated.py
was_installed_by_pip
def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ try: dist = pkg_resources.get_distribution(pkg) return (dist.has_metadata('INSTALLER') and 'pip' in dist.get_metadata_lines('INSTALLER')) except pkg_resources.DistributionNotFound: return False
python
def was_installed_by_pip(pkg): # type: (str) -> bool """Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ try: dist = pkg_resources.get_distribution(pkg) return (dist.has_metadata('INSTALLER') and 'pip' in dist.get_metadata_lines('INSTALLER')) except pkg_resources.DistributionNotFound: return False
[ "def", "was_installed_by_pip", "(", "pkg", ")", ":", "# type: (str) -> bool", "try", ":", "dist", "=", "pkg_resources", ".", "get_distribution", "(", "pkg", ")", "return", "(", "dist", ".", "has_metadata", "(", "'INSTALLER'", ")", "and", "'pip'", "in", "dist", ".", "get_metadata_lines", "(", "'INSTALLER'", ")", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "return", "False" ]
Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora.
[ "Checks", "whether", "pkg", "was", "installed", "by", "pip" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/outdated.py#L79-L91
25,683
pypa/pipenv
pipenv/patched/notpip/_internal/utils/outdated.py
pip_version_check
def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is finder = PackageFinder( find_links=options.find_links, index_urls=[options.index_url] + options.extra_index_urls, allow_all_prereleases=False, # Explicitly set to False trusted_hosts=options.trusted_hosts, session=session, ) all_candidates = finder.find_all_candidates("pip") if not all_candidates: return pypi_version = str( max(all_candidates, key=lambda c: c.version).version ) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip')): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
python
def pip_version_check(session, options): # type: (PipSession, optparse.Values) -> None """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if not installed_version: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = SelfCheckState(cache_dir=options.cache_dir) current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if (current_time - last_check).total_seconds() < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: # Lets use PackageFinder to see what the latest pip version is finder = PackageFinder( find_links=options.find_links, index_urls=[options.index_url] + options.extra_index_urls, allow_all_prereleases=False, # Explicitly set to False trusted_hosts=options.trusted_hosts, session=session, ) all_candidates = finder.find_all_candidates("pip") if not all_candidates: return pypi_version = str( max(all_candidates, key=lambda c: c.version).version ) # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version and was_installed_by_pip('pip')): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, )
[ "def", "pip_version_check", "(", "session", ",", "options", ")", ":", "# type: (PipSession, optparse.Values) -> None", "installed_version", "=", "get_installed_version", "(", "\"pip\"", ")", "if", "not", "installed_version", ":", "return", "pip_version", "=", "packaging_version", ".", "parse", "(", "installed_version", ")", "pypi_version", "=", "None", "try", ":", "state", "=", "SelfCheckState", "(", "cache_dir", "=", "options", ".", "cache_dir", ")", "current_time", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "# Determine if we need to refresh the state", "if", "\"last_check\"", "in", "state", ".", "state", "and", "\"pypi_version\"", "in", "state", ".", "state", ":", "last_check", "=", "datetime", ".", "datetime", ".", "strptime", "(", "state", ".", "state", "[", "\"last_check\"", "]", ",", "SELFCHECK_DATE_FMT", ")", "if", "(", "current_time", "-", "last_check", ")", ".", "total_seconds", "(", ")", "<", "7", "*", "24", "*", "60", "*", "60", ":", "pypi_version", "=", "state", ".", "state", "[", "\"pypi_version\"", "]", "# Refresh the version if we need to or just see if we need to warn", "if", "pypi_version", "is", "None", ":", "# Lets use PackageFinder to see what the latest pip version is", "finder", "=", "PackageFinder", "(", "find_links", "=", "options", ".", "find_links", ",", "index_urls", "=", "[", "options", ".", "index_url", "]", "+", "options", ".", "extra_index_urls", ",", "allow_all_prereleases", "=", "False", ",", "# Explicitly set to False", "trusted_hosts", "=", "options", ".", "trusted_hosts", ",", "session", "=", "session", ",", ")", "all_candidates", "=", "finder", ".", "find_all_candidates", "(", "\"pip\"", ")", "if", "not", "all_candidates", ":", "return", "pypi_version", "=", "str", "(", "max", "(", "all_candidates", ",", "key", "=", "lambda", "c", ":", "c", ".", "version", ")", ".", "version", ")", "# save that we've performed a check", "state", ".", "save", "(", "pypi_version", ",", "current_time", ")", "remote_version", "=", "packaging_version", ".", "parse", "(", "pypi_version", ")", "# Determine if our pypi_version is older", "if", "(", "pip_version", "<", "remote_version", "and", "pip_version", ".", "base_version", "!=", "remote_version", ".", "base_version", "and", "was_installed_by_pip", "(", "'pip'", ")", ")", ":", "# Advise \"python -m pip\" on Windows to avoid issues", "# with overwriting pip.exe.", "if", "WINDOWS", ":", "pip_cmd", "=", "\"python -m pip\"", "else", ":", "pip_cmd", "=", "\"pip\"", "logger", ".", "warning", "(", "\"You are using pip version %s, however version %s is \"", "\"available.\\nYou should consider upgrading via the \"", "\"'%s install --upgrade pip' command.\"", ",", "pip_version", ",", "pypi_version", ",", "pip_cmd", ")", "except", "Exception", ":", "logger", ".", "debug", "(", "\"There was an error checking the latest version of pip\"", ",", "exc_info", "=", "True", ",", ")" ]
Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path.
[ "Check", "for", "an", "update", "for", "pip", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/outdated.py#L94-L164
25,684
pypa/pipenv
pipenv/patched/notpip/_internal/pep425tags.py
get_impl_version_info
def get_impl_version_info(): # type: () -> Tuple[int, ...] """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 # attrs exist only on pypy return (sys.version_info[0], sys.pypy_version_info.major, # type: ignore sys.pypy_version_info.minor) # type: ignore else: return sys.version_info[0], sys.version_info[1]
python
def get_impl_version_info(): # type: () -> Tuple[int, ...] """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 # attrs exist only on pypy return (sys.version_info[0], sys.pypy_version_info.major, # type: ignore sys.pypy_version_info.minor) # type: ignore else: return sys.version_info[0], sys.version_info[1]
[ "def", "get_impl_version_info", "(", ")", ":", "# type: () -> Tuple[int, ...]", "if", "get_abbr_impl", "(", ")", "==", "'pp'", ":", "# as per https://github.com/pypa/pip/issues/2882", "# attrs exist only on pypy", "return", "(", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "pypy_version_info", ".", "major", ",", "# type: ignore", "sys", ".", "pypy_version_info", ".", "minor", ")", "# type: ignore", "else", ":", "return", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]" ]
Return sys.version_info-like tuple for use in decrementing the minor version.
[ "Return", "sys", ".", "version_info", "-", "like", "tuple", "for", "use", "in", "decrementing", "the", "minor", "version", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/pep425tags.py#L64-L75
25,685
pypa/pipenv
pipenv/vendor/requests/utils.py
extract_zipped_paths
def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) member = '/'.join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, *member.split('/')) if not os.path.exists(extracted_path): extracted_path = zip_file.extract(member, path=tmp) return extracted_path
python
def extract_zipped_paths(path): """Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged. """ if os.path.exists(path): # this is already a valid path, no need to do anything further return path # find the first valid part of the provided path and treat that as a zip archive # assume the rest of the path is the name of a member in the archive archive, member = os.path.split(path) while archive and not os.path.exists(archive): archive, prefix = os.path.split(archive) member = '/'.join([prefix, member]) if not zipfile.is_zipfile(archive): return path zip_file = zipfile.ZipFile(archive) if member not in zip_file.namelist(): return path # we have a valid zip archive and a valid member of that archive tmp = tempfile.gettempdir() extracted_path = os.path.join(tmp, *member.split('/')) if not os.path.exists(extracted_path): extracted_path = zip_file.extract(member, path=tmp) return extracted_path
[ "def", "extract_zipped_paths", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "# this is already a valid path, no need to do anything further", "return", "path", "# find the first valid part of the provided path and treat that as a zip archive", "# assume the rest of the path is the name of a member in the archive", "archive", ",", "member", "=", "os", ".", "path", ".", "split", "(", "path", ")", "while", "archive", "and", "not", "os", ".", "path", ".", "exists", "(", "archive", ")", ":", "archive", ",", "prefix", "=", "os", ".", "path", ".", "split", "(", "archive", ")", "member", "=", "'/'", ".", "join", "(", "[", "prefix", ",", "member", "]", ")", "if", "not", "zipfile", ".", "is_zipfile", "(", "archive", ")", ":", "return", "path", "zip_file", "=", "zipfile", ".", "ZipFile", "(", "archive", ")", "if", "member", "not", "in", "zip_file", ".", "namelist", "(", ")", ":", "return", "path", "# we have a valid zip archive and a valid member of that archive", "tmp", "=", "tempfile", ".", "gettempdir", "(", ")", "extracted_path", "=", "os", ".", "path", ".", "join", "(", "tmp", ",", "*", "member", ".", "split", "(", "'/'", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "extracted_path", ")", ":", "extracted_path", "=", "zip_file", ".", "extract", "(", "member", ",", "path", "=", "tmp", ")", "return", "extracted_path" ]
Replace nonexistent paths that look like they refer to a member of a zip archive with the location of an extracted copy of the target, or else just return the provided path unchanged.
[ "Replace", "nonexistent", "paths", "that", "look", "like", "they", "refer", "to", "a", "member", "of", "a", "zip", "archive", "with", "the", "location", "of", "an", "extracted", "copy", "of", "the", "target", "or", "else", "just", "return", "the", "provided", "path", "unchanged", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L227-L256
25,686
pypa/pipenv
pipenv/vendor/requests/utils.py
_parse_content_type_header
def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1:].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict
python
def _parse_content_type_header(header): """Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters """ tokens = header.split(';') content_type, params = tokens[0].strip(), tokens[1:] params_dict = {} items_to_strip = "\"' " for param in params: param = param.strip() if param: key, value = param, True index_of_equals = param.find("=") if index_of_equals != -1: key = param[:index_of_equals].strip(items_to_strip) value = param[index_of_equals + 1:].strip(items_to_strip) params_dict[key.lower()] = value return content_type, params_dict
[ "def", "_parse_content_type_header", "(", "header", ")", ":", "tokens", "=", "header", ".", "split", "(", "';'", ")", "content_type", ",", "params", "=", "tokens", "[", "0", "]", ".", "strip", "(", ")", ",", "tokens", "[", "1", ":", "]", "params_dict", "=", "{", "}", "items_to_strip", "=", "\"\\\"' \"", "for", "param", "in", "params", ":", "param", "=", "param", ".", "strip", "(", ")", "if", "param", ":", "key", ",", "value", "=", "param", ",", "True", "index_of_equals", "=", "param", ".", "find", "(", "\"=\"", ")", "if", "index_of_equals", "!=", "-", "1", ":", "key", "=", "param", "[", ":", "index_of_equals", "]", ".", "strip", "(", "items_to_strip", ")", "value", "=", "param", "[", "index_of_equals", "+", "1", ":", "]", ".", "strip", "(", "items_to_strip", ")", "params_dict", "[", "key", ".", "lower", "(", ")", "]", "=", "value", "return", "content_type", ",", "params_dict" ]
Returns content type and parameters from given header :param header: string :return: tuple containing content type and dictionary of parameters
[ "Returns", "content", "type", "and", "parameters", "from", "given", "header" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L450-L472
25,687
pypa/pipenv
pipenv/vendor/requests/utils.py
iter_slices
def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
python
def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 if slice_length is None or slice_length <= 0: slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length
[ "def", "iter_slices", "(", "string", ",", "slice_length", ")", ":", "pos", "=", "0", "if", "slice_length", "is", "None", "or", "slice_length", "<=", "0", ":", "slice_length", "=", "len", "(", "string", ")", "while", "pos", "<", "len", "(", "string", ")", ":", "yield", "string", "[", "pos", ":", "pos", "+", "slice_length", "]", "pos", "+=", "slice_length" ]
Iterate over slices of a string.
[ "Iterate", "over", "slices", "of", "a", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L514-L521
25,688
pypa/pipenv
pipenv/vendor/requests/utils.py
get_unicode_from_response
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content
python
def get_unicode_from_response(r): """Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' 'more information, please see the discussion on issue #2266. (This' ' warning should only appear once.)'), DeprecationWarning) tried_encodings = [] # Try charset from content-type encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) # Fall back: try: return str(r.content, encoding, errors='replace') except TypeError: return r.content
[ "def", "get_unicode_from_response", "(", "r", ")", ":", "warnings", ".", "warn", "(", "(", "'In requests 3.0, get_unicode_from_response will be removed. For '", "'more information, please see the discussion on issue #2266. (This'", "' warning should only appear once.)'", ")", ",", "DeprecationWarning", ")", "tried_encodings", "=", "[", "]", "# Try charset from content-type", "encoding", "=", "get_encoding_from_headers", "(", "r", ".", "headers", ")", "if", "encoding", ":", "try", ":", "return", "str", "(", "r", ".", "content", ",", "encoding", ")", "except", "UnicodeError", ":", "tried_encodings", ".", "append", "(", "encoding", ")", "# Fall back:", "try", ":", "return", "str", "(", "r", ".", "content", ",", "encoding", ",", "errors", "=", "'replace'", ")", "except", "TypeError", ":", "return", "r", ".", "content" ]
Returns the requested content back in unicode. :param r: Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters :rtype: str
[ "Returns", "the", "requested", "content", "back", "in", "unicode", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L524-L557
25,689
pypa/pipenv
pipenv/vendor/requests/utils.py
requote_uri
def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent)
python
def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except InvalidURL: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent)
[ "def", "requote_uri", "(", "uri", ")", ":", "safe_with_percent", "=", "\"!#$%&'()*+,/:;=?@[]~\"", "safe_without_percent", "=", "\"!#$&'()*+,/:;=?@[]~\"", "try", ":", "# Unquote only the unreserved characters", "# Then quote only illegal characters (do not quote reserved,", "# unreserved, or '%')", "return", "quote", "(", "unquote_unreserved", "(", "uri", ")", ",", "safe", "=", "safe_with_percent", ")", "except", "InvalidURL", ":", "# We couldn't unquote the given URI, so let's try quoting it, but", "# there may be unquoted '%'s in the URI. We need to make sure they're", "# properly quoted so they do not cause issues elsewhere.", "return", "quote", "(", "uri", ",", "safe", "=", "safe_without_percent", ")" ]
Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str
[ "Re", "-", "quote", "the", "given", "URI", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L589-L608
25,690
pypa/pipenv
pipenv/vendor/requests/utils.py
address_in_network
def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask)
python
def address_in_network(ip, net): """This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool """ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0] network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask return (ipaddr & netmask) == (network & netmask)
[ "def", "address_in_network", "(", "ip", ",", "net", ")", ":", "ipaddr", "=", "struct", ".", "unpack", "(", "'=L'", ",", "socket", ".", "inet_aton", "(", "ip", ")", ")", "[", "0", "]", "netaddr", ",", "bits", "=", "net", ".", "split", "(", "'/'", ")", "netmask", "=", "struct", ".", "unpack", "(", "'=L'", ",", "socket", ".", "inet_aton", "(", "dotted_netmask", "(", "int", "(", "bits", ")", ")", ")", ")", "[", "0", "]", "network", "=", "struct", ".", "unpack", "(", "'=L'", ",", "socket", ".", "inet_aton", "(", "netaddr", ")", ")", "[", "0", "]", "&", "netmask", "return", "(", "ipaddr", "&", "netmask", ")", "==", "(", "network", "&", "netmask", ")" ]
This function allows you to check if an IP belongs to a network subnet Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 :rtype: bool
[ "This", "function", "allows", "you", "to", "check", "if", "an", "IP", "belongs", "to", "a", "network", "subnet" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L611-L623
25,691
pypa/pipenv
pipenv/vendor/requests/utils.py
is_valid_cidr
def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split('/')[0]) except socket.error: return False else: return False return True
python
def is_valid_cidr(string_network): """ Very simple check of the cidr format in no_proxy variable. :rtype: bool """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) except ValueError: return False if mask < 1 or mask > 32: return False try: socket.inet_aton(string_network.split('/')[0]) except socket.error: return False else: return False return True
[ "def", "is_valid_cidr", "(", "string_network", ")", ":", "if", "string_network", ".", "count", "(", "'/'", ")", "==", "1", ":", "try", ":", "mask", "=", "int", "(", "string_network", ".", "split", "(", "'/'", ")", "[", "1", "]", ")", "except", "ValueError", ":", "return", "False", "if", "mask", "<", "1", "or", "mask", ">", "32", ":", "return", "False", "try", ":", "socket", ".", "inet_aton", "(", "string_network", ".", "split", "(", "'/'", ")", "[", "0", "]", ")", "except", "socket", ".", "error", ":", "return", "False", "else", ":", "return", "False", "return", "True" ]
Very simple check of the cidr format in no_proxy variable. :rtype: bool
[ "Very", "simple", "check", "of", "the", "cidr", "format", "in", "no_proxy", "variable", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L648-L669
25,692
pypa/pipenv
pipenv/vendor/requests/utils.py
set_environ
def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value
python
def set_environ(env_name, value): """Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing""" value_changed = value is not None if value_changed: old_value = os.environ.get(env_name) os.environ[env_name] = value try: yield finally: if value_changed: if old_value is None: del os.environ[env_name] else: os.environ[env_name] = old_value
[ "def", "set_environ", "(", "env_name", ",", "value", ")", ":", "value_changed", "=", "value", "is", "not", "None", "if", "value_changed", ":", "old_value", "=", "os", ".", "environ", ".", "get", "(", "env_name", ")", "os", ".", "environ", "[", "env_name", "]", "=", "value", "try", ":", "yield", "finally", ":", "if", "value_changed", ":", "if", "old_value", "is", "None", ":", "del", "os", ".", "environ", "[", "env_name", "]", "else", ":", "os", ".", "environ", "[", "env_name", "]", "=", "old_value" ]
Set the environment variable 'env_name' to 'value' Save previous value, yield, and then restore the previous value stored in the environment variable 'env_name'. If 'value' is None, do nothing
[ "Set", "the", "environment", "variable", "env_name", "to", "value" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L673-L691
25,693
pypa/pipenv
pipenv/vendor/requests/utils.py
select_proxy
def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get('all')) proxy_keys = [ urlparts.scheme + '://' + urlparts.hostname, urlparts.scheme, 'all://' + urlparts.hostname, 'all', ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy
python
def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: return proxies.get(urlparts.scheme, proxies.get('all')) proxy_keys = [ urlparts.scheme + '://' + urlparts.hostname, urlparts.scheme, 'all://' + urlparts.hostname, 'all', ] proxy = None for proxy_key in proxy_keys: if proxy_key in proxies: proxy = proxies[proxy_key] break return proxy
[ "def", "select_proxy", "(", "url", ",", "proxies", ")", ":", "proxies", "=", "proxies", "or", "{", "}", "urlparts", "=", "urlparse", "(", "url", ")", "if", "urlparts", ".", "hostname", "is", "None", ":", "return", "proxies", ".", "get", "(", "urlparts", ".", "scheme", ",", "proxies", ".", "get", "(", "'all'", ")", ")", "proxy_keys", "=", "[", "urlparts", ".", "scheme", "+", "'://'", "+", "urlparts", ".", "hostname", ",", "urlparts", ".", "scheme", ",", "'all://'", "+", "urlparts", ".", "hostname", ",", "'all'", ",", "]", "proxy", "=", "None", "for", "proxy_key", "in", "proxy_keys", ":", "if", "proxy_key", "in", "proxies", ":", "proxy", "=", "proxies", "[", "proxy_key", "]", "break", "return", "proxy" ]
Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
[ "Select", "a", "proxy", "for", "the", "url", "if", "applicable", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L767-L790
25,694
pypa/pipenv
pipenv/vendor/requests/utils.py
prepend_scheme_if_needed
def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a # netloc present. Assume that it's being over-cautious, and switch netloc # and path if urlparse decided there was no netloc. if not netloc: netloc, path = path, netloc return urlunparse((scheme, netloc, path, params, query, fragment))
python
def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a # netloc present. Assume that it's being over-cautious, and switch netloc # and path if urlparse decided there was no netloc. if not netloc: netloc, path = path, netloc return urlunparse((scheme, netloc, path, params, query, fragment))
[ "def", "prepend_scheme_if_needed", "(", "url", ",", "new_scheme", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ",", "new_scheme", ")", "# urlparse is a finicky beast, and sometimes decides that there isn't a", "# netloc present. Assume that it's being over-cautious, and switch netloc", "# and path if urlparse decided there was no netloc.", "if", "not", "netloc", ":", "netloc", ",", "path", "=", "path", ",", "netloc", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", ")", ")" ]
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str
[ "Given", "a", "URL", "that", "may", "or", "may", "not", "have", "a", "scheme", "prepend", "the", "given", "scheme", ".", "Does", "not", "replace", "a", "present", "scheme", "with", "the", "one", "provided", "as", "an", "argument", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L889-L903
25,695
pypa/pipenv
pipenv/vendor/requests/utils.py
get_auth_from_url
def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth
python
def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str) """ parsed = urlparse(url) try: auth = (unquote(parsed.username), unquote(parsed.password)) except (AttributeError, TypeError): auth = ('', '') return auth
[ "def", "get_auth_from_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ")", "try", ":", "auth", "=", "(", "unquote", "(", "parsed", ".", "username", ")", ",", "unquote", "(", "parsed", ".", "password", ")", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "auth", "=", "(", "''", ",", "''", ")", "return", "auth" ]
Given a url with authentication components, extract them into a tuple of username,password. :rtype: (str,str)
[ "Given", "a", "url", "with", "authentication", "components", "extract", "them", "into", "a", "tuple", "of", "username", "password", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L906-L919
25,696
pypa/pipenv
pipenv/vendor/requests/utils.py
check_header_validity
def check_header_validity(header): """Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). """ name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader("Invalid return character or leading space in header: %s" % name) except TypeError: raise InvalidHeader("Value for header {%s: %s} must be of type str or " "bytes, not %s" % (name, value, type(value)))
python
def check_header_validity(header): """Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). """ name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader("Invalid return character or leading space in header: %s" % name) except TypeError: raise InvalidHeader("Value for header {%s: %s} must be of type str or " "bytes, not %s" % (name, value, type(value)))
[ "def", "check_header_validity", "(", "header", ")", ":", "name", ",", "value", "=", "header", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "pat", "=", "_CLEAN_HEADER_REGEX_BYTE", "else", ":", "pat", "=", "_CLEAN_HEADER_REGEX_STR", "try", ":", "if", "not", "pat", ".", "match", "(", "value", ")", ":", "raise", "InvalidHeader", "(", "\"Invalid return character or leading space in header: %s\"", "%", "name", ")", "except", "TypeError", ":", "raise", "InvalidHeader", "(", "\"Value for header {%s: %s} must be of type str or \"", "\"bytes, not %s\"", "%", "(", "name", ",", "value", ",", "type", "(", "value", ")", ")", ")" ]
Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value).
[ "Verifies", "that", "header", "value", "is", "a", "string", "which", "doesn", "t", "contain", "leading", "whitespace", "or", "return", "characters", ".", "This", "prevents", "unintended", "header", "injection", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L927-L945
25,697
pypa/pipenv
pipenv/vendor/requests/utils.py
urldefragauth
def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, path, params, query, ''))
python
def urldefragauth(url): """ Given a url remove the fragment and the authentication part. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) # see func:`prepend_scheme_if_needed` if not netloc: netloc, path = path, netloc netloc = netloc.rsplit('@', 1)[-1] return urlunparse((scheme, netloc, path, params, query, ''))
[ "def", "urldefragauth", "(", "url", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ")", "# see func:`prepend_scheme_if_needed`", "if", "not", "netloc", ":", "netloc", ",", "path", "=", "path", ",", "netloc", "netloc", "=", "netloc", ".", "rsplit", "(", "'@'", ",", "1", ")", "[", "-", "1", "]", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "''", ")", ")" ]
Given a url remove the fragment and the authentication part. :rtype: str
[ "Given", "a", "url", "remove", "the", "fragment", "and", "the", "authentication", "part", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L948-L962
25,698
pypa/pipenv
pipenv/vendor/requests/utils.py
rewind_body
def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, 'seek', None) if body_seek is not None and isinstance(prepared_request._body_position, integer_types): try: body_seek(prepared_request._body_position) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect.") else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
python
def rewind_body(prepared_request): """Move file pointer back to its recorded starting position so it can be read again on redirect. """ body_seek = getattr(prepared_request.body, 'seek', None) if body_seek is not None and isinstance(prepared_request._body_position, integer_types): try: body_seek(prepared_request._body_position) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect.") else: raise UnrewindableBodyError("Unable to rewind request body for redirect.")
[ "def", "rewind_body", "(", "prepared_request", ")", ":", "body_seek", "=", "getattr", "(", "prepared_request", ".", "body", ",", "'seek'", ",", "None", ")", "if", "body_seek", "is", "not", "None", "and", "isinstance", "(", "prepared_request", ".", "_body_position", ",", "integer_types", ")", ":", "try", ":", "body_seek", "(", "prepared_request", ".", "_body_position", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "raise", "UnrewindableBodyError", "(", "\"An error occurred when rewinding request \"", "\"body for redirect.\"", ")", "else", ":", "raise", "UnrewindableBodyError", "(", "\"Unable to rewind request body for redirect.\"", ")" ]
Move file pointer back to its recorded starting position so it can be read again on redirect.
[ "Move", "file", "pointer", "back", "to", "its", "recorded", "starting", "position", "so", "it", "can", "be", "read", "again", "on", "redirect", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L965-L977
25,699
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
has_safe_repr
def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in (bool, int, float, complex, range_type, Markup) + string_types: return True if type(value) in (tuple, list, set, frozenset): for item in value: if not has_safe_repr(item): return False return True elif type(value) is dict: for key, value in iteritems(value): if not has_safe_repr(key): return False if not has_safe_repr(value): return False return True return False
python
def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if type(value) in (bool, int, float, complex, range_type, Markup) + string_types: return True if type(value) in (tuple, list, set, frozenset): for item in value: if not has_safe_repr(item): return False return True elif type(value) is dict: for key, value in iteritems(value): if not has_safe_repr(key): return False if not has_safe_repr(value): return False return True return False
[ "def", "has_safe_repr", "(", "value", ")", ":", "if", "value", "is", "None", "or", "value", "is", "NotImplemented", "or", "value", "is", "Ellipsis", ":", "return", "True", "if", "type", "(", "value", ")", "in", "(", "bool", ",", "int", ",", "float", ",", "complex", ",", "range_type", ",", "Markup", ")", "+", "string_types", ":", "return", "True", "if", "type", "(", "value", ")", "in", "(", "tuple", ",", "list", ",", "set", ",", "frozenset", ")", ":", "for", "item", "in", "value", ":", "if", "not", "has_safe_repr", "(", "item", ")", ":", "return", "False", "return", "True", "elif", "type", "(", "value", ")", "is", "dict", ":", "for", "key", ",", "value", "in", "iteritems", "(", "value", ")", ":", "if", "not", "has_safe_repr", "(", "key", ")", ":", "return", "False", "if", "not", "has_safe_repr", "(", "value", ")", ":", "return", "False", "return", "True", "return", "False" ]
Does the node have a safe representation?
[ "Does", "the", "node", "have", "a", "safe", "representation?" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L87-L105