repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/cerberus/errors.py
|
BasicErrorHandler._insert_error
|
def _insert_error(self, path, node):
""" Adds an error or sub-tree to :attr:tree.
:param path: Path to the error.
:type path: Tuple of strings and integers.
:param node: An error message or a sub-tree.
:type node: String or dictionary.
"""
field = path[0]
if len(path) == 1:
if field in self.tree:
subtree = self.tree[field].pop()
self.tree[field] += [node, subtree]
else:
self.tree[field] = [node, {}]
elif len(path) >= 1:
if field not in self.tree:
self.tree[field] = [{}]
subtree = self.tree[field][-1]
if subtree:
new = self.__class__(tree=copy(subtree))
else:
new = self.__class__()
new._insert_error(path[1:], node)
subtree.update(new.tree)
|
python
|
def _insert_error(self, path, node):
""" Adds an error or sub-tree to :attr:tree.
:param path: Path to the error.
:type path: Tuple of strings and integers.
:param node: An error message or a sub-tree.
:type node: String or dictionary.
"""
field = path[0]
if len(path) == 1:
if field in self.tree:
subtree = self.tree[field].pop()
self.tree[field] += [node, subtree]
else:
self.tree[field] = [node, {}]
elif len(path) >= 1:
if field not in self.tree:
self.tree[field] = [{}]
subtree = self.tree[field][-1]
if subtree:
new = self.__class__(tree=copy(subtree))
else:
new = self.__class__()
new._insert_error(path[1:], node)
subtree.update(new.tree)
|
[
"def",
"_insert_error",
"(",
"self",
",",
"path",
",",
"node",
")",
":",
"field",
"=",
"path",
"[",
"0",
"]",
"if",
"len",
"(",
"path",
")",
"==",
"1",
":",
"if",
"field",
"in",
"self",
".",
"tree",
":",
"subtree",
"=",
"self",
".",
"tree",
"[",
"field",
"]",
".",
"pop",
"(",
")",
"self",
".",
"tree",
"[",
"field",
"]",
"+=",
"[",
"node",
",",
"subtree",
"]",
"else",
":",
"self",
".",
"tree",
"[",
"field",
"]",
"=",
"[",
"node",
",",
"{",
"}",
"]",
"elif",
"len",
"(",
"path",
")",
">=",
"1",
":",
"if",
"field",
"not",
"in",
"self",
".",
"tree",
":",
"self",
".",
"tree",
"[",
"field",
"]",
"=",
"[",
"{",
"}",
"]",
"subtree",
"=",
"self",
".",
"tree",
"[",
"field",
"]",
"[",
"-",
"1",
"]",
"if",
"subtree",
":",
"new",
"=",
"self",
".",
"__class__",
"(",
"tree",
"=",
"copy",
"(",
"subtree",
")",
")",
"else",
":",
"new",
"=",
"self",
".",
"__class__",
"(",
")",
"new",
".",
"_insert_error",
"(",
"path",
"[",
"1",
":",
"]",
",",
"node",
")",
"subtree",
".",
"update",
"(",
"new",
".",
"tree",
")"
] |
Adds an error or sub-tree to :attr:tree.
:param path: Path to the error.
:type path: Tuple of strings and integers.
:param node: An error message or a sub-tree.
:type node: String or dictionary.
|
[
"Adds",
"an",
"error",
"or",
"sub",
"-",
"tree",
"to",
":",
"attr",
":",
"tree",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/errors.py#L528-L553
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/requests/hooks.py
|
dispatch_hook
|
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data
|
python
|
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data
|
[
"def",
"dispatch_hook",
"(",
"key",
",",
"hooks",
",",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
":",
"hooks",
"=",
"hooks",
"or",
"{",
"}",
"hooks",
"=",
"hooks",
".",
"get",
"(",
"key",
")",
"if",
"hooks",
":",
"if",
"hasattr",
"(",
"hooks",
",",
"'__call__'",
")",
":",
"hooks",
"=",
"[",
"hooks",
"]",
"for",
"hook",
"in",
"hooks",
":",
"_hook_data",
"=",
"hook",
"(",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
"if",
"_hook_data",
"is",
"not",
"None",
":",
"hook_data",
"=",
"_hook_data",
"return",
"hook_data"
] |
Dispatches a hook dictionary on a given piece of data.
|
[
"Dispatches",
"a",
"hook",
"dictionary",
"on",
"a",
"given",
"piece",
"of",
"data",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/hooks.py#L23-L34
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/dotenv/cli.py
|
list
|
def list(ctx):
'''Display all the stored key/value.'''
file = ctx.obj['FILE']
dotenv_as_dict = dotenv_values(file)
for k, v in dotenv_as_dict.items():
click.echo('%s=%s' % (k, v))
|
python
|
def list(ctx):
'''Display all the stored key/value.'''
file = ctx.obj['FILE']
dotenv_as_dict = dotenv_values(file)
for k, v in dotenv_as_dict.items():
click.echo('%s=%s' % (k, v))
|
[
"def",
"list",
"(",
"ctx",
")",
":",
"file",
"=",
"ctx",
".",
"obj",
"[",
"'FILE'",
"]",
"dotenv_as_dict",
"=",
"dotenv_values",
"(",
"file",
")",
"for",
"k",
",",
"v",
"in",
"dotenv_as_dict",
".",
"items",
"(",
")",
":",
"click",
".",
"echo",
"(",
"'%s=%s'",
"%",
"(",
"k",
",",
"v",
")",
")"
] |
Display all the stored key/value.
|
[
"Display",
"all",
"the",
"stored",
"key",
"/",
"value",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L33-L38
|
train
|
pypa/pipenv
|
pipenv/vendor/dotenv/cli.py
|
set
|
def set(ctx, key, value):
'''Store the given key/value.'''
file = ctx.obj['FILE']
quote = ctx.obj['QUOTE']
success, key, value = set_key(file, key, value, quote)
if success:
click.echo('%s=%s' % (key, value))
else:
exit(1)
|
python
|
def set(ctx, key, value):
'''Store the given key/value.'''
file = ctx.obj['FILE']
quote = ctx.obj['QUOTE']
success, key, value = set_key(file, key, value, quote)
if success:
click.echo('%s=%s' % (key, value))
else:
exit(1)
|
[
"def",
"set",
"(",
"ctx",
",",
"key",
",",
"value",
")",
":",
"file",
"=",
"ctx",
".",
"obj",
"[",
"'FILE'",
"]",
"quote",
"=",
"ctx",
".",
"obj",
"[",
"'QUOTE'",
"]",
"success",
",",
"key",
",",
"value",
"=",
"set_key",
"(",
"file",
",",
"key",
",",
"value",
",",
"quote",
")",
"if",
"success",
":",
"click",
".",
"echo",
"(",
"'%s=%s'",
"%",
"(",
"key",
",",
"value",
")",
")",
"else",
":",
"exit",
"(",
"1",
")"
] |
Store the given key/value.
|
[
"Store",
"the",
"given",
"key",
"/",
"value",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L45-L53
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/passa/models/synchronizers.py
|
_build_paths
|
def _build_paths():
"""Prepare paths for distlib.wheel.Wheel to install into.
"""
paths = sysconfig.get_paths()
return {
"prefix": sys.prefix,
"data": paths["data"],
"scripts": paths["scripts"],
"headers": paths["include"],
"purelib": paths["purelib"],
"platlib": paths["platlib"],
}
|
python
|
def _build_paths():
"""Prepare paths for distlib.wheel.Wheel to install into.
"""
paths = sysconfig.get_paths()
return {
"prefix": sys.prefix,
"data": paths["data"],
"scripts": paths["scripts"],
"headers": paths["include"],
"purelib": paths["purelib"],
"platlib": paths["platlib"],
}
|
[
"def",
"_build_paths",
"(",
")",
":",
"paths",
"=",
"sysconfig",
".",
"get_paths",
"(",
")",
"return",
"{",
"\"prefix\"",
":",
"sys",
".",
"prefix",
",",
"\"data\"",
":",
"paths",
"[",
"\"data\"",
"]",
",",
"\"scripts\"",
":",
"paths",
"[",
"\"scripts\"",
"]",
",",
"\"headers\"",
":",
"paths",
"[",
"\"include\"",
"]",
",",
"\"purelib\"",
":",
"paths",
"[",
"\"purelib\"",
"]",
",",
"\"platlib\"",
":",
"paths",
"[",
"\"platlib\"",
"]",
",",
"}"
] |
Prepare paths for distlib.wheel.Wheel to install into.
|
[
"Prepare",
"paths",
"for",
"distlib",
".",
"wheel",
".",
"Wheel",
"to",
"install",
"into",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/models/synchronizers.py#L98-L109
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/manifest.py
|
Manifest._parse_directive
|
def _parse_directive(self, directive):
"""
Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns
"""
words = directive.split()
if len(words) == 1 and words[0] not in ('include', 'exclude',
'global-include',
'global-exclude',
'recursive-include',
'recursive-exclude',
'graft', 'prune'):
# no action given, let's use the default 'include'
words.insert(0, 'include')
action = words[0]
patterns = thedir = dir_pattern = None
if action in ('include', 'exclude',
'global-include', 'global-exclude'):
if len(words) < 2:
raise DistlibException(
'%r expects <pattern1> <pattern2> ...' % action)
patterns = [convert_path(word) for word in words[1:]]
elif action in ('recursive-include', 'recursive-exclude'):
if len(words) < 3:
raise DistlibException(
'%r expects <dir> <pattern1> <pattern2> ...' % action)
thedir = convert_path(words[1])
patterns = [convert_path(word) for word in words[2:]]
elif action in ('graft', 'prune'):
if len(words) != 2:
raise DistlibException(
'%r expects a single <dir_pattern>' % action)
dir_pattern = convert_path(words[1])
else:
raise DistlibException('unknown action %r' % action)
return action, patterns, thedir, dir_pattern
|
python
|
def _parse_directive(self, directive):
"""
Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns
"""
words = directive.split()
if len(words) == 1 and words[0] not in ('include', 'exclude',
'global-include',
'global-exclude',
'recursive-include',
'recursive-exclude',
'graft', 'prune'):
# no action given, let's use the default 'include'
words.insert(0, 'include')
action = words[0]
patterns = thedir = dir_pattern = None
if action in ('include', 'exclude',
'global-include', 'global-exclude'):
if len(words) < 2:
raise DistlibException(
'%r expects <pattern1> <pattern2> ...' % action)
patterns = [convert_path(word) for word in words[1:]]
elif action in ('recursive-include', 'recursive-exclude'):
if len(words) < 3:
raise DistlibException(
'%r expects <dir> <pattern1> <pattern2> ...' % action)
thedir = convert_path(words[1])
patterns = [convert_path(word) for word in words[2:]]
elif action in ('graft', 'prune'):
if len(words) != 2:
raise DistlibException(
'%r expects a single <dir_pattern>' % action)
dir_pattern = convert_path(words[1])
else:
raise DistlibException('unknown action %r' % action)
return action, patterns, thedir, dir_pattern
|
[
"def",
"_parse_directive",
"(",
"self",
",",
"directive",
")",
":",
"words",
"=",
"directive",
".",
"split",
"(",
")",
"if",
"len",
"(",
"words",
")",
"==",
"1",
"and",
"words",
"[",
"0",
"]",
"not",
"in",
"(",
"'include'",
",",
"'exclude'",
",",
"'global-include'",
",",
"'global-exclude'",
",",
"'recursive-include'",
",",
"'recursive-exclude'",
",",
"'graft'",
",",
"'prune'",
")",
":",
"# no action given, let's use the default 'include'",
"words",
".",
"insert",
"(",
"0",
",",
"'include'",
")",
"action",
"=",
"words",
"[",
"0",
"]",
"patterns",
"=",
"thedir",
"=",
"dir_pattern",
"=",
"None",
"if",
"action",
"in",
"(",
"'include'",
",",
"'exclude'",
",",
"'global-include'",
",",
"'global-exclude'",
")",
":",
"if",
"len",
"(",
"words",
")",
"<",
"2",
":",
"raise",
"DistlibException",
"(",
"'%r expects <pattern1> <pattern2> ...'",
"%",
"action",
")",
"patterns",
"=",
"[",
"convert_path",
"(",
"word",
")",
"for",
"word",
"in",
"words",
"[",
"1",
":",
"]",
"]",
"elif",
"action",
"in",
"(",
"'recursive-include'",
",",
"'recursive-exclude'",
")",
":",
"if",
"len",
"(",
"words",
")",
"<",
"3",
":",
"raise",
"DistlibException",
"(",
"'%r expects <dir> <pattern1> <pattern2> ...'",
"%",
"action",
")",
"thedir",
"=",
"convert_path",
"(",
"words",
"[",
"1",
"]",
")",
"patterns",
"=",
"[",
"convert_path",
"(",
"word",
")",
"for",
"word",
"in",
"words",
"[",
"2",
":",
"]",
"]",
"elif",
"action",
"in",
"(",
"'graft'",
",",
"'prune'",
")",
":",
"if",
"len",
"(",
"words",
")",
"!=",
"2",
":",
"raise",
"DistlibException",
"(",
"'%r expects a single <dir_pattern>'",
"%",
"action",
")",
"dir_pattern",
"=",
"convert_path",
"(",
"words",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"DistlibException",
"(",
"'unknown action %r'",
"%",
"action",
")",
"return",
"action",
",",
"patterns",
",",
"thedir",
",",
"dir_pattern"
] |
Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns
|
[
"Validate",
"a",
"directive",
".",
":",
"param",
"directive",
":",
"The",
"directive",
"to",
"validate",
".",
":",
"return",
":",
"A",
"tuple",
"of",
"action",
"patterns",
"thedir",
"dir_patterns"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L209-L254
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/manifest.py
|
Manifest._include_pattern
|
def _include_pattern(self, pattern, anchor=True, prefix=None,
is_regex=False):
"""Select strings (presumably filenames) from 'self.files' that
match 'pattern', a Unix-style wildcard (glob) pattern.
Patterns are not quite the same as implemented by the 'fnmatch'
module: '*' and '?' match non-special characters, where "special"
is platform-dependent: slash on Unix; colon, slash, and backslash on
DOS/Windows; and colon on Mac OS.
If 'anchor' is true (the default), then the pattern match is more
stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
'anchor' is false, both of these will match.
If 'prefix' is supplied, then only filenames starting with 'prefix'
(itself a pattern) and ending with 'pattern', with anything in between
them, will match. 'anchor' is ignored in this case.
If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
'pattern' is assumed to be either a string containing a regex or a
regex object -- no translation is done, the regex is just compiled
and used as-is.
Selected strings will be added to self.files.
Return True if files are found.
"""
# XXX docstring lying about what the special chars are?
found = False
pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
# delayed loading of allfiles list
if self.allfiles is None:
self.findall()
for name in self.allfiles:
if pattern_re.search(name):
self.files.add(name)
found = True
return found
|
python
|
def _include_pattern(self, pattern, anchor=True, prefix=None,
is_regex=False):
"""Select strings (presumably filenames) from 'self.files' that
match 'pattern', a Unix-style wildcard (glob) pattern.
Patterns are not quite the same as implemented by the 'fnmatch'
module: '*' and '?' match non-special characters, where "special"
is platform-dependent: slash on Unix; colon, slash, and backslash on
DOS/Windows; and colon on Mac OS.
If 'anchor' is true (the default), then the pattern match is more
stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
'anchor' is false, both of these will match.
If 'prefix' is supplied, then only filenames starting with 'prefix'
(itself a pattern) and ending with 'pattern', with anything in between
them, will match. 'anchor' is ignored in this case.
If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
'pattern' is assumed to be either a string containing a regex or a
regex object -- no translation is done, the regex is just compiled
and used as-is.
Selected strings will be added to self.files.
Return True if files are found.
"""
# XXX docstring lying about what the special chars are?
found = False
pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
# delayed loading of allfiles list
if self.allfiles is None:
self.findall()
for name in self.allfiles:
if pattern_re.search(name):
self.files.add(name)
found = True
return found
|
[
"def",
"_include_pattern",
"(",
"self",
",",
"pattern",
",",
"anchor",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"is_regex",
"=",
"False",
")",
":",
"# XXX docstring lying about what the special chars are?",
"found",
"=",
"False",
"pattern_re",
"=",
"self",
".",
"_translate_pattern",
"(",
"pattern",
",",
"anchor",
",",
"prefix",
",",
"is_regex",
")",
"# delayed loading of allfiles list",
"if",
"self",
".",
"allfiles",
"is",
"None",
":",
"self",
".",
"findall",
"(",
")",
"for",
"name",
"in",
"self",
".",
"allfiles",
":",
"if",
"pattern_re",
".",
"search",
"(",
"name",
")",
":",
"self",
".",
"files",
".",
"add",
"(",
"name",
")",
"found",
"=",
"True",
"return",
"found"
] |
Select strings (presumably filenames) from 'self.files' that
match 'pattern', a Unix-style wildcard (glob) pattern.
Patterns are not quite the same as implemented by the 'fnmatch'
module: '*' and '?' match non-special characters, where "special"
is platform-dependent: slash on Unix; colon, slash, and backslash on
DOS/Windows; and colon on Mac OS.
If 'anchor' is true (the default), then the pattern match is more
stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
'anchor' is false, both of these will match.
If 'prefix' is supplied, then only filenames starting with 'prefix'
(itself a pattern) and ending with 'pattern', with anything in between
them, will match. 'anchor' is ignored in this case.
If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
'pattern' is assumed to be either a string containing a regex or a
regex object -- no translation is done, the regex is just compiled
and used as-is.
Selected strings will be added to self.files.
Return True if files are found.
|
[
"Select",
"strings",
"(",
"presumably",
"filenames",
")",
"from",
"self",
".",
"files",
"that",
"match",
"pattern",
"a",
"Unix",
"-",
"style",
"wildcard",
"(",
"glob",
")",
"pattern",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L256-L295
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/manifest.py
|
Manifest._exclude_pattern
|
def _exclude_pattern(self, pattern, anchor=True, prefix=None,
is_regex=False):
"""Remove strings (presumably filenames) from 'files' that match
'pattern'.
Other parameters are the same as for 'include_pattern()', above.
The list 'self.files' is modified in place. Return True if files are
found.
This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
packaging source distributions
"""
found = False
pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
for f in list(self.files):
if pattern_re.search(f):
self.files.remove(f)
found = True
return found
|
python
|
def _exclude_pattern(self, pattern, anchor=True, prefix=None,
is_regex=False):
"""Remove strings (presumably filenames) from 'files' that match
'pattern'.
Other parameters are the same as for 'include_pattern()', above.
The list 'self.files' is modified in place. Return True if files are
found.
This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
packaging source distributions
"""
found = False
pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
for f in list(self.files):
if pattern_re.search(f):
self.files.remove(f)
found = True
return found
|
[
"def",
"_exclude_pattern",
"(",
"self",
",",
"pattern",
",",
"anchor",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"is_regex",
"=",
"False",
")",
":",
"found",
"=",
"False",
"pattern_re",
"=",
"self",
".",
"_translate_pattern",
"(",
"pattern",
",",
"anchor",
",",
"prefix",
",",
"is_regex",
")",
"for",
"f",
"in",
"list",
"(",
"self",
".",
"files",
")",
":",
"if",
"pattern_re",
".",
"search",
"(",
"f",
")",
":",
"self",
".",
"files",
".",
"remove",
"(",
"f",
")",
"found",
"=",
"True",
"return",
"found"
] |
Remove strings (presumably filenames) from 'files' that match
'pattern'.
Other parameters are the same as for 'include_pattern()', above.
The list 'self.files' is modified in place. Return True if files are
found.
This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
packaging source distributions
|
[
"Remove",
"strings",
"(",
"presumably",
"filenames",
")",
"from",
"files",
"that",
"match",
"pattern",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L297-L315
|
train
|
pypa/pipenv
|
pipenv/vendor/distlib/manifest.py
|
Manifest._translate_pattern
|
def _translate_pattern(self, pattern, anchor=True, prefix=None,
is_regex=False):
"""Translate a shell-like wildcard pattern to a compiled regular
expression.
Return the compiled regex. If 'is_regex' true,
then 'pattern' is directly compiled to a regex (if it's a string)
or just returned as-is (assumes it's a regex object).
"""
if is_regex:
if isinstance(pattern, str):
return re.compile(pattern)
else:
return pattern
if _PYTHON_VERSION > (3, 2):
# ditch start and end characters
start, _, end = self._glob_to_re('_').partition('_')
if pattern:
pattern_re = self._glob_to_re(pattern)
if _PYTHON_VERSION > (3, 2):
assert pattern_re.startswith(start) and pattern_re.endswith(end)
else:
pattern_re = ''
base = re.escape(os.path.join(self.base, ''))
if prefix is not None:
# ditch end of pattern character
if _PYTHON_VERSION <= (3, 2):
empty_pattern = self._glob_to_re('')
prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)]
else:
prefix_re = self._glob_to_re(prefix)
assert prefix_re.startswith(start) and prefix_re.endswith(end)
prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
sep = os.sep
if os.sep == '\\':
sep = r'\\'
if _PYTHON_VERSION <= (3, 2):
pattern_re = '^' + base + sep.join((prefix_re,
'.*' + pattern_re))
else:
pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep,
pattern_re, end)
else: # no prefix -- respect anchor flag
if anchor:
if _PYTHON_VERSION <= (3, 2):
pattern_re = '^' + base + pattern_re
else:
pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):])
return re.compile(pattern_re)
|
python
|
def _translate_pattern(self, pattern, anchor=True, prefix=None,
is_regex=False):
"""Translate a shell-like wildcard pattern to a compiled regular
expression.
Return the compiled regex. If 'is_regex' true,
then 'pattern' is directly compiled to a regex (if it's a string)
or just returned as-is (assumes it's a regex object).
"""
if is_regex:
if isinstance(pattern, str):
return re.compile(pattern)
else:
return pattern
if _PYTHON_VERSION > (3, 2):
# ditch start and end characters
start, _, end = self._glob_to_re('_').partition('_')
if pattern:
pattern_re = self._glob_to_re(pattern)
if _PYTHON_VERSION > (3, 2):
assert pattern_re.startswith(start) and pattern_re.endswith(end)
else:
pattern_re = ''
base = re.escape(os.path.join(self.base, ''))
if prefix is not None:
# ditch end of pattern character
if _PYTHON_VERSION <= (3, 2):
empty_pattern = self._glob_to_re('')
prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)]
else:
prefix_re = self._glob_to_re(prefix)
assert prefix_re.startswith(start) and prefix_re.endswith(end)
prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
sep = os.sep
if os.sep == '\\':
sep = r'\\'
if _PYTHON_VERSION <= (3, 2):
pattern_re = '^' + base + sep.join((prefix_re,
'.*' + pattern_re))
else:
pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep,
pattern_re, end)
else: # no prefix -- respect anchor flag
if anchor:
if _PYTHON_VERSION <= (3, 2):
pattern_re = '^' + base + pattern_re
else:
pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):])
return re.compile(pattern_re)
|
[
"def",
"_translate_pattern",
"(",
"self",
",",
"pattern",
",",
"anchor",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"is_regex",
"=",
"False",
")",
":",
"if",
"is_regex",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"str",
")",
":",
"return",
"re",
".",
"compile",
"(",
"pattern",
")",
"else",
":",
"return",
"pattern",
"if",
"_PYTHON_VERSION",
">",
"(",
"3",
",",
"2",
")",
":",
"# ditch start and end characters",
"start",
",",
"_",
",",
"end",
"=",
"self",
".",
"_glob_to_re",
"(",
"'_'",
")",
".",
"partition",
"(",
"'_'",
")",
"if",
"pattern",
":",
"pattern_re",
"=",
"self",
".",
"_glob_to_re",
"(",
"pattern",
")",
"if",
"_PYTHON_VERSION",
">",
"(",
"3",
",",
"2",
")",
":",
"assert",
"pattern_re",
".",
"startswith",
"(",
"start",
")",
"and",
"pattern_re",
".",
"endswith",
"(",
"end",
")",
"else",
":",
"pattern_re",
"=",
"''",
"base",
"=",
"re",
".",
"escape",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base",
",",
"''",
")",
")",
"if",
"prefix",
"is",
"not",
"None",
":",
"# ditch end of pattern character",
"if",
"_PYTHON_VERSION",
"<=",
"(",
"3",
",",
"2",
")",
":",
"empty_pattern",
"=",
"self",
".",
"_glob_to_re",
"(",
"''",
")",
"prefix_re",
"=",
"self",
".",
"_glob_to_re",
"(",
"prefix",
")",
"[",
":",
"-",
"len",
"(",
"empty_pattern",
")",
"]",
"else",
":",
"prefix_re",
"=",
"self",
".",
"_glob_to_re",
"(",
"prefix",
")",
"assert",
"prefix_re",
".",
"startswith",
"(",
"start",
")",
"and",
"prefix_re",
".",
"endswith",
"(",
"end",
")",
"prefix_re",
"=",
"prefix_re",
"[",
"len",
"(",
"start",
")",
":",
"len",
"(",
"prefix_re",
")",
"-",
"len",
"(",
"end",
")",
"]",
"sep",
"=",
"os",
".",
"sep",
"if",
"os",
".",
"sep",
"==",
"'\\\\'",
":",
"sep",
"=",
"r'\\\\'",
"if",
"_PYTHON_VERSION",
"<=",
"(",
"3",
",",
"2",
")",
":",
"pattern_re",
"=",
"'^'",
"+",
"base",
"+",
"sep",
".",
"join",
"(",
"(",
"prefix_re",
",",
"'.*'",
"+",
"pattern_re",
")",
")",
"else",
":",
"pattern_re",
"=",
"pattern_re",
"[",
"len",
"(",
"start",
")",
":",
"len",
"(",
"pattern_re",
")",
"-",
"len",
"(",
"end",
")",
"]",
"pattern_re",
"=",
"r'%s%s%s%s.*%s%s'",
"%",
"(",
"start",
",",
"base",
",",
"prefix_re",
",",
"sep",
",",
"pattern_re",
",",
"end",
")",
"else",
":",
"# no prefix -- respect anchor flag",
"if",
"anchor",
":",
"if",
"_PYTHON_VERSION",
"<=",
"(",
"3",
",",
"2",
")",
":",
"pattern_re",
"=",
"'^'",
"+",
"base",
"+",
"pattern_re",
"else",
":",
"pattern_re",
"=",
"r'%s%s%s'",
"%",
"(",
"start",
",",
"base",
",",
"pattern_re",
"[",
"len",
"(",
"start",
")",
":",
"]",
")",
"return",
"re",
".",
"compile",
"(",
"pattern_re",
")"
] |
Translate a shell-like wildcard pattern to a compiled regular
expression.
Return the compiled regex. If 'is_regex' true,
then 'pattern' is directly compiled to a regex (if it's a string)
or just returned as-is (assumes it's a regex object).
|
[
"Translate",
"a",
"shell",
"-",
"like",
"wildcard",
"pattern",
"to",
"a",
"compiled",
"regular",
"expression",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/manifest.py#L317-L370
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/expect.py
|
Expecter.expect_loop
|
def expect_loop(self, timeout=-1):
"""Blocking expect"""
spawn = self.spawn
if timeout is not None:
end_time = time.time() + timeout
try:
incoming = spawn.buffer
spawn._buffer = spawn.buffer_type()
spawn._before = spawn.buffer_type()
while True:
idx = self.new_data(incoming)
# Keep reading until exception or return.
if idx is not None:
return idx
# No match at this point
if (timeout is not None) and (timeout < 0):
return self.timeout()
# Still have time left, so read more data
incoming = spawn.read_nonblocking(spawn.maxread, timeout)
if self.spawn.delayafterread is not None:
time.sleep(self.spawn.delayafterread)
if timeout is not None:
timeout = end_time - time.time()
except EOF as e:
return self.eof(e)
except TIMEOUT as e:
return self.timeout(e)
except:
self.errored()
raise
|
python
|
def expect_loop(self, timeout=-1):
"""Blocking expect"""
spawn = self.spawn
if timeout is not None:
end_time = time.time() + timeout
try:
incoming = spawn.buffer
spawn._buffer = spawn.buffer_type()
spawn._before = spawn.buffer_type()
while True:
idx = self.new_data(incoming)
# Keep reading until exception or return.
if idx is not None:
return idx
# No match at this point
if (timeout is not None) and (timeout < 0):
return self.timeout()
# Still have time left, so read more data
incoming = spawn.read_nonblocking(spawn.maxread, timeout)
if self.spawn.delayafterread is not None:
time.sleep(self.spawn.delayafterread)
if timeout is not None:
timeout = end_time - time.time()
except EOF as e:
return self.eof(e)
except TIMEOUT as e:
return self.timeout(e)
except:
self.errored()
raise
|
[
"def",
"expect_loop",
"(",
"self",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"spawn",
"=",
"self",
".",
"spawn",
"if",
"timeout",
"is",
"not",
"None",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"try",
":",
"incoming",
"=",
"spawn",
".",
"buffer",
"spawn",
".",
"_buffer",
"=",
"spawn",
".",
"buffer_type",
"(",
")",
"spawn",
".",
"_before",
"=",
"spawn",
".",
"buffer_type",
"(",
")",
"while",
"True",
":",
"idx",
"=",
"self",
".",
"new_data",
"(",
"incoming",
")",
"# Keep reading until exception or return.",
"if",
"idx",
"is",
"not",
"None",
":",
"return",
"idx",
"# No match at this point",
"if",
"(",
"timeout",
"is",
"not",
"None",
")",
"and",
"(",
"timeout",
"<",
"0",
")",
":",
"return",
"self",
".",
"timeout",
"(",
")",
"# Still have time left, so read more data",
"incoming",
"=",
"spawn",
".",
"read_nonblocking",
"(",
"spawn",
".",
"maxread",
",",
"timeout",
")",
"if",
"self",
".",
"spawn",
".",
"delayafterread",
"is",
"not",
"None",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"spawn",
".",
"delayafterread",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"end_time",
"-",
"time",
".",
"time",
"(",
")",
"except",
"EOF",
"as",
"e",
":",
"return",
"self",
".",
"eof",
"(",
"e",
")",
"except",
"TIMEOUT",
"as",
"e",
":",
"return",
"self",
".",
"timeout",
"(",
"e",
")",
"except",
":",
"self",
".",
"errored",
"(",
")",
"raise"
] |
Blocking expect
|
[
"Blocking",
"expect"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/expect.py#L91-L122
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/_collections.py
|
HTTPHeaderDict.add
|
def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = [key, val]
# Keep the common case aka no item present as fast as possible
vals = self._container.setdefault(key_lower, new_vals)
if new_vals is not vals:
vals.append(val)
|
python
|
def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = [key, val]
# Keep the common case aka no item present as fast as possible
vals = self._container.setdefault(key_lower, new_vals)
if new_vals is not vals:
vals.append(val)
|
[
"def",
"add",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"key_lower",
"=",
"key",
".",
"lower",
"(",
")",
"new_vals",
"=",
"[",
"key",
",",
"val",
"]",
"# Keep the common case aka no item present as fast as possible",
"vals",
"=",
"self",
".",
"_container",
".",
"setdefault",
"(",
"key_lower",
",",
"new_vals",
")",
"if",
"new_vals",
"is",
"not",
"vals",
":",
"vals",
".",
"append",
"(",
"val",
")"
] |
Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
|
[
"Adds",
"a",
"(",
"name",
"value",
")",
"pair",
"doesn",
"t",
"overwrite",
"the",
"value",
"if",
"it",
"already",
"exists",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/_collections.py#L209-L223
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/_collections.py
|
HTTPHeaderDict.extend
|
def extend(self, *args, **kwargs):
"""Generic import function for any type of header-like object.
Adapted version of MutableMapping.update in order to insert items
with self.add instead of self.__setitem__
"""
if len(args) > 1:
raise TypeError("extend() takes at most 1 positional "
"arguments ({0} given)".format(len(args)))
other = args[0] if len(args) >= 1 else ()
if isinstance(other, HTTPHeaderDict):
for key, val in other.iteritems():
self.add(key, val)
elif isinstance(other, Mapping):
for key in other:
self.add(key, other[key])
elif hasattr(other, "keys"):
for key in other.keys():
self.add(key, other[key])
else:
for key, value in other:
self.add(key, value)
for key, value in kwargs.items():
self.add(key, value)
|
python
|
def extend(self, *args, **kwargs):
"""Generic import function for any type of header-like object.
Adapted version of MutableMapping.update in order to insert items
with self.add instead of self.__setitem__
"""
if len(args) > 1:
raise TypeError("extend() takes at most 1 positional "
"arguments ({0} given)".format(len(args)))
other = args[0] if len(args) >= 1 else ()
if isinstance(other, HTTPHeaderDict):
for key, val in other.iteritems():
self.add(key, val)
elif isinstance(other, Mapping):
for key in other:
self.add(key, other[key])
elif hasattr(other, "keys"):
for key in other.keys():
self.add(key, other[key])
else:
for key, value in other:
self.add(key, value)
for key, value in kwargs.items():
self.add(key, value)
|
[
"def",
"extend",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"extend() takes at most 1 positional \"",
"\"arguments ({0} given)\"",
".",
"format",
"(",
"len",
"(",
"args",
")",
")",
")",
"other",
"=",
"args",
"[",
"0",
"]",
"if",
"len",
"(",
"args",
")",
">=",
"1",
"else",
"(",
")",
"if",
"isinstance",
"(",
"other",
",",
"HTTPHeaderDict",
")",
":",
"for",
"key",
",",
"val",
"in",
"other",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"add",
"(",
"key",
",",
"val",
")",
"elif",
"isinstance",
"(",
"other",
",",
"Mapping",
")",
":",
"for",
"key",
"in",
"other",
":",
"self",
".",
"add",
"(",
"key",
",",
"other",
"[",
"key",
"]",
")",
"elif",
"hasattr",
"(",
"other",
",",
"\"keys\"",
")",
":",
"for",
"key",
"in",
"other",
".",
"keys",
"(",
")",
":",
"self",
".",
"add",
"(",
"key",
",",
"other",
"[",
"key",
"]",
")",
"else",
":",
"for",
"key",
",",
"value",
"in",
"other",
":",
"self",
".",
"add",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"self",
".",
"add",
"(",
"key",
",",
"value",
")"
] |
Generic import function for any type of header-like object.
Adapted version of MutableMapping.update in order to insert items
with self.add instead of self.__setitem__
|
[
"Generic",
"import",
"function",
"for",
"any",
"type",
"of",
"header",
"-",
"like",
"object",
".",
"Adapted",
"version",
"of",
"MutableMapping",
".",
"update",
"in",
"order",
"to",
"insert",
"items",
"with",
"self",
".",
"add",
"instead",
"of",
"self",
".",
"__setitem__"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/_collections.py#L225-L249
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/_collections.py
|
HTTPHeaderDict.getlist
|
def getlist(self, key, default=__marker):
"""Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist."""
try:
vals = self._container[key.lower()]
except KeyError:
if default is self.__marker:
return []
return default
else:
return vals[1:]
|
python
|
def getlist(self, key, default=__marker):
"""Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist."""
try:
vals = self._container[key.lower()]
except KeyError:
if default is self.__marker:
return []
return default
else:
return vals[1:]
|
[
"def",
"getlist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"__marker",
")",
":",
"try",
":",
"vals",
"=",
"self",
".",
"_container",
"[",
"key",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"self",
".",
"__marker",
":",
"return",
"[",
"]",
"return",
"default",
"else",
":",
"return",
"vals",
"[",
"1",
":",
"]"
] |
Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist.
|
[
"Returns",
"a",
"list",
"of",
"all",
"the",
"values",
"for",
"the",
"named",
"field",
".",
"Returns",
"an",
"empty",
"list",
"if",
"the",
"key",
"doesn",
"t",
"exist",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/_collections.py#L251-L261
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/_collections.py
|
HTTPHeaderDict.iteritems
|
def iteritems(self):
"""Iterate over all header lines, including duplicate ones."""
for key in self:
vals = self._container[key.lower()]
for val in vals[1:]:
yield vals[0], val
|
python
|
def iteritems(self):
"""Iterate over all header lines, including duplicate ones."""
for key in self:
vals = self._container[key.lower()]
for val in vals[1:]:
yield vals[0], val
|
[
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"vals",
"=",
"self",
".",
"_container",
"[",
"key",
".",
"lower",
"(",
")",
"]",
"for",
"val",
"in",
"vals",
"[",
"1",
":",
"]",
":",
"yield",
"vals",
"[",
"0",
"]",
",",
"val"
] |
Iterate over all header lines, including duplicate ones.
|
[
"Iterate",
"over",
"all",
"header",
"lines",
"including",
"duplicate",
"ones",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/_collections.py#L287-L292
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/_collections.py
|
HTTPHeaderDict.itermerged
|
def itermerged(self):
"""Iterate over all headers, merging duplicate ones together."""
for key in self:
val = self._container[key.lower()]
yield val[0], ', '.join(val[1:])
|
python
|
def itermerged(self):
"""Iterate over all headers, merging duplicate ones together."""
for key in self:
val = self._container[key.lower()]
yield val[0], ', '.join(val[1:])
|
[
"def",
"itermerged",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"val",
"=",
"self",
".",
"_container",
"[",
"key",
".",
"lower",
"(",
")",
"]",
"yield",
"val",
"[",
"0",
"]",
",",
"', '",
".",
"join",
"(",
"val",
"[",
"1",
":",
"]",
")"
] |
Iterate over all headers, merging duplicate ones together.
|
[
"Iterate",
"over",
"all",
"headers",
"merging",
"duplicate",
"ones",
"together",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/_collections.py#L294-L298
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/_collections.py
|
HTTPHeaderDict.from_httplib
|
def from_httplib(cls, message): # Python 2
"""Read headers from a Python 2 httplib message object."""
# python2.7 does not expose a proper API for exporting multiheaders
# efficiently. This function re-reads raw lines from the message
# object and extracts the multiheaders properly.
obs_fold_continued_leaders = (' ', '\t')
headers = []
for line in message.headers:
if line.startswith(obs_fold_continued_leaders):
if not headers:
# We received a header line that starts with OWS as described
# in RFC-7230 S3.2.4. This indicates a multiline header, but
# there exists no previous header to which we can attach it.
raise InvalidHeader(
'Header continuation with no previous header: %s' % line
)
else:
key, value = headers[-1]
headers[-1] = (key, value + ' ' + line.strip())
continue
key, value = line.split(':', 1)
headers.append((key, value.strip()))
return cls(headers)
|
python
|
def from_httplib(cls, message): # Python 2
"""Read headers from a Python 2 httplib message object."""
# python2.7 does not expose a proper API for exporting multiheaders
# efficiently. This function re-reads raw lines from the message
# object and extracts the multiheaders properly.
obs_fold_continued_leaders = (' ', '\t')
headers = []
for line in message.headers:
if line.startswith(obs_fold_continued_leaders):
if not headers:
# We received a header line that starts with OWS as described
# in RFC-7230 S3.2.4. This indicates a multiline header, but
# there exists no previous header to which we can attach it.
raise InvalidHeader(
'Header continuation with no previous header: %s' % line
)
else:
key, value = headers[-1]
headers[-1] = (key, value + ' ' + line.strip())
continue
key, value = line.split(':', 1)
headers.append((key, value.strip()))
return cls(headers)
|
[
"def",
"from_httplib",
"(",
"cls",
",",
"message",
")",
":",
"# Python 2",
"# python2.7 does not expose a proper API for exporting multiheaders",
"# efficiently. This function re-reads raw lines from the message",
"# object and extracts the multiheaders properly.",
"obs_fold_continued_leaders",
"=",
"(",
"' '",
",",
"'\\t'",
")",
"headers",
"=",
"[",
"]",
"for",
"line",
"in",
"message",
".",
"headers",
":",
"if",
"line",
".",
"startswith",
"(",
"obs_fold_continued_leaders",
")",
":",
"if",
"not",
"headers",
":",
"# We received a header line that starts with OWS as described",
"# in RFC-7230 S3.2.4. This indicates a multiline header, but",
"# there exists no previous header to which we can attach it.",
"raise",
"InvalidHeader",
"(",
"'Header continuation with no previous header: %s'",
"%",
"line",
")",
"else",
":",
"key",
",",
"value",
"=",
"headers",
"[",
"-",
"1",
"]",
"headers",
"[",
"-",
"1",
"]",
"=",
"(",
"key",
",",
"value",
"+",
"' '",
"+",
"line",
".",
"strip",
"(",
")",
")",
"continue",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"headers",
".",
"append",
"(",
"(",
"key",
",",
"value",
".",
"strip",
"(",
")",
")",
")",
"return",
"cls",
"(",
"headers",
")"
] |
Read headers from a Python 2 httplib message object.
|
[
"Read",
"headers",
"from",
"a",
"Python",
"2",
"httplib",
"message",
"object",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/_collections.py#L304-L329
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/requests/cookies.py
|
create_cookie
|
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = {
'version': 0,
'name': name,
'value': value,
'port': None,
'domain': '',
'path': '/',
'secure': False,
'expires': None,
'discard': True,
'comment': None,
'comment_url': None,
'rest': {'HttpOnly': None},
'rfc2109': False,
}
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result)
|
python
|
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = {
'version': 0,
'name': name,
'value': value,
'port': None,
'domain': '',
'path': '/',
'secure': False,
'expires': None,
'discard': True,
'comment': None,
'comment_url': None,
'rest': {'HttpOnly': None},
'rfc2109': False,
}
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result)
|
[
"def",
"create_cookie",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"'version'",
":",
"0",
",",
"'name'",
":",
"name",
",",
"'value'",
":",
"value",
",",
"'port'",
":",
"None",
",",
"'domain'",
":",
"''",
",",
"'path'",
":",
"'/'",
",",
"'secure'",
":",
"False",
",",
"'expires'",
":",
"None",
",",
"'discard'",
":",
"True",
",",
"'comment'",
":",
"None",
",",
"'comment_url'",
":",
"None",
",",
"'rest'",
":",
"{",
"'HttpOnly'",
":",
"None",
"}",
",",
"'rfc2109'",
":",
"False",
",",
"}",
"badargs",
"=",
"set",
"(",
"kwargs",
")",
"-",
"set",
"(",
"result",
")",
"if",
"badargs",
":",
"err",
"=",
"'create_cookie() got unexpected keyword arguments: %s'",
"raise",
"TypeError",
"(",
"err",
"%",
"list",
"(",
"badargs",
")",
")",
"result",
".",
"update",
"(",
"kwargs",
")",
"result",
"[",
"'port_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'port'",
"]",
")",
"result",
"[",
"'domain_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'domain'",
"]",
")",
"result",
"[",
"'domain_initial_dot'",
"]",
"=",
"result",
"[",
"'domain'",
"]",
".",
"startswith",
"(",
"'.'",
")",
"result",
"[",
"'path_specified'",
"]",
"=",
"bool",
"(",
"result",
"[",
"'path'",
"]",
")",
"return",
"cookielib",
".",
"Cookie",
"(",
"*",
"*",
"result",
")"
] |
Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
|
[
"Make",
"a",
"cookie",
"from",
"underspecified",
"parameters",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L441-L474
|
train
|
pypa/pipenv
|
pipenv/vendor/requests/cookies.py
|
morsel_to_cookie
|
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
|
python
|
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
|
[
"def",
"morsel_to_cookie",
"(",
"morsel",
")",
":",
"expires",
"=",
"None",
"if",
"morsel",
"[",
"'max-age'",
"]",
":",
"try",
":",
"expires",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"+",
"int",
"(",
"morsel",
"[",
"'max-age'",
"]",
")",
")",
"except",
"ValueError",
":",
"raise",
"TypeError",
"(",
"'max-age: %s must be integer'",
"%",
"morsel",
"[",
"'max-age'",
"]",
")",
"elif",
"morsel",
"[",
"'expires'",
"]",
":",
"time_template",
"=",
"'%a, %d-%b-%Y %H:%M:%S GMT'",
"expires",
"=",
"calendar",
".",
"timegm",
"(",
"time",
".",
"strptime",
"(",
"morsel",
"[",
"'expires'",
"]",
",",
"time_template",
")",
")",
"return",
"create_cookie",
"(",
"comment",
"=",
"morsel",
"[",
"'comment'",
"]",
",",
"comment_url",
"=",
"bool",
"(",
"morsel",
"[",
"'comment'",
"]",
")",
",",
"discard",
"=",
"False",
",",
"domain",
"=",
"morsel",
"[",
"'domain'",
"]",
",",
"expires",
"=",
"expires",
",",
"name",
"=",
"morsel",
".",
"key",
",",
"path",
"=",
"morsel",
"[",
"'path'",
"]",
",",
"port",
"=",
"None",
",",
"rest",
"=",
"{",
"'HttpOnly'",
":",
"morsel",
"[",
"'httponly'",
"]",
"}",
",",
"rfc2109",
"=",
"False",
",",
"secure",
"=",
"bool",
"(",
"morsel",
"[",
"'secure'",
"]",
")",
",",
"value",
"=",
"morsel",
".",
"value",
",",
"version",
"=",
"morsel",
"[",
"'version'",
"]",
"or",
"0",
",",
")"
] |
Convert a Morsel object into a Cookie containing the one k/v pair.
|
[
"Convert",
"a",
"Morsel",
"object",
"into",
"a",
"Cookie",
"containing",
"the",
"one",
"k",
"/",
"v",
"pair",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L477-L505
|
train
|
pypa/pipenv
|
pipenv/vendor/requests/cookies.py
|
cookiejar_from_dict
|
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
|
python
|
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
|
[
"def",
"cookiejar_from_dict",
"(",
"cookie_dict",
",",
"cookiejar",
"=",
"None",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"cookiejar",
"is",
"None",
":",
"cookiejar",
"=",
"RequestsCookieJar",
"(",
")",
"if",
"cookie_dict",
"is",
"not",
"None",
":",
"names_from_jar",
"=",
"[",
"cookie",
".",
"name",
"for",
"cookie",
"in",
"cookiejar",
"]",
"for",
"name",
"in",
"cookie_dict",
":",
"if",
"overwrite",
"or",
"(",
"name",
"not",
"in",
"names_from_jar",
")",
":",
"cookiejar",
".",
"set_cookie",
"(",
"create_cookie",
"(",
"name",
",",
"cookie_dict",
"[",
"name",
"]",
")",
")",
"return",
"cookiejar"
] |
Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
:rtype: CookieJar
|
[
"Returns",
"a",
"CookieJar",
"from",
"a",
"key",
"/",
"value",
"dictionary",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L508-L526
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/requests/cookies.py
|
RequestsCookieJar.get
|
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
"""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
|
python
|
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
"""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
|
[
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_find_no_duplicates",
"(",
"name",
",",
"domain",
",",
"path",
")",
"except",
"KeyError",
":",
"return",
"default"
] |
Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
|
[
"Dict",
"-",
"like",
"get",
"()",
"that",
"also",
"supports",
"optional",
"domain",
"and",
"path",
"args",
"in",
"order",
"to",
"resolve",
"naming",
"collisions",
"from",
"using",
"one",
"cookie",
"jar",
"over",
"multiple",
"domains",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L189-L199
|
train
|
pypa/pipenv
|
pipenv/vendor/requests/cookies.py
|
RequestsCookieJar.set
|
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
|
python
|
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
|
[
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"# support client code that unsets cookies by assignment of a None value:",
"if",
"value",
"is",
"None",
":",
"remove_cookie_by_name",
"(",
"self",
",",
"name",
",",
"domain",
"=",
"kwargs",
".",
"get",
"(",
"'domain'",
")",
",",
"path",
"=",
"kwargs",
".",
"get",
"(",
"'path'",
")",
")",
"return",
"if",
"isinstance",
"(",
"value",
",",
"Morsel",
")",
":",
"c",
"=",
"morsel_to_cookie",
"(",
"value",
")",
"else",
":",
"c",
"=",
"create_cookie",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"set_cookie",
"(",
"c",
")",
"return",
"c"
] |
Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
|
[
"Dict",
"-",
"like",
"set",
"()",
"that",
"also",
"supports",
"optional",
"domain",
"and",
"path",
"args",
"in",
"order",
"to",
"resolve",
"naming",
"collisions",
"from",
"using",
"one",
"cookie",
"jar",
"over",
"multiple",
"domains",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L201-L216
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/requests/cookies.py
|
RequestsCookieJar._find_no_duplicates
|
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
"""
toReturn = 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:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
|
python
|
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
"""
toReturn = 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:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
|
[
"def",
"_find_no_duplicates",
"(",
"self",
",",
"name",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"toReturn",
"=",
"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",
":",
"if",
"toReturn",
"is",
"not",
"None",
":",
"# if there are multiple cookies that meet passed in criteria",
"raise",
"CookieConflictError",
"(",
"'There are multiple cookies with name, %r'",
"%",
"(",
"name",
")",
")",
"toReturn",
"=",
"cookie",
".",
"value",
"# we will eventually return this as long as no cookie conflict",
"if",
"toReturn",
":",
"return",
"toReturn",
"raise",
"KeyError",
"(",
"'name=%r, domain=%r, path=%r'",
"%",
"(",
"name",
",",
"domain",
",",
"path",
")",
")"
] |
Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
|
[
"Both",
"__get_item__",
"and",
"get",
"call",
"this",
"function",
":",
"it",
"s",
"never",
"used",
"elsewhere",
"in",
"Requests",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/cookies.py#L376-L399
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/screen.py
|
screen._decode
|
def _decode(self, s):
'''This converts from the external coding system (as passed to
the constructor) to the internal one (unicode). '''
if self.decoder is not None:
return self.decoder.decode(s)
else:
raise TypeError("This screen was constructed with encoding=None, "
"so it does not handle bytes.")
|
python
|
def _decode(self, s):
'''This converts from the external coding system (as passed to
the constructor) to the internal one (unicode). '''
if self.decoder is not None:
return self.decoder.decode(s)
else:
raise TypeError("This screen was constructed with encoding=None, "
"so it does not handle bytes.")
|
[
"def",
"_decode",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"decoder",
"is",
"not",
"None",
":",
"return",
"self",
".",
"decoder",
".",
"decode",
"(",
"s",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"This screen was constructed with encoding=None, \"",
"\"so it does not handle bytes.\"",
")"
] |
This converts from the external coding system (as passed to
the constructor) to the internal one (unicode).
|
[
"This",
"converts",
"from",
"the",
"external",
"coding",
"system",
"(",
"as",
"passed",
"to",
"the",
"constructor",
")",
"to",
"the",
"internal",
"one",
"(",
"unicode",
")",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L104-L111
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/screen.py
|
screen._unicode
|
def _unicode(self):
'''This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline.'''
return u'\n'.join ([ u''.join(c) for c in self.w ])
|
python
|
def _unicode(self):
'''This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline.'''
return u'\n'.join ([ u''.join(c) for c in self.w ])
|
[
"def",
"_unicode",
"(",
"self",
")",
":",
"return",
"u'\\n'",
".",
"join",
"(",
"[",
"u''",
".",
"join",
"(",
"c",
")",
"for",
"c",
"in",
"self",
".",
"w",
"]",
")"
] |
This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline.
|
[
"This",
"returns",
"a",
"printable",
"representation",
"of",
"the",
"screen",
"as",
"a",
"unicode",
"string",
"(",
"which",
"under",
"Python",
"3",
".",
"x",
"is",
"the",
"same",
"as",
"str",
")",
".",
"The",
"end",
"of",
"each",
"screen",
"line",
"is",
"terminated",
"by",
"a",
"newline",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L113-L118
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/screen.py
|
screen.dump
|
def dump (self):
'''This returns a copy of the screen as a unicode string. This is similar to
__str__/__unicode__ except that lines are not terminated with line
feeds.'''
return u''.join ([ u''.join(c) for c in self.w ])
|
python
|
def dump (self):
'''This returns a copy of the screen as a unicode string. This is similar to
__str__/__unicode__ except that lines are not terminated with line
feeds.'''
return u''.join ([ u''.join(c) for c in self.w ])
|
[
"def",
"dump",
"(",
"self",
")",
":",
"return",
"u''",
".",
"join",
"(",
"[",
"u''",
".",
"join",
"(",
"c",
")",
"for",
"c",
"in",
"self",
".",
"w",
"]",
")"
] |
This returns a copy of the screen as a unicode string. This is similar to
__str__/__unicode__ except that lines are not terminated with line
feeds.
|
[
"This",
"returns",
"a",
"copy",
"of",
"the",
"screen",
"as",
"a",
"unicode",
"string",
".",
"This",
"is",
"similar",
"to",
"__str__",
"/",
"__unicode__",
"except",
"that",
"lines",
"are",
"not",
"terminated",
"with",
"line",
"feeds",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L131-L136
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/screen.py
|
screen.pretty
|
def pretty (self):
'''This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.'''
top_bot = u'+' + u'-'*self.cols + u'+\n'
return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
|
python
|
def pretty (self):
'''This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.'''
top_bot = u'+' + u'-'*self.cols + u'+\n'
return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
|
[
"def",
"pretty",
"(",
"self",
")",
":",
"top_bot",
"=",
"u'+'",
"+",
"u'-'",
"*",
"self",
".",
"cols",
"+",
"u'+\\n'",
"return",
"top_bot",
"+",
"u'\\n'",
".",
"join",
"(",
"[",
"u'|'",
"+",
"line",
"+",
"u'|'",
"for",
"line",
"in",
"unicode",
"(",
"self",
")",
".",
"split",
"(",
"u'\\n'",
")",
"]",
")",
"+",
"u'\\n'",
"+",
"top_bot"
] |
This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.
|
[
"This",
"returns",
"a",
"copy",
"of",
"the",
"screen",
"as",
"a",
"unicode",
"string",
"with",
"an",
"ASCII",
"text",
"box",
"around",
"the",
"screen",
"border",
".",
"This",
"is",
"similar",
"to",
"__str__",
"/",
"__unicode__",
"except",
"that",
"it",
"adds",
"a",
"box",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L138-L144
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/screen.py
|
screen.insert_abs
|
def insert_abs (self, r, c, ch):
'''This inserts a character at (r,c). Everything under
and to the right is shifted right one character.
The last character of the line is lost.
'''
if isinstance(ch, bytes):
ch = self._decode(ch)
r = constrain (r, 1, self.rows)
c = constrain (c, 1, self.cols)
for ci in range (self.cols, c, -1):
self.put_abs (r,ci, self.get_abs(r,ci-1))
self.put_abs (r,c,ch)
|
python
|
def insert_abs (self, r, c, ch):
'''This inserts a character at (r,c). Everything under
and to the right is shifted right one character.
The last character of the line is lost.
'''
if isinstance(ch, bytes):
ch = self._decode(ch)
r = constrain (r, 1, self.rows)
c = constrain (c, 1, self.cols)
for ci in range (self.cols, c, -1):
self.put_abs (r,ci, self.get_abs(r,ci-1))
self.put_abs (r,c,ch)
|
[
"def",
"insert_abs",
"(",
"self",
",",
"r",
",",
"c",
",",
"ch",
")",
":",
"if",
"isinstance",
"(",
"ch",
",",
"bytes",
")",
":",
"ch",
"=",
"self",
".",
"_decode",
"(",
"ch",
")",
"r",
"=",
"constrain",
"(",
"r",
",",
"1",
",",
"self",
".",
"rows",
")",
"c",
"=",
"constrain",
"(",
"c",
",",
"1",
",",
"self",
".",
"cols",
")",
"for",
"ci",
"in",
"range",
"(",
"self",
".",
"cols",
",",
"c",
",",
"-",
"1",
")",
":",
"self",
".",
"put_abs",
"(",
"r",
",",
"ci",
",",
"self",
".",
"get_abs",
"(",
"r",
",",
"ci",
"-",
"1",
")",
")",
"self",
".",
"put_abs",
"(",
"r",
",",
"c",
",",
"ch",
")"
] |
This inserts a character at (r,c). Everything under
and to the right is shifted right one character.
The last character of the line is lost.
|
[
"This",
"inserts",
"a",
"character",
"at",
"(",
"r",
"c",
")",
".",
"Everything",
"under",
"and",
"to",
"the",
"right",
"is",
"shifted",
"right",
"one",
"character",
".",
"The",
"last",
"character",
"of",
"the",
"line",
"is",
"lost",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L220-L233
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/screen.py
|
screen.scroll_screen_rows
|
def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r
'''Enable scrolling from row {start} to row {end}.'''
self.scroll_row_start = rs
self.scroll_row_end = re
self.scroll_constrain()
|
python
|
def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r
'''Enable scrolling from row {start} to row {end}.'''
self.scroll_row_start = rs
self.scroll_row_end = re
self.scroll_constrain()
|
[
"def",
"scroll_screen_rows",
"(",
"self",
",",
"rs",
",",
"re",
")",
":",
"# <ESC>[{start};{end}r",
"self",
".",
"scroll_row_start",
"=",
"rs",
"self",
".",
"scroll_row_end",
"=",
"re",
"self",
".",
"scroll_constrain",
"(",
")"
] |
Enable scrolling from row {start} to row {end}.
|
[
"Enable",
"scrolling",
"from",
"row",
"{",
"start",
"}",
"to",
"row",
"{",
"end",
"}",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/screen.py#L353-L358
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/iso8601/iso8601.py
|
parse_timezone
|
def parse_timezone(matches, default_timezone=UTC):
"""Parses ISO 8601 time zone specs into tzinfo offsets
"""
if matches["timezone"] == "Z":
return UTC
# This isn't strictly correct, but it's common to encounter dates without
# timezones so I'll assume the default (which defaults to UTC).
# Addresses issue 4.
if matches["timezone"] is None:
return default_timezone
sign = matches["tz_sign"]
hours = to_int(matches, "tz_hour")
minutes = to_int(matches, "tz_minute", default_to_zero=True)
description = "%s%02d:%02d" % (sign, hours, minutes)
if sign == "-":
hours = -hours
minutes = -minutes
return FixedOffset(hours, minutes, description)
|
python
|
def parse_timezone(matches, default_timezone=UTC):
"""Parses ISO 8601 time zone specs into tzinfo offsets
"""
if matches["timezone"] == "Z":
return UTC
# This isn't strictly correct, but it's common to encounter dates without
# timezones so I'll assume the default (which defaults to UTC).
# Addresses issue 4.
if matches["timezone"] is None:
return default_timezone
sign = matches["tz_sign"]
hours = to_int(matches, "tz_hour")
minutes = to_int(matches, "tz_minute", default_to_zero=True)
description = "%s%02d:%02d" % (sign, hours, minutes)
if sign == "-":
hours = -hours
minutes = -minutes
return FixedOffset(hours, minutes, description)
|
[
"def",
"parse_timezone",
"(",
"matches",
",",
"default_timezone",
"=",
"UTC",
")",
":",
"if",
"matches",
"[",
"\"timezone\"",
"]",
"==",
"\"Z\"",
":",
"return",
"UTC",
"# This isn't strictly correct, but it's common to encounter dates without",
"# timezones so I'll assume the default (which defaults to UTC).",
"# Addresses issue 4.",
"if",
"matches",
"[",
"\"timezone\"",
"]",
"is",
"None",
":",
"return",
"default_timezone",
"sign",
"=",
"matches",
"[",
"\"tz_sign\"",
"]",
"hours",
"=",
"to_int",
"(",
"matches",
",",
"\"tz_hour\"",
")",
"minutes",
"=",
"to_int",
"(",
"matches",
",",
"\"tz_minute\"",
",",
"default_to_zero",
"=",
"True",
")",
"description",
"=",
"\"%s%02d:%02d\"",
"%",
"(",
"sign",
",",
"hours",
",",
"minutes",
")",
"if",
"sign",
"==",
"\"-\"",
":",
"hours",
"=",
"-",
"hours",
"minutes",
"=",
"-",
"minutes",
"return",
"FixedOffset",
"(",
"hours",
",",
"minutes",
",",
"description",
")"
] |
Parses ISO 8601 time zone specs into tzinfo offsets
|
[
"Parses",
"ISO",
"8601",
"time",
"zone",
"specs",
"into",
"tzinfo",
"offsets"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/iso8601/iso8601.py#L153-L172
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/yaspin/signal_handlers.py
|
default_handler
|
def default_handler(signum, frame, spinner):
"""Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
"""
spinner.fail()
spinner.stop()
sys.exit(0)
|
python
|
def default_handler(signum, frame, spinner):
"""Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
"""
spinner.fail()
spinner.stop()
sys.exit(0)
|
[
"def",
"default_handler",
"(",
"signum",
",",
"frame",
",",
"spinner",
")",
":",
"spinner",
".",
"fail",
"(",
")",
"spinner",
".",
"stop",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] |
Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
|
[
"Signal",
"handler",
"used",
"to",
"gracefully",
"shut",
"down",
"the",
"spinner",
"instance",
"when",
"specified",
"signal",
"is",
"received",
"by",
"the",
"process",
"running",
"the",
"spinner",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/signal_handlers.py#L14-L23
|
train
|
pypa/pipenv
|
pipenv/vendor/yaspin/signal_handlers.py
|
fancy_handler
|
def fancy_handler(signum, frame, spinner):
"""Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
"""
spinner.red.fail("✘")
spinner.stop()
sys.exit(0)
|
python
|
def fancy_handler(signum, frame, spinner):
"""Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
"""
spinner.red.fail("✘")
spinner.stop()
sys.exit(0)
|
[
"def",
"fancy_handler",
"(",
"signum",
",",
"frame",
",",
"spinner",
")",
":",
"spinner",
".",
"red",
".",
"fail",
"(",
"\"✘\")",
"",
"spinner",
".",
"stop",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] |
Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
|
[
"Signal",
"handler",
"used",
"to",
"gracefully",
"shut",
"down",
"the",
"spinner",
"instance",
"when",
"specified",
"signal",
"is",
"received",
"by",
"the",
"process",
"running",
"the",
"spinner",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yaspin/signal_handlers.py#L26-L35
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/yarg/release.py
|
Release.package_type
|
def package_type(self):
"""
>>> package = yarg.get('yarg')
>>> v = "0.1.0"
>>> r = package.release(v)
>>> r.package_type
u'wheel'
"""
mapping = {'bdist_egg': u'egg', 'bdist_wheel': u'wheel',
'sdist': u'source'}
ptype = self._release['packagetype']
if ptype in mapping.keys():
return mapping[ptype]
return ptype
|
python
|
def package_type(self):
"""
>>> package = yarg.get('yarg')
>>> v = "0.1.0"
>>> r = package.release(v)
>>> r.package_type
u'wheel'
"""
mapping = {'bdist_egg': u'egg', 'bdist_wheel': u'wheel',
'sdist': u'source'}
ptype = self._release['packagetype']
if ptype in mapping.keys():
return mapping[ptype]
return ptype
|
[
"def",
"package_type",
"(",
"self",
")",
":",
"mapping",
"=",
"{",
"'bdist_egg'",
":",
"u'egg'",
",",
"'bdist_wheel'",
":",
"u'wheel'",
",",
"'sdist'",
":",
"u'source'",
"}",
"ptype",
"=",
"self",
".",
"_release",
"[",
"'packagetype'",
"]",
"if",
"ptype",
"in",
"mapping",
".",
"keys",
"(",
")",
":",
"return",
"mapping",
"[",
"ptype",
"]",
"return",
"ptype"
] |
>>> package = yarg.get('yarg')
>>> v = "0.1.0"
>>> r = package.release(v)
>>> r.package_type
u'wheel'
|
[
">>>",
"package",
"=",
"yarg",
".",
"get",
"(",
"yarg",
")",
">>>",
"v",
"=",
"0",
".",
"1",
".",
"0",
">>>",
"r",
"=",
"package",
".",
"release",
"(",
"v",
")",
">>>",
"r",
".",
"package_type",
"u",
"wheel"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/release.py#L123-L136
|
train
|
pypa/pipenv
|
pipenv/vendor/pexpect/ANSI.py
|
ANSI.process
|
def process (self, c):
"""Process a single character. Called by :meth:`write`."""
if isinstance(c, bytes):
c = self._decode(c)
self.state.process(c)
|
python
|
def process (self, c):
"""Process a single character. Called by :meth:`write`."""
if isinstance(c, bytes):
c = self._decode(c)
self.state.process(c)
|
[
"def",
"process",
"(",
"self",
",",
"c",
")",
":",
"if",
"isinstance",
"(",
"c",
",",
"bytes",
")",
":",
"c",
"=",
"self",
".",
"_decode",
"(",
"c",
")",
"self",
".",
"state",
".",
"process",
"(",
"c",
")"
] |
Process a single character. Called by :meth:`write`.
|
[
"Process",
"a",
"single",
"character",
".",
"Called",
"by",
":",
"meth",
":",
"write",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pexpect/ANSI.py#L281-L285
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/urllib3/util/request.py
|
make_headers
|
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None, proxy_basic_auth=None, disable_cache=None):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
auth header.
:param proxy_basic_auth:
Colon-separated username:password string for 'proxy-authorization: basic ...'
auth header.
:param disable_cache:
If ``True``, adds 'cache-control: no-cache' header.
Example::
>>> make_headers(keep_alive=True, user_agent="Batman/1.0")
{'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
>>> make_headers(accept_encoding=True)
{'accept-encoding': 'gzip,deflate'}
"""
headers = {}
if accept_encoding:
if isinstance(accept_encoding, str):
pass
elif isinstance(accept_encoding, list):
accept_encoding = ','.join(accept_encoding)
else:
accept_encoding = ACCEPT_ENCODING
headers['accept-encoding'] = accept_encoding
if user_agent:
headers['user-agent'] = user_agent
if keep_alive:
headers['connection'] = 'keep-alive'
if basic_auth:
headers['authorization'] = 'Basic ' + \
b64encode(b(basic_auth)).decode('utf-8')
if proxy_basic_auth:
headers['proxy-authorization'] = 'Basic ' + \
b64encode(b(proxy_basic_auth)).decode('utf-8')
if disable_cache:
headers['cache-control'] = 'no-cache'
return headers
|
python
|
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None, proxy_basic_auth=None, disable_cache=None):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
auth header.
:param proxy_basic_auth:
Colon-separated username:password string for 'proxy-authorization: basic ...'
auth header.
:param disable_cache:
If ``True``, adds 'cache-control: no-cache' header.
Example::
>>> make_headers(keep_alive=True, user_agent="Batman/1.0")
{'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
>>> make_headers(accept_encoding=True)
{'accept-encoding': 'gzip,deflate'}
"""
headers = {}
if accept_encoding:
if isinstance(accept_encoding, str):
pass
elif isinstance(accept_encoding, list):
accept_encoding = ','.join(accept_encoding)
else:
accept_encoding = ACCEPT_ENCODING
headers['accept-encoding'] = accept_encoding
if user_agent:
headers['user-agent'] = user_agent
if keep_alive:
headers['connection'] = 'keep-alive'
if basic_auth:
headers['authorization'] = 'Basic ' + \
b64encode(b(basic_auth)).decode('utf-8')
if proxy_basic_auth:
headers['proxy-authorization'] = 'Basic ' + \
b64encode(b(proxy_basic_auth)).decode('utf-8')
if disable_cache:
headers['cache-control'] = 'no-cache'
return headers
|
[
"def",
"make_headers",
"(",
"keep_alive",
"=",
"None",
",",
"accept_encoding",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"basic_auth",
"=",
"None",
",",
"proxy_basic_auth",
"=",
"None",
",",
"disable_cache",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"}",
"if",
"accept_encoding",
":",
"if",
"isinstance",
"(",
"accept_encoding",
",",
"str",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"accept_encoding",
",",
"list",
")",
":",
"accept_encoding",
"=",
"','",
".",
"join",
"(",
"accept_encoding",
")",
"else",
":",
"accept_encoding",
"=",
"ACCEPT_ENCODING",
"headers",
"[",
"'accept-encoding'",
"]",
"=",
"accept_encoding",
"if",
"user_agent",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"user_agent",
"if",
"keep_alive",
":",
"headers",
"[",
"'connection'",
"]",
"=",
"'keep-alive'",
"if",
"basic_auth",
":",
"headers",
"[",
"'authorization'",
"]",
"=",
"'Basic '",
"+",
"b64encode",
"(",
"b",
"(",
"basic_auth",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"proxy_basic_auth",
":",
"headers",
"[",
"'proxy-authorization'",
"]",
"=",
"'Basic '",
"+",
"b64encode",
"(",
"b",
"(",
"proxy_basic_auth",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"disable_cache",
":",
"headers",
"[",
"'cache-control'",
"]",
"=",
"'no-cache'",
"return",
"headers"
] |
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
auth header.
:param proxy_basic_auth:
Colon-separated username:password string for 'proxy-authorization: basic ...'
auth header.
:param disable_cache:
If ``True``, adds 'cache-control: no-cache' header.
Example::
>>> make_headers(keep_alive=True, user_agent="Batman/1.0")
{'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
>>> make_headers(accept_encoding=True)
{'accept-encoding': 'gzip,deflate'}
|
[
"Shortcuts",
"for",
"generating",
"request",
"headers",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/request.py#L11-L74
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/cerberus/utils.py
|
mapping_to_frozenset
|
def mapping_to_frozenset(mapping):
""" Be aware that this treats any sequence type with the equal members as
equal. As it is used to identify equality of schemas, this can be
considered okay as definitions are semantically equal regardless the
container type. """
mapping = mapping.copy()
for key, value in mapping.items():
if isinstance(value, Mapping):
mapping[key] = mapping_to_frozenset(value)
elif isinstance(value, Sequence):
value = list(value)
for i, item in enumerate(value):
if isinstance(item, Mapping):
value[i] = mapping_to_frozenset(item)
mapping[key] = tuple(value)
return frozenset(mapping.items())
|
python
|
def mapping_to_frozenset(mapping):
""" Be aware that this treats any sequence type with the equal members as
equal. As it is used to identify equality of schemas, this can be
considered okay as definitions are semantically equal regardless the
container type. """
mapping = mapping.copy()
for key, value in mapping.items():
if isinstance(value, Mapping):
mapping[key] = mapping_to_frozenset(value)
elif isinstance(value, Sequence):
value = list(value)
for i, item in enumerate(value):
if isinstance(item, Mapping):
value[i] = mapping_to_frozenset(item)
mapping[key] = tuple(value)
return frozenset(mapping.items())
|
[
"def",
"mapping_to_frozenset",
"(",
"mapping",
")",
":",
"mapping",
"=",
"mapping",
".",
"copy",
"(",
")",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Mapping",
")",
":",
"mapping",
"[",
"key",
"]",
"=",
"mapping_to_frozenset",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"Sequence",
")",
":",
"value",
"=",
"list",
"(",
"value",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"Mapping",
")",
":",
"value",
"[",
"i",
"]",
"=",
"mapping_to_frozenset",
"(",
"item",
")",
"mapping",
"[",
"key",
"]",
"=",
"tuple",
"(",
"value",
")",
"return",
"frozenset",
"(",
"mapping",
".",
"items",
"(",
")",
")"
] |
Be aware that this treats any sequence type with the equal members as
equal. As it is used to identify equality of schemas, this can be
considered okay as definitions are semantically equal regardless the
container type.
|
[
"Be",
"aware",
"that",
"this",
"treats",
"any",
"sequence",
"type",
"with",
"the",
"equal",
"members",
"as",
"equal",
".",
"As",
"it",
"is",
"used",
"to",
"identify",
"equality",
"of",
"schemas",
"this",
"can",
"be",
"considered",
"okay",
"as",
"definitions",
"are",
"semantically",
"equal",
"regardless",
"the",
"container",
"type",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/utils.py#L48-L63
|
train
|
pypa/pipenv
|
pipenv/vendor/cerberus/utils.py
|
validator_factory
|
def validator_factory(name, bases=None, namespace={}):
""" Dynamically create a :class:`~cerberus.Validator` subclass.
Docstrings of mixin-classes will be added to the resulting
class' one if ``__doc__`` is not in :obj:`namespace`.
:param name: The name of the new class.
:type name: :class:`str`
:param bases: Class(es) with additional and overriding attributes.
:type bases: :class:`tuple` of or a single :term:`class`
:param namespace: Attributes for the new class.
:type namespace: :class:`dict`
:return: The created class.
"""
Validator = get_Validator_class()
if bases is None:
bases = (Validator,)
elif isinstance(bases, tuple):
bases += (Validator,)
else:
bases = (bases, Validator)
docstrings = [x.__doc__ for x in bases if x.__doc__]
if len(docstrings) > 1 and '__doc__' not in namespace:
namespace.update({'__doc__': '\n'.join(docstrings)})
return type(name, bases, namespace)
|
python
|
def validator_factory(name, bases=None, namespace={}):
""" Dynamically create a :class:`~cerberus.Validator` subclass.
Docstrings of mixin-classes will be added to the resulting
class' one if ``__doc__`` is not in :obj:`namespace`.
:param name: The name of the new class.
:type name: :class:`str`
:param bases: Class(es) with additional and overriding attributes.
:type bases: :class:`tuple` of or a single :term:`class`
:param namespace: Attributes for the new class.
:type namespace: :class:`dict`
:return: The created class.
"""
Validator = get_Validator_class()
if bases is None:
bases = (Validator,)
elif isinstance(bases, tuple):
bases += (Validator,)
else:
bases = (bases, Validator)
docstrings = [x.__doc__ for x in bases if x.__doc__]
if len(docstrings) > 1 and '__doc__' not in namespace:
namespace.update({'__doc__': '\n'.join(docstrings)})
return type(name, bases, namespace)
|
[
"def",
"validator_factory",
"(",
"name",
",",
"bases",
"=",
"None",
",",
"namespace",
"=",
"{",
"}",
")",
":",
"Validator",
"=",
"get_Validator_class",
"(",
")",
"if",
"bases",
"is",
"None",
":",
"bases",
"=",
"(",
"Validator",
",",
")",
"elif",
"isinstance",
"(",
"bases",
",",
"tuple",
")",
":",
"bases",
"+=",
"(",
"Validator",
",",
")",
"else",
":",
"bases",
"=",
"(",
"bases",
",",
"Validator",
")",
"docstrings",
"=",
"[",
"x",
".",
"__doc__",
"for",
"x",
"in",
"bases",
"if",
"x",
".",
"__doc__",
"]",
"if",
"len",
"(",
"docstrings",
")",
">",
"1",
"and",
"'__doc__'",
"not",
"in",
"namespace",
":",
"namespace",
".",
"update",
"(",
"{",
"'__doc__'",
":",
"'\\n'",
".",
"join",
"(",
"docstrings",
")",
"}",
")",
"return",
"type",
"(",
"name",
",",
"bases",
",",
"namespace",
")"
] |
Dynamically create a :class:`~cerberus.Validator` subclass.
Docstrings of mixin-classes will be added to the resulting
class' one if ``__doc__`` is not in :obj:`namespace`.
:param name: The name of the new class.
:type name: :class:`str`
:param bases: Class(es) with additional and overriding attributes.
:type bases: :class:`tuple` of or a single :term:`class`
:param namespace: Attributes for the new class.
:type namespace: :class:`dict`
:return: The created class.
|
[
"Dynamically",
"create",
"a",
":",
"class",
":",
"~cerberus",
".",
"Validator",
"subclass",
".",
"Docstrings",
"of",
"mixin",
"-",
"classes",
"will",
"be",
"added",
"to",
"the",
"resulting",
"class",
"one",
"if",
"__doc__",
"is",
"not",
"in",
":",
"obj",
":",
"namespace",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/utils.py#L93-L119
|
train
|
pypa/pipenv
|
pipenv/vendor/vistir/cmdparse.py
|
Script.cmdify
|
def cmdify(self):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are doubled, so they are all
escaped properly.
* Backslashes elsewhere are left as-is; cmd will interpret them
literally.
The result is then quoted into a pair of double quotes to be grouped.
An argument is intentionally not quoted if it does not contain
whitespaces. This is done to be compatible with Windows built-in
commands that don't work well with quotes, e.g. everything with `echo`,
and DOS-style (forward slash) switches.
The intended use of this function is to pre-process an argument list
before passing it into ``subprocess.Popen(..., shell=True)``.
See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence
"""
return " ".join(
itertools.chain(
[_quote_if_contains(self.command, r"[\s^()]")],
(_quote_if_contains(arg, r"[\s^]") for arg in self.args),
)
)
|
python
|
def cmdify(self):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are doubled, so they are all
escaped properly.
* Backslashes elsewhere are left as-is; cmd will interpret them
literally.
The result is then quoted into a pair of double quotes to be grouped.
An argument is intentionally not quoted if it does not contain
whitespaces. This is done to be compatible with Windows built-in
commands that don't work well with quotes, e.g. everything with `echo`,
and DOS-style (forward slash) switches.
The intended use of this function is to pre-process an argument list
before passing it into ``subprocess.Popen(..., shell=True)``.
See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence
"""
return " ".join(
itertools.chain(
[_quote_if_contains(self.command, r"[\s^()]")],
(_quote_if_contains(arg, r"[\s^]") for arg in self.args),
)
)
|
[
"def",
"cmdify",
"(",
"self",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"itertools",
".",
"chain",
"(",
"[",
"_quote_if_contains",
"(",
"self",
".",
"command",
",",
"r\"[\\s^()]\"",
")",
"]",
",",
"(",
"_quote_if_contains",
"(",
"arg",
",",
"r\"[\\s^]\"",
")",
"for",
"arg",
"in",
"self",
".",
"args",
")",
",",
")",
")"
] |
Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are doubled, so they are all
escaped properly.
* Backslashes elsewhere are left as-is; cmd will interpret them
literally.
The result is then quoted into a pair of double quotes to be grouped.
An argument is intentionally not quoted if it does not contain
whitespaces. This is done to be compatible with Windows built-in
commands that don't work well with quotes, e.g. everything with `echo`,
and DOS-style (forward slash) switches.
The intended use of this function is to pre-process an argument list
before passing it into ``subprocess.Popen(..., shell=True)``.
See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence
|
[
"Encode",
"into",
"a",
"cmd",
"-",
"executable",
"string",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/cmdparse.py#L56-L85
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/attr/filters.py
|
include
|
def include(*what):
"""
Whitelist *what*.
:param what: What to whitelist.
:type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or attribute in attrs
return include_
|
python
|
def include(*what):
"""
Whitelist *what*.
:param what: What to whitelist.
:type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or attribute in attrs
return include_
|
[
"def",
"include",
"(",
"*",
"what",
")",
":",
"cls",
",",
"attrs",
"=",
"_split_what",
"(",
"what",
")",
"def",
"include_",
"(",
"attribute",
",",
"value",
")",
":",
"return",
"value",
".",
"__class__",
"in",
"cls",
"or",
"attribute",
"in",
"attrs",
"return",
"include_"
] |
Whitelist *what*.
:param what: What to whitelist.
:type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s
:rtype: :class:`callable`
|
[
"Whitelist",
"*",
"what",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/filters.py#L21-L35
|
train
|
pypa/pipenv
|
pipenv/vendor/attr/filters.py
|
exclude
|
def exclude(*what):
"""
Blacklist *what*.
:param what: What to blacklist.
:type what: :class:`list` of classes or :class:`attr.Attribute`\\ s.
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def exclude_(attribute, value):
return value.__class__ not in cls and attribute not in attrs
return exclude_
|
python
|
def exclude(*what):
"""
Blacklist *what*.
:param what: What to blacklist.
:type what: :class:`list` of classes or :class:`attr.Attribute`\\ s.
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def exclude_(attribute, value):
return value.__class__ not in cls and attribute not in attrs
return exclude_
|
[
"def",
"exclude",
"(",
"*",
"what",
")",
":",
"cls",
",",
"attrs",
"=",
"_split_what",
"(",
"what",
")",
"def",
"exclude_",
"(",
"attribute",
",",
"value",
")",
":",
"return",
"value",
".",
"__class__",
"not",
"in",
"cls",
"and",
"attribute",
"not",
"in",
"attrs",
"return",
"exclude_"
] |
Blacklist *what*.
:param what: What to blacklist.
:type what: :class:`list` of classes or :class:`attr.Attribute`\\ s.
:rtype: :class:`callable`
|
[
"Blacklist",
"*",
"what",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/filters.py#L38-L52
|
train
|
pypa/pipenv
|
pipenv/vendor/attr/_funcs.py
|
asdict
|
def asdict(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
):
"""
Return the ``attrs`` attribute values of *inst* as a dict.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the
value as the second argument.
:param callable dict_factory: A callable to produce dictionaries from. For
example, to produce ordered dictionaries instead of normal Python
dictionaries, pass in ``collections.OrderedDict``.
:param bool retain_collection_types: Do not convert to ``list`` when
encountering an attribute whose type is ``tuple`` or ``set``. Only
meaningful if ``recurse`` is ``True``.
:rtype: return type of *dict_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.0.0 *dict_factory*
.. versionadded:: 16.1.0 *retain_collection_types*
"""
attrs = fields(inst.__class__)
rv = dict_factory()
for a in attrs:
v = getattr(inst, a.name)
if filter is not None and not filter(a, v):
continue
if recurse is True:
if has(v.__class__):
rv[a.name] = asdict(
v, True, filter, dict_factory, retain_collection_types
)
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain_collection_types is True else list
rv[a.name] = cf(
[
_asdict_anything(
i, filter, dict_factory, retain_collection_types
)
for i in v
]
)
elif isinstance(v, dict):
df = dict_factory
rv[a.name] = df(
(
_asdict_anything(
kk, filter, df, retain_collection_types
),
_asdict_anything(
vv, filter, df, retain_collection_types
),
)
for kk, vv in iteritems(v)
)
else:
rv[a.name] = v
else:
rv[a.name] = v
return rv
|
python
|
def asdict(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
):
"""
Return the ``attrs`` attribute values of *inst* as a dict.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the
value as the second argument.
:param callable dict_factory: A callable to produce dictionaries from. For
example, to produce ordered dictionaries instead of normal Python
dictionaries, pass in ``collections.OrderedDict``.
:param bool retain_collection_types: Do not convert to ``list`` when
encountering an attribute whose type is ``tuple`` or ``set``. Only
meaningful if ``recurse`` is ``True``.
:rtype: return type of *dict_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.0.0 *dict_factory*
.. versionadded:: 16.1.0 *retain_collection_types*
"""
attrs = fields(inst.__class__)
rv = dict_factory()
for a in attrs:
v = getattr(inst, a.name)
if filter is not None and not filter(a, v):
continue
if recurse is True:
if has(v.__class__):
rv[a.name] = asdict(
v, True, filter, dict_factory, retain_collection_types
)
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain_collection_types is True else list
rv[a.name] = cf(
[
_asdict_anything(
i, filter, dict_factory, retain_collection_types
)
for i in v
]
)
elif isinstance(v, dict):
df = dict_factory
rv[a.name] = df(
(
_asdict_anything(
kk, filter, df, retain_collection_types
),
_asdict_anything(
vv, filter, df, retain_collection_types
),
)
for kk, vv in iteritems(v)
)
else:
rv[a.name] = v
else:
rv[a.name] = v
return rv
|
[
"def",
"asdict",
"(",
"inst",
",",
"recurse",
"=",
"True",
",",
"filter",
"=",
"None",
",",
"dict_factory",
"=",
"dict",
",",
"retain_collection_types",
"=",
"False",
",",
")",
":",
"attrs",
"=",
"fields",
"(",
"inst",
".",
"__class__",
")",
"rv",
"=",
"dict_factory",
"(",
")",
"for",
"a",
"in",
"attrs",
":",
"v",
"=",
"getattr",
"(",
"inst",
",",
"a",
".",
"name",
")",
"if",
"filter",
"is",
"not",
"None",
"and",
"not",
"filter",
"(",
"a",
",",
"v",
")",
":",
"continue",
"if",
"recurse",
"is",
"True",
":",
"if",
"has",
"(",
"v",
".",
"__class__",
")",
":",
"rv",
"[",
"a",
".",
"name",
"]",
"=",
"asdict",
"(",
"v",
",",
"True",
",",
"filter",
",",
"dict_factory",
",",
"retain_collection_types",
")",
"elif",
"isinstance",
"(",
"v",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"cf",
"=",
"v",
".",
"__class__",
"if",
"retain_collection_types",
"is",
"True",
"else",
"list",
"rv",
"[",
"a",
".",
"name",
"]",
"=",
"cf",
"(",
"[",
"_asdict_anything",
"(",
"i",
",",
"filter",
",",
"dict_factory",
",",
"retain_collection_types",
")",
"for",
"i",
"in",
"v",
"]",
")",
"elif",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"df",
"=",
"dict_factory",
"rv",
"[",
"a",
".",
"name",
"]",
"=",
"df",
"(",
"(",
"_asdict_anything",
"(",
"kk",
",",
"filter",
",",
"df",
",",
"retain_collection_types",
")",
",",
"_asdict_anything",
"(",
"vv",
",",
"filter",
",",
"df",
",",
"retain_collection_types",
")",
",",
")",
"for",
"kk",
",",
"vv",
"in",
"iteritems",
"(",
"v",
")",
")",
"else",
":",
"rv",
"[",
"a",
".",
"name",
"]",
"=",
"v",
"else",
":",
"rv",
"[",
"a",
".",
"name",
"]",
"=",
"v",
"return",
"rv"
] |
Return the ``attrs`` attribute values of *inst* as a dict.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the
value as the second argument.
:param callable dict_factory: A callable to produce dictionaries from. For
example, to produce ordered dictionaries instead of normal Python
dictionaries, pass in ``collections.OrderedDict``.
:param bool retain_collection_types: Do not convert to ``list`` when
encountering an attribute whose type is ``tuple`` or ``set``. Only
meaningful if ``recurse`` is ``True``.
:rtype: return type of *dict_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.0.0 *dict_factory*
.. versionadded:: 16.1.0 *retain_collection_types*
|
[
"Return",
"the",
"attrs",
"attribute",
"values",
"of",
"*",
"inst",
"*",
"as",
"a",
"dict",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_funcs.py#L10-L82
|
train
|
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
|
train
|
pypa/pipenv
|
pipenv/vendor/attr/_funcs.py
|
astuple
|
def astuple(
inst,
recurse=True,
filter=None,
tuple_factory=tuple,
retain_collection_types=False,
):
"""
Return the ``attrs`` attribute values of *inst* as a tuple.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the
value as the second argument.
:param callable tuple_factory: A callable to produce tuples from. For
example, to produce lists instead of tuples.
:param bool retain_collection_types: Do not convert to ``list``
or ``dict`` when encountering an attribute which type is
``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is
``True``.
:rtype: return type of *tuple_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.2.0
"""
attrs = fields(inst.__class__)
rv = []
retain = retain_collection_types # Very long. :/
for a in attrs:
v = getattr(inst, a.name)
if filter is not None and not filter(a, v):
continue
if recurse is True:
if has(v.__class__):
rv.append(
astuple(
v,
recurse=True,
filter=filter,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
)
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain is True else list
rv.append(
cf(
[
astuple(
j,
recurse=True,
filter=filter,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
if has(j.__class__)
else j
for j in v
]
)
)
elif isinstance(v, dict):
df = v.__class__ if retain is True else dict
rv.append(
df(
(
astuple(
kk,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
if has(kk.__class__)
else kk,
astuple(
vv,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
if has(vv.__class__)
else vv,
)
for kk, vv in iteritems(v)
)
)
else:
rv.append(v)
else:
rv.append(v)
return rv if tuple_factory is list else tuple_factory(rv)
|
python
|
def astuple(
inst,
recurse=True,
filter=None,
tuple_factory=tuple,
retain_collection_types=False,
):
"""
Return the ``attrs`` attribute values of *inst* as a tuple.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the
value as the second argument.
:param callable tuple_factory: A callable to produce tuples from. For
example, to produce lists instead of tuples.
:param bool retain_collection_types: Do not convert to ``list``
or ``dict`` when encountering an attribute which type is
``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is
``True``.
:rtype: return type of *tuple_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.2.0
"""
attrs = fields(inst.__class__)
rv = []
retain = retain_collection_types # Very long. :/
for a in attrs:
v = getattr(inst, a.name)
if filter is not None and not filter(a, v):
continue
if recurse is True:
if has(v.__class__):
rv.append(
astuple(
v,
recurse=True,
filter=filter,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
)
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain is True else list
rv.append(
cf(
[
astuple(
j,
recurse=True,
filter=filter,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
if has(j.__class__)
else j
for j in v
]
)
)
elif isinstance(v, dict):
df = v.__class__ if retain is True else dict
rv.append(
df(
(
astuple(
kk,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
if has(kk.__class__)
else kk,
astuple(
vv,
tuple_factory=tuple_factory,
retain_collection_types=retain,
)
if has(vv.__class__)
else vv,
)
for kk, vv in iteritems(v)
)
)
else:
rv.append(v)
else:
rv.append(v)
return rv if tuple_factory is list else tuple_factory(rv)
|
[
"def",
"astuple",
"(",
"inst",
",",
"recurse",
"=",
"True",
",",
"filter",
"=",
"None",
",",
"tuple_factory",
"=",
"tuple",
",",
"retain_collection_types",
"=",
"False",
",",
")",
":",
"attrs",
"=",
"fields",
"(",
"inst",
".",
"__class__",
")",
"rv",
"=",
"[",
"]",
"retain",
"=",
"retain_collection_types",
"# Very long. :/",
"for",
"a",
"in",
"attrs",
":",
"v",
"=",
"getattr",
"(",
"inst",
",",
"a",
".",
"name",
")",
"if",
"filter",
"is",
"not",
"None",
"and",
"not",
"filter",
"(",
"a",
",",
"v",
")",
":",
"continue",
"if",
"recurse",
"is",
"True",
":",
"if",
"has",
"(",
"v",
".",
"__class__",
")",
":",
"rv",
".",
"append",
"(",
"astuple",
"(",
"v",
",",
"recurse",
"=",
"True",
",",
"filter",
"=",
"filter",
",",
"tuple_factory",
"=",
"tuple_factory",
",",
"retain_collection_types",
"=",
"retain",
",",
")",
")",
"elif",
"isinstance",
"(",
"v",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"cf",
"=",
"v",
".",
"__class__",
"if",
"retain",
"is",
"True",
"else",
"list",
"rv",
".",
"append",
"(",
"cf",
"(",
"[",
"astuple",
"(",
"j",
",",
"recurse",
"=",
"True",
",",
"filter",
"=",
"filter",
",",
"tuple_factory",
"=",
"tuple_factory",
",",
"retain_collection_types",
"=",
"retain",
",",
")",
"if",
"has",
"(",
"j",
".",
"__class__",
")",
"else",
"j",
"for",
"j",
"in",
"v",
"]",
")",
")",
"elif",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"df",
"=",
"v",
".",
"__class__",
"if",
"retain",
"is",
"True",
"else",
"dict",
"rv",
".",
"append",
"(",
"df",
"(",
"(",
"astuple",
"(",
"kk",
",",
"tuple_factory",
"=",
"tuple_factory",
",",
"retain_collection_types",
"=",
"retain",
",",
")",
"if",
"has",
"(",
"kk",
".",
"__class__",
")",
"else",
"kk",
",",
"astuple",
"(",
"vv",
",",
"tuple_factory",
"=",
"tuple_factory",
",",
"retain_collection_types",
"=",
"retain",
",",
")",
"if",
"has",
"(",
"vv",
".",
"__class__",
")",
"else",
"vv",
",",
")",
"for",
"kk",
",",
"vv",
"in",
"iteritems",
"(",
"v",
")",
")",
")",
"else",
":",
"rv",
".",
"append",
"(",
"v",
")",
"else",
":",
"rv",
".",
"append",
"(",
"v",
")",
"return",
"rv",
"if",
"tuple_factory",
"is",
"list",
"else",
"tuple_factory",
"(",
"rv",
")"
] |
Return the ``attrs`` attribute values of *inst* as a tuple.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines whether an
attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the
value as the second argument.
:param callable tuple_factory: A callable to produce tuples from. For
example, to produce lists instead of tuples.
:param bool retain_collection_types: Do not convert to ``list``
or ``dict`` when encountering an attribute which type is
``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is
``True``.
:rtype: return type of *tuple_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.2.0
|
[
"Return",
"the",
"attrs",
"attribute",
"values",
"of",
"*",
"inst",
"*",
"as",
"a",
"tuple",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_funcs.py#L116-L212
|
train
|
pypa/pipenv
|
pipenv/vendor/attr/_funcs.py
|
assoc
|
def assoc(inst, **changes):
"""
Copy *inst* and apply *changes*.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't
be found on *cls*.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. deprecated:: 17.1.0
Use :func:`evolve` instead.
"""
import warnings
warnings.warn(
"assoc is deprecated and will be removed after 2018/01.",
DeprecationWarning,
stacklevel=2,
)
new = copy.copy(inst)
attrs = fields(inst.__class__)
for k, v in iteritems(changes):
a = getattr(attrs, k, NOTHING)
if a is NOTHING:
raise AttrsAttributeNotFoundError(
"{k} is not an attrs attribute on {cl}.".format(
k=k, cl=new.__class__
)
)
_obj_setattr(new, k, v)
return new
|
python
|
def assoc(inst, **changes):
"""
Copy *inst* and apply *changes*.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't
be found on *cls*.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. deprecated:: 17.1.0
Use :func:`evolve` instead.
"""
import warnings
warnings.warn(
"assoc is deprecated and will be removed after 2018/01.",
DeprecationWarning,
stacklevel=2,
)
new = copy.copy(inst)
attrs = fields(inst.__class__)
for k, v in iteritems(changes):
a = getattr(attrs, k, NOTHING)
if a is NOTHING:
raise AttrsAttributeNotFoundError(
"{k} is not an attrs attribute on {cl}.".format(
k=k, cl=new.__class__
)
)
_obj_setattr(new, k, v)
return new
|
[
"def",
"assoc",
"(",
"inst",
",",
"*",
"*",
"changes",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"assoc is deprecated and will be removed after 2018/01.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"new",
"=",
"copy",
".",
"copy",
"(",
"inst",
")",
"attrs",
"=",
"fields",
"(",
"inst",
".",
"__class__",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"changes",
")",
":",
"a",
"=",
"getattr",
"(",
"attrs",
",",
"k",
",",
"NOTHING",
")",
"if",
"a",
"is",
"NOTHING",
":",
"raise",
"AttrsAttributeNotFoundError",
"(",
"\"{k} is not an attrs attribute on {cl}.\"",
".",
"format",
"(",
"k",
"=",
"k",
",",
"cl",
"=",
"new",
".",
"__class__",
")",
")",
"_obj_setattr",
"(",
"new",
",",
"k",
",",
"v",
")",
"return",
"new"
] |
Copy *inst* and apply *changes*.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't
be found on *cls*.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. deprecated:: 17.1.0
Use :func:`evolve` instead.
|
[
"Copy",
"*",
"inst",
"*",
"and",
"apply",
"*",
"changes",
"*",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_funcs.py#L227-L262
|
train
|
pypa/pipenv
|
pipenv/vendor/attr/_funcs.py
|
evolve
|
def evolve(inst, **changes):
"""
Create a new instance, based on *inst* with *changes* applied.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise TypeError: If *attr_name* couldn't be found in the class
``__init__``.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 17.1.0
"""
cls = inst.__class__
attrs = fields(cls)
for a in attrs:
if not a.init:
continue
attr_name = a.name # To deal with private attributes.
init_name = attr_name if attr_name[0] != "_" else attr_name[1:]
if init_name not in changes:
changes[init_name] = getattr(inst, attr_name)
return cls(**changes)
|
python
|
def evolve(inst, **changes):
"""
Create a new instance, based on *inst* with *changes* applied.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise TypeError: If *attr_name* couldn't be found in the class
``__init__``.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 17.1.0
"""
cls = inst.__class__
attrs = fields(cls)
for a in attrs:
if not a.init:
continue
attr_name = a.name # To deal with private attributes.
init_name = attr_name if attr_name[0] != "_" else attr_name[1:]
if init_name not in changes:
changes[init_name] = getattr(inst, attr_name)
return cls(**changes)
|
[
"def",
"evolve",
"(",
"inst",
",",
"*",
"*",
"changes",
")",
":",
"cls",
"=",
"inst",
".",
"__class__",
"attrs",
"=",
"fields",
"(",
"cls",
")",
"for",
"a",
"in",
"attrs",
":",
"if",
"not",
"a",
".",
"init",
":",
"continue",
"attr_name",
"=",
"a",
".",
"name",
"# To deal with private attributes.",
"init_name",
"=",
"attr_name",
"if",
"attr_name",
"[",
"0",
"]",
"!=",
"\"_\"",
"else",
"attr_name",
"[",
"1",
":",
"]",
"if",
"init_name",
"not",
"in",
"changes",
":",
"changes",
"[",
"init_name",
"]",
"=",
"getattr",
"(",
"inst",
",",
"attr_name",
")",
"return",
"cls",
"(",
"*",
"*",
"changes",
")"
] |
Create a new instance, based on *inst* with *changes* applied.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise TypeError: If *attr_name* couldn't be found in the class
``__init__``.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 17.1.0
|
[
"Create",
"a",
"new",
"instance",
"based",
"on",
"*",
"inst",
"*",
"with",
"*",
"changes",
"*",
"applied",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_funcs.py#L265-L290
|
train
|
pypa/pipenv
|
pipenv/vendor/yarg/client.py
|
get
|
def get(package_name, pypi_server="https://pypi.python.org/pypi/"):
"""
Constructs a request to the PyPI server and returns a
:class:`yarg.package.Package`.
:param package_name: case sensitive name of the package on the PyPI server.
:param pypi_server: (option) URL to the PyPI server.
>>> import yarg
>>> package = yarg.get('yarg')
<Package yarg>
"""
if not pypi_server.endswith("/"):
pypi_server = pypi_server + "/"
response = requests.get("{0}{1}/json".format(pypi_server,
package_name))
if response.status_code >= 300:
raise HTTPError(status_code=response.status_code,
reason=response.reason)
if hasattr(response.content, 'decode'):
return json2package(response.content.decode())
else:
return json2package(response.content)
|
python
|
def get(package_name, pypi_server="https://pypi.python.org/pypi/"):
"""
Constructs a request to the PyPI server and returns a
:class:`yarg.package.Package`.
:param package_name: case sensitive name of the package on the PyPI server.
:param pypi_server: (option) URL to the PyPI server.
>>> import yarg
>>> package = yarg.get('yarg')
<Package yarg>
"""
if not pypi_server.endswith("/"):
pypi_server = pypi_server + "/"
response = requests.get("{0}{1}/json".format(pypi_server,
package_name))
if response.status_code >= 300:
raise HTTPError(status_code=response.status_code,
reason=response.reason)
if hasattr(response.content, 'decode'):
return json2package(response.content.decode())
else:
return json2package(response.content)
|
[
"def",
"get",
"(",
"package_name",
",",
"pypi_server",
"=",
"\"https://pypi.python.org/pypi/\"",
")",
":",
"if",
"not",
"pypi_server",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"pypi_server",
"=",
"pypi_server",
"+",
"\"/\"",
"response",
"=",
"requests",
".",
"get",
"(",
"\"{0}{1}/json\"",
".",
"format",
"(",
"pypi_server",
",",
"package_name",
")",
")",
"if",
"response",
".",
"status_code",
">=",
"300",
":",
"raise",
"HTTPError",
"(",
"status_code",
"=",
"response",
".",
"status_code",
",",
"reason",
"=",
"response",
".",
"reason",
")",
"if",
"hasattr",
"(",
"response",
".",
"content",
",",
"'decode'",
")",
":",
"return",
"json2package",
"(",
"response",
".",
"content",
".",
"decode",
"(",
")",
")",
"else",
":",
"return",
"json2package",
"(",
"response",
".",
"content",
")"
] |
Constructs a request to the PyPI server and returns a
:class:`yarg.package.Package`.
:param package_name: case sensitive name of the package on the PyPI server.
:param pypi_server: (option) URL to the PyPI server.
>>> import yarg
>>> package = yarg.get('yarg')
<Package yarg>
|
[
"Constructs",
"a",
"request",
"to",
"the",
"PyPI",
"server",
"and",
"returns",
"a",
":",
"class",
":",
"yarg",
".",
"package",
".",
"Package",
"."
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/yarg/client.py#L32-L54
|
train
|
pypa/pipenv
|
pipenv/vendor/click/_bashcomplete.py
|
resolve_ctx
|
def resolve_ctx(cli, prog_name, args):
"""
Parse into a hierarchy of contexts. Contexts are connected through the parent variable.
:param cli: command definition
:param prog_name: the program that is running
:param args: full list of args
:return: the final context/command parsed
"""
ctx = cli.make_context(prog_name, args, resilient_parsing=True)
args = ctx.protected_args + ctx.args
while args:
if isinstance(ctx.command, MultiCommand):
if not ctx.command.chain:
cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
if cmd is None:
return ctx
ctx = cmd.make_context(cmd_name, args, parent=ctx,
resilient_parsing=True)
args = ctx.protected_args + ctx.args
else:
# Walk chained subcommand contexts saving the last one.
while args:
cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
if cmd is None:
return ctx
sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,
allow_extra_args=True,
allow_interspersed_args=False,
resilient_parsing=True)
args = sub_ctx.args
ctx = sub_ctx
args = sub_ctx.protected_args + sub_ctx.args
else:
break
return ctx
|
python
|
def resolve_ctx(cli, prog_name, args):
"""
Parse into a hierarchy of contexts. Contexts are connected through the parent variable.
:param cli: command definition
:param prog_name: the program that is running
:param args: full list of args
:return: the final context/command parsed
"""
ctx = cli.make_context(prog_name, args, resilient_parsing=True)
args = ctx.protected_args + ctx.args
while args:
if isinstance(ctx.command, MultiCommand):
if not ctx.command.chain:
cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
if cmd is None:
return ctx
ctx = cmd.make_context(cmd_name, args, parent=ctx,
resilient_parsing=True)
args = ctx.protected_args + ctx.args
else:
# Walk chained subcommand contexts saving the last one.
while args:
cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)
if cmd is None:
return ctx
sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,
allow_extra_args=True,
allow_interspersed_args=False,
resilient_parsing=True)
args = sub_ctx.args
ctx = sub_ctx
args = sub_ctx.protected_args + sub_ctx.args
else:
break
return ctx
|
[
"def",
"resolve_ctx",
"(",
"cli",
",",
"prog_name",
",",
"args",
")",
":",
"ctx",
"=",
"cli",
".",
"make_context",
"(",
"prog_name",
",",
"args",
",",
"resilient_parsing",
"=",
"True",
")",
"args",
"=",
"ctx",
".",
"protected_args",
"+",
"ctx",
".",
"args",
"while",
"args",
":",
"if",
"isinstance",
"(",
"ctx",
".",
"command",
",",
"MultiCommand",
")",
":",
"if",
"not",
"ctx",
".",
"command",
".",
"chain",
":",
"cmd_name",
",",
"cmd",
",",
"args",
"=",
"ctx",
".",
"command",
".",
"resolve_command",
"(",
"ctx",
",",
"args",
")",
"if",
"cmd",
"is",
"None",
":",
"return",
"ctx",
"ctx",
"=",
"cmd",
".",
"make_context",
"(",
"cmd_name",
",",
"args",
",",
"parent",
"=",
"ctx",
",",
"resilient_parsing",
"=",
"True",
")",
"args",
"=",
"ctx",
".",
"protected_args",
"+",
"ctx",
".",
"args",
"else",
":",
"# Walk chained subcommand contexts saving the last one.",
"while",
"args",
":",
"cmd_name",
",",
"cmd",
",",
"args",
"=",
"ctx",
".",
"command",
".",
"resolve_command",
"(",
"ctx",
",",
"args",
")",
"if",
"cmd",
"is",
"None",
":",
"return",
"ctx",
"sub_ctx",
"=",
"cmd",
".",
"make_context",
"(",
"cmd_name",
",",
"args",
",",
"parent",
"=",
"ctx",
",",
"allow_extra_args",
"=",
"True",
",",
"allow_interspersed_args",
"=",
"False",
",",
"resilient_parsing",
"=",
"True",
")",
"args",
"=",
"sub_ctx",
".",
"args",
"ctx",
"=",
"sub_ctx",
"args",
"=",
"sub_ctx",
".",
"protected_args",
"+",
"sub_ctx",
".",
"args",
"else",
":",
"break",
"return",
"ctx"
] |
Parse into a hierarchy of contexts. Contexts are connected through the parent variable.
:param cli: command definition
:param prog_name: the program that is running
:param args: full list of args
:return: the final context/command parsed
|
[
"Parse",
"into",
"a",
"hierarchy",
"of",
"contexts",
".",
"Contexts",
"are",
"connected",
"through",
"the",
"parent",
"variable",
".",
":",
"param",
"cli",
":",
"command",
"definition",
":",
"param",
"prog_name",
":",
"the",
"program",
"that",
"is",
"running",
":",
"param",
"args",
":",
"full",
"list",
"of",
"args",
":",
"return",
":",
"the",
"final",
"context",
"/",
"command",
"parsed"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_bashcomplete.py#L85-L119
|
train
|
pypa/pipenv
|
pipenv/vendor/click/_bashcomplete.py
|
is_incomplete_option
|
def is_incomplete_option(all_args, cmd_param):
"""
:param all_args: the full original list of args supplied
:param cmd_param: the current command paramter
:return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and
corresponds to this cmd_param. In other words whether this cmd_param option can still accept
values
"""
if not isinstance(cmd_param, Option):
return False
if cmd_param.is_flag:
return False
last_option = None
for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):
if index + 1 > cmd_param.nargs:
break
if start_of_option(arg_str):
last_option = arg_str
return True if last_option and last_option in cmd_param.opts else False
|
python
|
def is_incomplete_option(all_args, cmd_param):
"""
:param all_args: the full original list of args supplied
:param cmd_param: the current command paramter
:return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and
corresponds to this cmd_param. In other words whether this cmd_param option can still accept
values
"""
if not isinstance(cmd_param, Option):
return False
if cmd_param.is_flag:
return False
last_option = None
for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):
if index + 1 > cmd_param.nargs:
break
if start_of_option(arg_str):
last_option = arg_str
return True if last_option and last_option in cmd_param.opts else False
|
[
"def",
"is_incomplete_option",
"(",
"all_args",
",",
"cmd_param",
")",
":",
"if",
"not",
"isinstance",
"(",
"cmd_param",
",",
"Option",
")",
":",
"return",
"False",
"if",
"cmd_param",
".",
"is_flag",
":",
"return",
"False",
"last_option",
"=",
"None",
"for",
"index",
",",
"arg_str",
"in",
"enumerate",
"(",
"reversed",
"(",
"[",
"arg",
"for",
"arg",
"in",
"all_args",
"if",
"arg",
"!=",
"WORDBREAK",
"]",
")",
")",
":",
"if",
"index",
"+",
"1",
">",
"cmd_param",
".",
"nargs",
":",
"break",
"if",
"start_of_option",
"(",
"arg_str",
")",
":",
"last_option",
"=",
"arg_str",
"return",
"True",
"if",
"last_option",
"and",
"last_option",
"in",
"cmd_param",
".",
"opts",
"else",
"False"
] |
:param all_args: the full original list of args supplied
:param cmd_param: the current command paramter
:return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and
corresponds to this cmd_param. In other words whether this cmd_param option can still accept
values
|
[
":",
"param",
"all_args",
":",
"the",
"full",
"original",
"list",
"of",
"args",
"supplied",
":",
"param",
"cmd_param",
":",
"the",
"current",
"command",
"paramter",
":",
"return",
":",
"whether",
"or",
"not",
"the",
"last",
"option",
"declaration",
"(",
"i",
".",
"e",
".",
"starts",
"-",
"or",
"--",
")",
"is",
"incomplete",
"and",
"corresponds",
"to",
"this",
"cmd_param",
".",
"In",
"other",
"words",
"whether",
"this",
"cmd_param",
"option",
"can",
"still",
"accept",
"values"
] |
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_bashcomplete.py#L130-L149
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.