Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def sys_version(version_tuple):
old_version = sys.version_info
sys.version_info = version_tuple
yield
sys.version_info = old_version | [
"\n Set a temporary sys.version_info tuple\n\n :param version_tuple: a fake sys.version_info tuple\n "
] |
Please provide a description of the function:def add_to_set(original_set, element):
if not element:
return original_set
if isinstance(element, Set):
original_set |= element
elif isinstance(element, (list, tuple)):
original_set |= set(element)
else:
original_set.add(e... | [
"Given a set and some arbitrary element, add the element(s) to the set"
] |
Please provide a description of the function:def is_url_equal(url, other_url):
# type: (str, str) -> bool
if not isinstance(url, six.string_types):
raise TypeError("Expected string for url, received {0!r}".format(url))
if not isinstance(other_url, six.string_types):
raise TypeError("Exp... | [
"\n Compare two urls by scheme, host, and path, ignoring auth\n\n :param str url: The initial URL to compare\n :param str url: Second url to compare to the first\n :return: Whether the URLs are equal without **auth**, **query**, and **fragment**\n :rtype: bool\n\n >>> is_url_equal(\"https://user:p... |
Please provide a description of the function:def make_posix(path):
# type: (str) -> str
if not isinstance(path, six.string_types):
raise TypeError("Expected a string for path, received {0!r}...".format(path))
starts_with_sep = path.startswith(os.path.sep)
separated = normalize_path(path).sp... | [
"\n Convert a path with possible windows-style separators to a posix-style path\n (with **/** separators instead of **\\\\** separators).\n\n :param Text path: A path to convert.\n :return: A converted posix-style path\n :rtype: Text\n\n >>> make_posix(\"c:/users/user/venvs/some_venv\\\\Lib\\\\sit... |
Please provide a description of the function:def find_python(finder, line=None):
if line and not isinstance(line, six.string_types):
raise TypeError(
"Invalid python search type: expected string, received {0!r}".format(line)
)
if line and os.path.isabs(line):
if os.name... | [
"\n Given a `pythonfinder.Finder` instance and an optional line, find a corresponding python\n\n :param finder: A :class:`pythonfinder.Finder` instance to use for searching\n :type finder: :class:pythonfinder.Finder`\n :param str line: A version, path, name, or nothing, defaults to None\n :return: A ... |
Please provide a description of the function:def is_python_command(line):
if not isinstance(line, six.string_types):
raise TypeError("Not a valid command to check: {0!r}".format(line))
from pipenv.vendor.pythonfinder.utils import PYTHON_IMPLEMENTATIONS
is_version = re.match(r'[\d\.]+', line)
... | [
"\n Given an input, checks whether the input is a request for python or notself.\n\n This can be a version, a python runtime name, or a generic 'python' or 'pythonX.Y'\n\n :param str line: A potential request to find python\n :returns: Whether the line is a python lookup\n :rtype: bool\n "
] |
Please provide a description of the function:def get_hash(self, ireq, ireq_hashes=None):
# We _ALWAYS MUST PRIORITIZE_ the inclusion of hashes from local sources
# PLEASE *DO NOT MODIFY THIS* TO CHECK WHETHER AN IREQ ALREADY HAS A HASH
# RESOLVED. The resolver will pull hashes from PyP... | [
"\n Retrieve hashes for a specific ``InstallRequirement`` instance.\n\n :param ireq: An ``InstallRequirement`` to retrieve hashes for\n :type ireq: :class:`~pip_shims.InstallRequirement`\n :return: A set of hashes.\n :rtype: Set\n "
] |
Please provide a description of the function:def _get_process_mapping():
for impl in (proc, ps):
try:
mapping = impl.get_process_mapping()
except EnvironmentError:
continue
return mapping
raise ShellDetectionFailure('compatible proc fs or ps utility is requir... | [
"Select a way to obtain process information from the system.\n\n * `/proc` is used if supported.\n * The system `ps` utility is used as a fallback option.\n "
] |
Please provide a description of the function:def _iter_process_command(mapping, pid, max_depth):
for _ in range(max_depth):
try:
proc = mapping[pid]
except KeyError: # We've reached the root process. Give up.
break
try:
cmd = proc.args[0]
e... | [
"Iterator to traverse up the tree, yielding `argv[0]` of each process.\n "
] |
Please provide a description of the function:def _get_login_shell(proc_cmd):
login_shell = os.environ.get('SHELL', '')
if login_shell:
proc_cmd = login_shell
else:
proc_cmd = proc_cmd[1:]
return (os.path.basename(proc_cmd).lower(), proc_cmd) | [
"Form shell information from the SHELL environment variable if possible.\n "
] |
Please provide a description of the function:def get_shell(pid=None, max_depth=6):
pid = str(pid or os.getpid())
mapping = _get_process_mapping()
for proc_cmd in _iter_process_command(mapping, pid, max_depth):
if proc_cmd.startswith('-'): # Login shell! Let's use this.
return _ge... | [
"Get the shell that the supplied pid or os.getpid() is running in.\n "
] |
Please provide a description of the function:def send(self, request, stream=False, timeout=None, verify=True,
cert=None, proxies=None):
raise NotImplementedError | [
"Sends PreparedRequest object. Returns Response object.\n\n :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n :param stream: (optional) Whether to stream the request content.\n :param timeout: (optional) How long to wait for the server to send\n data before... |
Please provide a description of the function:def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolma... | [
"Initializes a urllib3 PoolManager.\n\n This method should not be called from user code, and is only\n exposed for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param connections: The number of urllib3 connection pools to cache.\n :param max... |
Please provide a description of the function:def proxy_manager_for(self, proxy, **proxy_kwargs):
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
elif proxy.lower().startswith('socks'):
username, password = get_auth_from_url(proxy)
manager ... | [
"Return urllib3 ProxyManager for the given proxy.\n\n This method should not be called from user code, and is only\n exposed for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param proxy: The proxy to return a urllib3 ProxyManager for.\n :pa... |
Please provide a description of the function:def build_response(self, req, resp):
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.hea... | [
"Builds a :class:`Response <requests.Response>` object from a urllib3\n response. This should not be called from user code, and is only exposed\n for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n :param req: The :class:`PreparedRequest <PreparedReque... |
Please provide a description of the function:def get_connection(self, url, proxies=None):
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise I... | [
"Returns a urllib3 connection for the given URL. This should not be\n called from user code, and is only exposed for use when subclassing the\n :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n :param url: The URL to connect to.\n :param proxies: (optional) A Requests-style dicti... |
Please provide a description of the function:def close(self):
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear() | [
"Disposes of any internal state.\n\n Currently, this closes the PoolManager and any active ProxyManager,\n which closes any pooled connections.\n "
] |
Please provide a description of the function:def request_url(self, request, proxies):
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
is_proxied_http_request = (proxy and scheme != 'https')
using_socks_proxy = False
if proxy:
... | [
"Obtain the url to use when making the final request.\n\n If the message is being sent through a HTTP proxy, the full URL has to\n be used. Otherwise, we should only use the path portion of the URL.\n\n This should not be called from user code, and is only exposed for use\n when subclass... |
Please provide a description of the function:def strip_ssh_from_git_uri(uri):
# type: (S) -> S
if isinstance(uri, six.string_types):
if "git+ssh://" in uri:
parsed = urlparse(uri)
# split the path on the first separating / so we can put the first segment
# into t... | [
"Return git+ssh:// formatted URI to git+git@ format"
] |
Please provide a description of the function:def add_ssh_scheme_to_git_uri(uri):
# type: (S) -> S
if isinstance(uri, six.string_types):
# Add scheme for parsing purposes, this is also what pip does
if uri.startswith("git+") and "://" not in uri:
uri = uri.replace("git+", "git+ss... | [
"Cleans VCS uris from pipenv.patched.notpip format"
] |
Please provide a description of the function:def is_vcs(pipfile_entry):
# type: (PipfileType) -> bool
if isinstance(pipfile_entry, Mapping):
return any(key for key in pipfile_entry.keys() if key in VCS_LIST)
elif isinstance(pipfile_entry, six.string_types):
if not is_valid_url(pipfile_... | [
"Determine if dictionary entry from Pipfile is for a vcs dependency."
] |
Please provide a description of the function:def multi_split(s, split):
# type: (S, Iterable[S]) -> List[S]
for r in split:
s = s.replace(r, "|")
return [i for i in s.split("|") if len(i) > 0] | [
"Splits on multiple given separators."
] |
Please provide a description of the function:def convert_entry_to_path(path):
# type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S
if not isinstance(path, Mapping):
raise TypeError("expecting a mapping, received {0!r}".format(path))
if not any(key in path for key in ["file", "path"]):
... | [
"Convert a pipfile entry to a string"
] |
Please provide a description of the function:def is_installable_file(path):
# type: (PipfileType) -> bool
from packaging import specifiers
if isinstance(path, Mapping):
path = convert_entry_to_path(path)
# If the string starts with a valid specifier operator, test if it is a valid
# s... | [
"Determine if a path can potentially be installed"
] |
Please provide a description of the function:def get_path(root, path, default=_UNSET):
if isinstance(path, six.string_types):
path = path.split(".")
cur = root
try:
for seg in path:
try:
cur = cur[seg]
except (KeyError, IndexError) as exc:
... | [
"Retrieve a value from a nested object via a tuple representing the\n lookup path.\n >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}\n >>> get_path(root, ('a', 'b', 'c', 2, 0))\n 3\n The path format is intentionally consistent with that of\n :func:`remap`.\n One of get_path's chief aims is impr... |
Please provide a description of the function:def _hash_comparison(self):
def hash_then_or(hash_name):
# For now, all the decent hashes have 6-char names, so we can get
# away with hard-coding space literals.
return chain([hash_name], repeat(' or'))
lines ... | [
"\n Return a comparison of actual and expected hash values.\n\n Example::\n\n Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n or 123451234512345123451234512345123451234512345\n Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcd... |
Please provide a description of the function:def reset(self):
self.result = {'encoding': None, 'confidence': 0.0, 'language': None}
self.done = False
self._got_data = False
self._has_win_bytes = False
self._input_state = InputState.PURE_ASCII
self._last_char = b'... | [
"\n Reset the UniversalDetector and all of its probers back to their\n initial states. This is called by ``__init__``, so you only need to\n call this directly in between analyses of different documents.\n "
] |
Please provide a description of the function:def feed(self, byte_str):
if self.done:
return
if not len(byte_str):
return
if not isinstance(byte_str, bytearray):
byte_str = bytearray(byte_str)
# First check for known BOMs, since these are gu... | [
"\n Takes a chunk of a document and feeds it through all of the relevant\n charset probers.\n\n After calling ``feed``, you can check the value of the ``done``\n attribute to see if you need to continue feeding the\n ``UniversalDetector`` more data, or if it has made a prediction\... |
Please provide a description of the function:def close(self):
# Don't bother with checks if we're already done
if self.done:
return self.result
self.done = True
if not self._got_data:
self.logger.debug('no data received!')
# Default to ASCII if ... | [
"\n Stop analyzing the current document and come up with a final\n prediction.\n\n :returns: The ``result`` attribute, a ``dict`` with the keys\n `encoding`, `confidence`, and `language`.\n "
] |
Please provide a description of the function:def bash(command="bash"):
bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh')
child = pexpect.spawn(command, ['--rcfile', bashrc], echo=False,
encoding='utf-8')
# If the user runs 'env', the value of PS1 will be in the ou... | [
"Start a bash shell and return a :class:`REPLWrapper` object."
] |
Please provide a description of the function:def run_command(self, command, timeout=-1):
# Split up multiline commands and feed them in bit-by-bit
cmdlines = command.splitlines()
# splitlines ignores trailing newlines - add it back in manually
if command.endswith('\n'):
... | [
"Send a command to the REPL, wait for and return output.\n\n :param str command: The command to send. Trailing newlines are not needed.\n This should be a complete block of input that will trigger execution;\n if a continuation prompt is found after sending input, :exc:`ValueError`\n ... |
Please provide a description of the function:def parse_hashes(self):
# type: () -> None
line, hashes = self.split_hashes(self.line)
self.hashes = hashes
self.line = line | [
"\n Parse hashes from *self.line* and set them on the current object.\n :returns: Nothing\n :rtype: None\n "
] |
Please provide a description of the function:def parse_extras(self):
# type: () -> None
extras = None
if "@" in self.line or self.is_vcs or self.is_url:
line = "{0}".format(self.line)
uri = URI.parse(line)
name = uri.name
if name:
... | [
"\n Parse extras from *self.line* and set them on the current object\n :returns: Nothing\n :rtype: None\n "
] |
Please provide a description of the function:def get_url(self):
# type: () -> STRING_TYPE
line = self.line
try:
parsed = URI.parse(line)
line = parsed.to_string(escape_password=False, direct=False, strip_ref=True)
except ValueError:
pass
... | [
"Sets ``self.name`` if given a **PEP-508** style URL"
] |
Please provide a description of the function:def requirement_info(self):
# type: () -> Tuple[Optional[S], Tuple[Optional[S], ...], Optional[S]]
# Direct URLs can be converted to packaging requirements directly, but
# only if they are `file://` (with only two slashes)
name = Non... | [
"\n Generates a 3-tuple of the requisite *name*, *extras* and *url* to generate a\n :class:`~packaging.requirements.Requirement` out of.\n\n :return: A Tuple of an optional name, a Tuple of extras, and an optional URL.\n :rtype: Tuple[Optional[S], Tuple[Optional[S], ...], Optional[S]]\n ... |
Please provide a description of the function:def line_is_installable(self):
# type: () -> bool
line = self.line
if is_file_url(line):
link = create_link(line)
line = link.url_without_fragment
line, _ = split_ref_from_uri(line)
if (
... | [
"\n This is a safeguard against decoy requirements when a user installs a package\n whose name coincides with the name of a folder in the cwd, e.g. install *alembic*\n when there is a folder called *alembic* in the working directory.\n\n In this case we first need to check that the given... |
Please provide a description of the function:def fork_pty():
'''This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
res... | [] |
Please provide a description of the function:def safecall(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper | [
"Wraps a function so that it swallows exceptions."
] |
Please provide a description of the function:def make_str(value):
if isinstance(value, bytes):
try:
return value.decode(get_filesystem_encoding())
except UnicodeError:
return value.decode('utf-8', 'replace')
return text_type(value) | [
"Converts a value into a valid string."
] |
Please provide a description of the function:def make_default_short_help(help, max_length=45):
words = help.split()
total_length = 0
result = []
done = False
for word in words:
if word[-1:] == '.':
done = True
new_length = result and 1 + len(word) or len(word)
... | [
"Return a condensed version of help string."
] |
Please provide a description of the function:def get_binary_stream(name):
opener = binary_streams.get(name)
if opener is None:
raise TypeError('Unknown standard stream %r' % name)
return opener() | [
"Returns a system stream for byte processing. This essentially\n returns the stream from the sys module with the given name but it\n solves some compatibility issues between different Python versions.\n Primarily this function is necessary for getting binary streams on\n Python 3.\n\n :param name: t... |
Please provide a description of the function:def get_text_stream(name, encoding=None, errors='strict'):
opener = text_streams.get(name)
if opener is None:
raise TypeError('Unknown standard stream %r' % name)
return opener(encoding, errors) | [
"Returns a system stream for text processing. This usually returns\n a wrapped stream around a binary stream returned from\n :func:`get_binary_stream` but it also can take shortcuts on Python 3\n for already correctly configured streams.\n\n :param name: the name of the stream to open. Valid names are... |
Please provide a description of the function:def open_file(filename, mode='r', encoding=None, errors='strict',
lazy=False, atomic=False):
if lazy:
return LazyFile(filename, mode, encoding, errors, atomic=atomic)
f, should_close = open_stream(filename, mode, encoding, errors,
... | [
"This is similar to how the :class:`File` works but for manual\n usage. Files are opened non lazy by default. This can open regular\n files as well as stdin/stdout if ``'-'`` is passed.\n\n If stdin/stdout is returned the stream is wrapped so that the context\n manager will not close the stream accide... |
Please provide a description of the function:def format_filename(filename, shorten=False):
if shorten:
filename = os.path.basename(filename)
return filename_to_ui(filename) | [
"Formats a filename for user display. The main purpose of this\n function is to ensure that the filename can be displayed at all. This\n will decode the filename to unicode if necessary in a way that it will\n not fail. Optionally, it can shorten the filename to not include the\n full path to the fil... |
Please provide a description of the function:def get_app_dir(app_name, roaming=True, force_posix=False):
r
if WIN:
key = roaming and 'APPDATA' or 'LOCALAPPDATA'
folder = os.environ.get(key)
if folder is None:
folder = os.path.expanduser('~')
return os.path.join(folder... | [
"Returns the config folder for the application. The default behavior\n is to return whatever is most appropriate for the operating system.\n\n To give you an idea, for an app called ``\"Foo Bar\"``, something like\n the following folders could be returned:\n\n Mac OS X:\n ``~/Library/Application S... |
Please provide a description of the function:def open(self):
if self._f is not None:
return self._f
try:
rv, self.should_close = open_stream(self.name, self.mode,
self.encoding,
... | [
"Opens the file if it's not yet open. This call might fail with\n a :exc:`FileError`. Not handling this error will produce an error\n that Click shows.\n "
] |
Please provide a description of the function:def split_args(line):
lex = shlex.shlex(line, posix=True)
lex.whitespace_split = True
lex.commenters = ''
res = []
try:
while True:
res.append(next(lex))
except ValueError: # No closing quotation
pass
except StopI... | [
"Version of shlex.split that silently accept incomplete strings.\n\n Parameters\n ----------\n line : str\n The string to split\n\n Returns\n -------\n [str]\n The line split in separated arguments\n "
] |
Please provide a description of the function:def confirm(text, default=False, abort=False, prompt_suffix=': ',
show_default=True, err=False):
prompt = _build_prompt(text, prompt_suffix, show_default,
default and 'Y/n' or 'y/N')
while 1:
try:
# Writ... | [
"Prompts for confirmation (yes/no question).\n\n If the user aborts the input by sending a interrupt signal this\n function will catch it and raise a :exc:`Abort` exception.\n\n .. versionadded:: 4.0\n Added the `err` parameter.\n\n :param text: the question to ask.\n :param default: the defaul... |
Please provide a description of the function:def echo_via_pager(text_or_generator, color=None):
color = resolve_color_default(color)
if inspect.isgeneratorfunction(text_or_generator):
i = text_or_generator()
elif isinstance(text_or_generator, string_types):
i = [text_or_generator]
... | [
"This function takes a text and shows it via an environment specific\n pager on stdout.\n\n .. versionchanged:: 3.0\n Added the `color` flag.\n\n :param text_or_generator: the text to page, or alternatively, a\n generator emitting the text to page.\n :param color: cont... |
Please provide a description of the function:def progressbar(iterable=None, length=None, label=None, show_eta=True,
show_percent=None, show_pos=False,
item_show_func=None, fill_char='#', empty_char='-',
bar_template='%(label)s [%(bar)s] %(info)s',
info_s... | [
"This function creates an iterable context manager that can be used\n to iterate over something while showing a progress bar. It will\n either iterate over the `iterable` or `length` items (that are counted\n up). While iteration happens, this function will print a rendered\n progress bar to the given... |
Please provide a description of the function:def clear():
if not isatty(sys.stdout):
return
# If we're on Windows and we don't have colorama available, then we
# clear the screen by shelling out. Otherwise we can use an escape
# sequence.
if WIN:
os.system('cls')
else:
... | [
"Clears the terminal screen. This will have the effect of clearing\n the whole visible space of the terminal and moving the cursor to the\n top left. This does not do anything if not connected to a terminal.\n\n .. versionadded:: 2.0\n "
] |
Please provide a description of the function:def edit(text=None, editor=None, env=None, require_save=True,
extension='.txt', filename=None):
r
from ._termui_impl import Editor
editor = Editor(editor=editor, env=env, require_save=require_save,
extension=extension)
if filename... | [
"Edits the given text in the defined editor. If an editor is given\n (should be the full path to the executable but the regular operating\n system search path is used for finding the executable) it overrides\n the detected editor. Optionally, some environment variables can be\n used. If the editor is... |
Please provide a description of the function:def launch(url, wait=False, locate=False):
from ._termui_impl import open_url
return open_url(url, wait=wait, locate=locate) | [
"This function launches the given URL (or filename) in the default\n viewer application for this file type. If this is an executable, it\n might launch the executable in a new session. The return value is\n the exit code of the launched application. Usually, ``0`` indicates\n success.\n\n Examples... |
Please provide a description of the function:def getchar(echo=False):
f = _getchar
if f is None:
from ._termui_impl import getchar as f
return f(echo) | [
"Fetches a single character from the terminal and returns it. This\n will always return a unicode character and under certain rare\n circumstances this might return more than one character. The\n situations which more than one character is returned is when for\n whatever reason multiple characters end... |
Please provide a description of the function:def pause(info='Press any key to continue ...', err=False):
if not isatty(sys.stdin) or not isatty(sys.stdout):
return
try:
if info:
echo(info, nl=False, err=err)
try:
getchar()
except (KeyboardInterrupt, E... | [
"This command stops execution and waits for the user to press any\n key to continue. This is similar to the Windows batch \"pause\"\n command. If the program is not run through a terminal, this command\n will instead do nothing.\n\n .. versionadded:: 2.0\n\n .. versionadded:: 4.0\n Added the ... |
Please provide a description of the function:def optional(validator):
if isinstance(validator, list):
return _OptionalValidator(_AndValidator(validator))
return _OptionalValidator(validator) | [
"\n A validator that makes an attribute optional. An optional attribute is one\n which can be set to ``None`` in addition to satisfying the requirements of\n the sub-validator.\n\n :param validator: A validator (or a list of validators) that is used for\n non-``None`` values.\n :type validato... |
Please provide a description of the function:def copy(self):
other = DirectedGraph()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for k, v in self._forwards.items()}
other._backwards = {k: set(v) for k, v in self._backwards.items()}
return other | [
"Return a shallow copy of this graph.\n "
] |
Please provide a description of the function:def add(self, key):
if key in self._vertices:
raise ValueError('vertex exists')
self._vertices.add(key)
self._forwards[key] = set()
self._backwards[key] = set() | [
"Add a new vertex to the graph.\n "
] |
Please provide a description of the function:def remove(self, key):
self._vertices.remove(key)
for f in self._forwards.pop(key):
self._backwards[f].remove(key)
for t in self._backwards.pop(key):
self._forwards[t].remove(key) | [
"Remove a vertex from the graph, disconnecting all edges from/to it.\n "
] |
Please provide a description of the function:def connect(self, f, t):
if t not in self._vertices:
raise KeyError(t)
self._forwards[f].add(t)
self._backwards[t].add(f) | [
"Connect two existing vertices.\n\n Nothing happens if the vertices are already connected.\n "
] |
Please provide a description of the function:def _const_compare_digest_backport(a, b):
result = abs(len(a) - len(b))
for l, r in zip(bytearray(a), bytearray(b)):
result |= l ^ r
return result == 0 | [
"\n Compare two digests of equal length in constant time.\n\n The digests must be of type str/bytes.\n Returns True if the digests match, and False otherwise.\n "
] |
Please provide a description of the function:def assert_fingerprint(cert, fingerprint):
fingerprint = fingerprint.replace(':', '').lower()
digest_length = len(fingerprint)
hashfunc = HASHFUNC_MAP.get(digest_length)
if not hashfunc:
raise SSLError(
'Fingerprint of invalid length... | [
"\n Checks if given fingerprint matches the supplied certificate.\n\n :param cert:\n Certificate as bytes object.\n :param fingerprint:\n Fingerprint as string of hexdigits, can be interspersed by colons.\n "
] |
Please provide a description of the function:def resolve_cert_reqs(candidate):
if candidate is None:
return CERT_NONE
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'CERT_' + candidate)
return res
retur... | [
"\n Resolves the argument to a numeric constant, which can be passed to\n the wrap_socket function/method from the ssl module.\n Defaults to :data:`ssl.CERT_NONE`.\n If given a string it is assumed to be the name of the constant in the\n :mod:`ssl` module or its abbreviation.\n (So you can specify... |
Please provide a description of the function:def resolve_ssl_version(candidate):
if candidate is None:
return PROTOCOL_SSLv23
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return re... | [
"\n like resolve_cert_reqs\n "
] |
Please provide a description of the function:def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None,
ca_cert_dir=None):
context = ssl_context
if ... | [
"\n All arguments except for server_hostname, ssl_context, and ca_cert_dir have\n the same meaning as they do when using :func:`ssl.wrap_socket`.\n\n :param server_hostname:\n When SNI is supported, the expected hostname of the certificate\n :param ssl_context:\n A pre-made :class:`SSLCont... |
Please provide a description of the function:def is_ipaddress(hostname):
if six.PY3 and isinstance(hostname, bytes):
# IDN A-label bytes are ASCII compatible.
hostname = hostname.decode('ascii')
families = [socket.AF_INET]
if hasattr(socket, 'AF_INET6'):
families.append(socket.... | [
"Detects whether the hostname given is an IP address.\n\n :param str hostname: Hostname to examine.\n :return: True if the hostname is an IP address, False otherwise.\n "
] |
Please provide a description of the function:def get_backoff_time(self):
# We want to consider only the last consecutive errors sequence (Ignore redirects).
consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None,
rev... | [
" Formula for computing the current backoff\n\n :rtype: float\n "
] |
Please provide a description of the function:def get_retry_after(self, response):
retry_after = response.getheader("Retry-After")
if retry_after is None:
return None
return self.parse_retry_after(retry_after) | [
" Get the value of Retry-After in seconds. "
] |
Please provide a description of the function:def sleep(self, response=None):
if response:
slept = self.sleep_for_retry(response)
if slept:
return
self._sleep_backoff() | [
" Sleep between retry attempts.\n\n This method will respect a server's ``Retry-After`` response header\n and sleep the duration of the time requested. If that is not present, it\n will use an exponential backoff. By default, the backoff factor is 0 and\n this method will return immediat... |
Please provide a description of the function:def _is_method_retryable(self, method):
if self.method_whitelist and method.upper() not in self.method_whitelist:
return False
return True | [
" Checks if a given HTTP method should be retried upon, depending if\n it is included on the method whitelist.\n "
] |
Please provide a description of the function:def is_retry(self, method, status_code, has_retry_after=False):
if not self._is_method_retryable(method):
return False
if self.status_forcelist and status_code in self.status_forcelist:
return True
return (self.total... | [
" Is this method/status code retryable? (Based on whitelists and control\n variables such as the number of total retries to allow, whether to\n respect the Retry-After header, whether this header is present, and\n whether the returned status code is on the list of status codes to\n be re... |
Please provide a description of the function:def is_exhausted(self):
retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)
retry_counts = list(filter(None, retry_counts))
if not retry_counts:
return False
return min(retry_counts) < 0 | [
" Are we out of retries? "
] |
Please provide a description of the function:def increment(self, method=None, url=None, response=None, error=None,
_pool=None, _stacktrace=None):
if self.total is False and error:
# Disabled, indicate to re-raise the error.
raise six.reraise(type(error), error,... | [
" Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.HTTPResponse`\n :param Exception error: An error encountered during the request, or\n ... |
Please provide a description of the function:def build_response(
self, request, response, from_cache=False, cacheable_methods=None
):
cacheable = cacheable_methods or self.cacheable_methods
if not from_cache and request.method in cacheable:
# Check for any heuristics tha... | [
"\n Build a response by making a request or using the cache.\n\n This will end up calling send and returning a potentially\n cached response\n "
] |
Please provide a description of the function:def get_process_mapping():
with open('/proc/{0}/stat'.format(os.getpid())) as f:
self_tty = f.read().split()[STAT_TTY]
processes = {}
for pid in os.listdir('/proc'):
if not pid.isdigit():
continue
try:
stat = '... | [
"Try to look up the process tree via Linux's /proc\n "
] |
Please provide a description of the function:def rehash(path, blocksize=1 << 20):
# type: (str, int) -> Tuple[str, str]
h = hashlib.sha256()
length = 0
with open(path, 'rb') as f:
for block in read_chunks(f, size=blocksize):
length += len(block)
h.update(block)
d... | [
"Return (hash, length) for path using hashlib.sha256()"
] |
Please provide a description of the function:def replace_python_tag(wheelname, new_tag):
# type: (str, str) -> str
parts = wheelname.split('-')
parts[-3] = new_tag
return '-'.join(parts) | [
"Replace the Python tag in a wheel file name with a new value.\n "
] |
Please provide a description of the function:def message_about_scripts_not_on_PATH(scripts):
# type: (Sequence[str]) -> Optional[str]
if not scripts:
return None
# Group scripts by the path they were installed in
grouped_by_dir = collections.defaultdict(set) # type: Dict[str, set]
for... | [
"Determine if any scripts are not on PATH and format a warning.\n\n Returns a warning message if one or more scripts are not on PATH,\n otherwise None.\n "
] |
Please provide a description of the function:def sorted_outrows(outrows):
# type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow]
# Normally, there should only be one row per path, in which case the
# second and third elements don't come into play when sorting.
# However, in cases in the wild ... | [
"\n Return the given rows of a RECORD file in sorted order.\n\n Each row is a 3-tuple (path, hash, size) and corresponds to a record of\n a RECORD file (see PEP 376 and PEP 427 for details). For the rows\n passed to this function, the size can be an integer as an int or string,\n or the empty string... |
Please provide a description of the function:def get_csv_rows_for_installed(
old_csv_rows, # type: Iterable[List[str]]
installed, # type: Dict[str, str]
changed, # type: set
generated, # type: List[str]
lib_dir, # type: str
):
# type: (...) -> List[InstalledCSVRow]
installed_rows =... | [
"\n :param installed: A map from archive RECORD path to installation RECORD\n path.\n "
] |
Please provide a description of the function:def move_wheel_files(
name, # type: str
req, # type: Requirement
wheeldir, # type: str
user=False, # type: bool
home=None, # type: Optional[str]
root=None, # type: Optional[str]
pycompile=True, # type: bool
scheme=None, # type: Optiona... | [
"Install a wheel",
"Map archive RECORD paths to installation RECORD paths.",
"# -*- coding: utf-8 -*-\nimport re\nimport sys\n\nfrom %(module)s import %(import_name)s\n\nif __name__ == '__main__':\n sys.argv[0] = re.sub(r'(-script\\.pyw?|\\.exe)?$', '', sys.argv[0])\n sys.exit(%(func)s())\n"
] |
Please provide a description of the function:def wheel_version(source_dir):
# type: (Optional[str]) -> Optional[Tuple[int, ...]]
try:
dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0]
wheel_data = dist.get_metadata('WHEEL')
wheel_data = Parser().parsestr(wheel_dat... | [
"\n Return the Wheel-Version of an extracted wheel, if possible.\n\n Otherwise, return None if we couldn't parse / extract it.\n "
] |
Please provide a description of the function:def _contains_egg_info(
s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)):
return bool(_egg_info_re.search(s)) | [
"Determine whether the string looks like an egg_info.\n\n :param s: The string to parse. E.g. foo-2.1\n "
] |
Please provide a description of the function:def should_use_ephemeral_cache(
req, # type: InstallRequirement
format_control, # type: FormatControl
autobuilding, # type: bool
cache_available # type: bool
):
# type: (...) -> Optional[bool]
if req.constraint:
return None
if req... | [
"\n Return whether to build an InstallRequirement object using the\n ephemeral cache.\n\n :param cache_available: whether a cache directory is available for the\n autobuilding=True case.\n\n :return: True or False to build the requirement with ephem_cache=True\n or False, respectively; or ... |
Please provide a description of the function:def format_command(
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> str
text = 'Command arguments: {}\n'.format(command_args)
if not command_output:
text += 'Command output: None'
elif logger.getEffectiv... | [
"\n Format command information for logging.\n "
] |
Please provide a description of the function:def get_legacy_build_wheel_path(
names, # type: List[str]
temp_dir, # type: str
req, # type: InstallRequirement
command_args, # type: List[str]
command_output, # type: str
):
# type: (...) -> Optional[str]
# Sort for determinism.
nam... | [
"\n Return the path to the wheel in the temporary build directory.\n "
] |
Please provide a description of the function:def support_index_min(self, tags=None):
# type: (Optional[List[Pep425Tag]]) -> Optional[int]
if tags is None: # for mock
tags = pep425tags.get_supported()
indexes = [tags.index(c) for c in self.file_tags if c in tags]
ret... | [
"\n Return the lowest index that one of the wheel's file_tag combinations\n achieves in the supported_tags list e.g. if there are 8 supported tags,\n and one of the file tags is first in the list, then return 0. Returns\n None is the wheel is not supported.\n "
] |
Please provide a description of the function:def supported(self, tags=None):
# type: (Optional[List[Pep425Tag]]) -> bool
if tags is None: # for mock
tags = pep425tags.get_supported()
return bool(set(tags).intersection(self.file_tags)) | [
"Is this wheel supported on this system?"
] |
Please provide a description of the function:def _build_one(self, req, output_dir, python_tag=None):
# Install build deps into temporary directory (PEP 518)
with req.build_env:
return self._build_one_inside_env(req, output_dir,
python_ta... | [
"Build one wheel.\n\n :return: The filename of the built wheel, or None if the build failed.\n "
] |
Please provide a description of the function:def _build_one_pep517(self, req, tempd, python_tag=None):
assert req.metadata_directory is not None
try:
req.spin_message = 'Building wheel for %s (PEP 517)' % (req.name,)
logger.debug('Destination directory: %s', tempd)
... | [
"Build one InstallRequirement using the PEP 517 build process.\n\n Returns path to wheel if successfully built. Otherwise, returns None.\n "
] |
Please provide a description of the function:def _build_one_legacy(self, req, tempd, python_tag=None):
base_args = self._base_setup_args(req)
spin_message = 'Building wheel for %s (setup.py)' % (req.name,)
with open_spinner(spin_message) as spinner:
logger.debug('Destinatio... | [
"Build one InstallRequirement using the \"legacy\" build process.\n\n Returns path to wheel if successfully built. Otherwise, returns None.\n "
] |
Please provide a description of the function:def build(
self,
requirements, # type: Iterable[InstallRequirement]
session, # type: PipSession
autobuilding=False # type: bool
):
# type: (...) -> List[InstallRequirement]
buildset = []
format_control =... | [
"Build wheels.\n\n :param unpack: If True, replace the sdist we built from with the\n newly built wheel, in preparation for installation.\n :return: True if all the wheels built correctly.\n "
] |
Please provide a description of the function:def _get_pypirc_command(self):
from distutils.core import Distribution
from distutils.config import PyPIRCCommand
d = Distribution()
return PyPIRCCommand(d) | [
"\n Get the distutils command for interacting with PyPI configurations.\n :return: the command.\n "
] |
Please provide a description of the function:def read_configuration(self):
# get distutils to do the work
c = self._get_pypirc_command()
c.repository = self.url
cfg = c._read_pypirc()
self.username = cfg.get('username')
self.password = cfg.get('password')
... | [
"\n Read the PyPI access configuration as supported by distutils, getting\n PyPI to do the actual work. This populates ``username``, ``password``,\n ``realm`` and ``url`` attributes from the configuration.\n "
] |
Please provide a description of the function:def save_configuration(self):
self.check_credentials()
# get distutils to do the work
c = self._get_pypirc_command()
c._store_pypirc(self.username, self.password) | [
"\n Save the PyPI access configuration. You must have set ``username`` and\n ``password`` attributes before calling this method.\n\n Again, distutils is used to do the actual work.\n "
] |
Please provide a description of the function:def check_credentials(self):
if self.username is None or self.password is None:
raise DistlibException('username and password must be set')
pm = HTTPPasswordMgr()
_, netloc, _, _, _, _ = urlparse(self.url)
pm.add_password(... | [
"\n Check that ``username`` and ``password`` have been set, and raise an\n exception if not.\n "
] |
Please provide a description of the function:def register(self, metadata):
self.check_credentials()
metadata.validate()
d = metadata.todict()
d[':action'] = 'verify'
request = self.encode_request(d.items(), [])
response = self.send_request(request)
d[':ac... | [
"\n Register a distribution on PyPI, using the provided metadata.\n\n :param metadata: A :class:`Metadata` instance defining at least a name\n and version number for the distribution to be\n registered.\n :return: The HTTP response received from P... |
Please provide a description of the function:def _reader(self, name, stream, outbuf):
while True:
s = stream.readline()
if not s:
break
s = s.decode('utf-8').rstrip()
outbuf.append(s)
logger.debug('%s: %s' % (name, s))
... | [
"\n Thread runner for reading lines of from a subprocess into a buffer.\n\n :param name: The logical name of the stream (used for logging only).\n :param stream: The stream to read from. This will typically a pipe\n connected to the output stream of a subprocess.\n ... |
Please provide a description of the function:def get_sign_command(self, filename, signer, sign_password,
keystore=None):
cmd = [self.gpg, '--status-fd', '2', '--no-tty']
if keystore is None:
keystore = self.gpg_home
if keystore:
cmd.exten... | [
"\n Return a suitable command for signing a file.\n\n :param filename: The pathname to the file to be signed.\n :param signer: The identifier of the signer of the file.\n :param sign_password: The passphrase for the signer's\n private key used for signing.\n ... |
Please provide a description of the function:def run_command(self, cmd, input_data=None):
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
}
if input_data is not None:
kwargs['stdin'] = subprocess.PIPE
stdout = []
stder... | [
"\n Run a command in a child process , passing it any input data specified.\n\n :param cmd: The command to run.\n :param input_data: If specified, this must be a byte string containing\n data to be sent to the child process.\n :return: A tuple consisting of the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.