Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _find_adapter(registry, ob):
types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
for t in types:
if t in registry:
return registry[t] | [
"Return an adapter factory for `ob` from `registry`"
] |
Please provide a description of the function:def ensure_directory(path):
dirname = os.path.dirname(path)
py31compat.makedirs(dirname, exist_ok=True) | [
"Ensure that the parent directory of `path` exists"
] |
Please provide a description of the function:def split_sections(s):
section = None
content = []
for line in yield_lines(s):
if line.startswith("["):
if line.endswith("]"):
if section or content:
yield section, content
section = lin... | [
"Split a string or iterable thereof into (section, content) pairs\n\n Each ``section`` is a stripped version of the section header (\"[section]\")\n and each ``content`` is a list of stripped lines excluding blank lines and\n comment-only lines. If there are any such lines before the first section\n he... |
Please provide a description of the function:def with_context(self, required_by):
if not required_by:
return self
args = self.args + (required_by,)
return ContextualVersionConflict(*args) | [
"\n If required_by is non-empty, return a version of self that is a\n ContextualVersionConflict.\n "
] |
Please provide a description of the function:def _build_master(cls):
ws = cls()
try:
from __main__ import __requires__
except ImportError:
# The main program does not list any requirements
return ws
# ensure the requirements are met
t... | [
"\n Prepare the master working set.\n "
] |
Please provide a description of the function:def _build_from_requirements(cls, req_spec):
# try it without defaults already on sys.path
# by starting with an empty path
ws = cls([])
reqs = parse_requirements(req_spec)
dists = ws.resolve(reqs, Environment())
for d... | [
"\n Build a working set from a requirement spec. Rewrites sys.path.\n "
] |
Please provide a description of the function:def add_entry(self, entry):
self.entry_keys.setdefault(entry, [])
self.entries.append(entry)
for dist in find_distributions(entry, True):
self.add(dist, entry, False) | [
"Add a path item to ``.entries``, finding any distributions on it\n\n ``find_distributions(entry, True)`` is used to find distributions\n corresponding to the path entry, and they are added. `entry` is\n always appended to ``.entries``, even if it is already present.\n (This is because ... |
Please provide a description of the function:def iter_entry_points(self, group, name=None):
return (
entry
for dist in self
for entry in dist.get_entry_map(group).values()
if name is None or name == entry.name
) | [
"Yield entry point objects from `group` matching `name`\n\n If `name` is None, yields all entry points in `group` from all\n distributions in the working set, otherwise only ones matching\n both `group` and `name` are yielded (in distribution order).\n "
] |
Please provide a description of the function:def run_script(self, requires, script_name):
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
self.require(requires)[0].run_script(script_name, ns) | [
"Locate distribution for `requires` and run `script_name` script"
] |
Please provide a description of the function:def require(self, *requirements):
needed = self.resolve(parse_requirements(requirements))
for dist in needed:
self.add(dist)
return needed | [
"Ensure that distributions matching `requirements` are activated\n\n `requirements` must be a string or a (possibly-nested) sequence\n thereof, specifying the distributions and versions required. The\n return value is a sequence of the distributions that needed to be\n activated to fulf... |
Please provide a description of the function:def subscribe(self, callback, existing=True):
if callback in self.callbacks:
return
self.callbacks.append(callback)
if not existing:
return
for dist in self:
callback(dist) | [
"Invoke `callback` for all distributions\n\n If `existing=True` (default),\n call on all existing ones, as well.\n "
] |
Please provide a description of the function:def markers_pass(self, req, extras=None):
extra_evals = (
req.marker.evaluate({'extra': extra})
for extra in self.get(req, ()) + (extras or (None,))
)
return not req.marker or any(extra_evals) | [
"\n Evaluate markers for req against each extra that\n demanded it.\n\n Return False if the req has a marker and fails\n evaluation. Otherwise, return True.\n "
] |
Please provide a description of the function:def scan(self, search_path=None):
if search_path is None:
search_path = sys.path
for item in search_path:
for dist in find_distributions(item):
self.add(dist) | [
"Scan `search_path` for distributions usable in this environment\n\n Any distributions found are added to the environment.\n `search_path` should be a sequence of ``sys.path`` items. If not\n supplied, ``sys.path`` is used. Only distributions conforming to\n the platform/python version... |
Please provide a description of the function:def add(self, dist):
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), ... | [
"Add `dist` if we ``can_add()`` it and it has not already been added\n "
] |
Please provide a description of the function:def best_match(
self, req, working_set, installer=None, replace_conflicting=False):
try:
dist = working_set.find(req)
except VersionConflict:
if not replace_conflicting:
raise
dist = Non... | [
"Find distribution best matching `req` and usable on `working_set`\n\n This calls the ``find(req)`` method of the `working_set` to see if a\n suitable distribution is already active. (This may raise\n ``VersionConflict`` if an unsuitable version of the project is already\n active in the... |
Please provide a description of the function:def extraction_error(self):
old_exc = sys.exc_info()[1]
cache_path = self.extraction_path or get_default_cache()
tmpl = textwrap.dedent().lstrip()
err = ExtractionError(tmpl.format(**locals()))
err.manager = self
err... | [
"Give an error message for problems extracting file(s)",
"\n Can't extract file(s) to egg cache\n\n The following error occurred while trying to extract file(s)\n to the Python egg cache:\n\n {old_exc}\n\n The Python egg cache directory is currently set to:... |
Please provide a description of the function:def _warn_unsafe_extraction_path(path):
if os.name == 'nt' and not path.startswith(os.environ['windir']):
# On Windows, permissions are generally restrictive by default
# and temp directories are not writable by other users, so
... | [
"\n If the default extraction path is overridden and set to an insecure\n location, such as /tmp, it opens up an opportunity for an attacker to\n replace an extracted file with an unauthorized payload. Warn the user\n if a known insecure location is used.\n\n See Distribute #375 f... |
Please provide a description of the function:def postprocess(self, tempname, filename):
if os.name == 'posix':
# Make the resource executable
mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
os.chmod(tempname, mode) | [
"Perform any platform-specific postprocessing of `tempname`\n\n This is where Mac header rewrites should be done; other platforms don't\n have anything special they should do.\n\n Resource providers should call this method ONLY after successfully\n extracting a compressed resource. They... |
Please provide a description of the function:def build(cls, path):
with zipfile.ZipFile(path) as zfile:
items = (
(
name.replace('/', os.sep),
zfile.getinfo(name),
)
for name in zfile.namelist()
... | [
"\n Build a dictionary similar to the zipimport directory\n caches, except instead of tuples, store ZipInfo objects.\n\n Use a platform-specific path separator (os.sep) for the path keys\n for compatibility with pypy on Windows.\n "
] |
Please provide a description of the function:def load(self, path):
path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if path not in self or self[path].mtime != mtime:
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
... | [
"\n Load a manifest at path or return a suitable manifest already loaded.\n "
] |
Please provide a description of the function:def _is_current(self, file_path, zip_path):
timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
if not os.path.isfile(file_path):
return False
stat = os.stat(file_path)
if stat.st_size != size or stat.st_mtim... | [
"\n Return True if the file_path is current for this zip_path\n "
] |
Please provide a description of the function:def load(self, require=True, *args, **kwargs):
if not require or args or kwargs:
warnings.warn(
"Parameters to load are deprecated. Call .resolve and "
".require separately.",
PkgResourcesDeprecati... | [
"\n Require packages for this EntryPoint, then resolve it.\n "
] |
Please provide a description of the function:def resolve(self):
module = __import__(self.module_name, fromlist=['__name__'], level=0)
try:
return functools.reduce(getattr, self.attrs, module)
except AttributeError as exc:
raise ImportError(str(exc)) | [
"\n Resolve the entry point from its module and attrs.\n "
] |
Please provide a description of the function:def parse(cls, src, dist=None):
m = cls.pattern.match(src)
if not m:
msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
raise ValueError(msg, src)
res = m.groupdict()
extras = cls._parse_extras(r... | [
"Parse a single entry point from string `src`\n\n Entry point syntax follows the form::\n\n name = some.module:some.attr [extra1, extra2]\n\n The entry name and module name are required, but the ``:attrs`` and\n ``[extras]`` parts are optional\n "
] |
Please provide a description of the function:def parse_group(cls, group, lines, dist=None):
if not MODULE(group):
raise ValueError("Invalid group name", group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if ep.name in this:
... | [
"Parse an entry point group"
] |
Please provide a description of the function:def parse_map(cls, data, dist=None):
if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for group, lines in data:
if group is None:
if not lin... | [
"Parse a map of entry point groups"
] |
Please provide a description of the function:def _dep_map(self):
try:
return self.__dep_map
except AttributeError:
self.__dep_map = self._filter_extras(self._build_dep_map())
return self.__dep_map | [
"\n A map of extra to its list of (direct) requirements\n for this distribution, including the null extra.\n "
] |
Please provide a description of the function:def _filter_extras(dm):
for extra in list(filter(None, dm)):
new_extra = extra
reqs = dm.pop(extra)
new_extra, _, marker = extra.partition(':')
fails_marker = marker and (
invalid_marker(marker)... | [
"\n Given a mapping of extras to dependencies, strip off\n environment markers and filter out any dependencies\n not matching the markers.\n "
] |
Please provide a description of the function:def requires(self, extras=()):
dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownE... | [
"List of Requirements needed for this distro if `extras` are used"
] |
Please provide a description of the function:def activate(self, path=None, replace=False):
if path is None:
path = sys.path
self.insert_on(path, replace=replace)
if path is sys.path:
fixup_namespace_packages(self.location)
for pkg in self._get_metadat... | [
"Ensure distribution is importable on `path` (default=sys.path)"
] |
Please provide a description of the function:def egg_name(self):
filename = "%s-%s-py%s" % (
to_filename(self.project_name), to_filename(self.version),
self.py_version or PY_MAJOR
)
if self.platform:
filename += '-' + self.platform
return fil... | [
"Return what this distribution's standard .egg filename should be"
] |
Please provide a description of the function:def as_requirement(self):
if isinstance(self.parsed_version, packaging.version.Version):
spec = "%s==%s" % (self.project_name, self.parsed_version)
else:
spec = "%s===%s" % (self.project_name, self.parsed_version)
ret... | [
"Return a ``Requirement`` that matches this distribution exactly"
] |
Please provide a description of the function:def load_entry_point(self, group, name):
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
return ep.load() | [
"Return the `name` entry point of `group` or raise ImportError"
] |
Please provide a description of the function:def get_entry_map(self, group=None):
try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(
self._get_metadata('entry_points.txt'), self
)
if group i... | [
"Return the entry point map for `group`, or the full entry map"
] |
Please provide a description of the function:def clone(self, **kw):
names = 'project_name version py_version platform location precedence'
for attr in names.split():
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provider)
return self.... | [
"Copy this distribution, substituting in any changed keyword args"
] |
Please provide a description of the function:def _reload_version(self):
md_version = _version_from_file(self._get_metadata(self.PKG_INFO))
if md_version:
self._version = md_version
return self | [
"\n Packages installed by distutils (e.g. numpy or scipy),\n which uses an old safe_version, and so\n their version numbers can get mangled when\n converted to filenames (e.g., 1.11.0.dev0+2329eae to\n 1.11.0.dev0_2329eae). These distributions will not be\n parsed properly\... |
Please provide a description of the function:def _compute_dependencies(self):
dm = self.__dep_map = {None: []}
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
reqs.extend(parse_requirements(req))
... | [
"Recompute this distribution's dependencies."
] |
Please provide a description of the function:def _expand_logical_shortcuts(cls, schema):
def is_of_rule(x):
return isinstance(x, _str_type) and \
x.startswith(('allof_', 'anyof_', 'noneof_', 'oneof_'))
for field in schema:
for of_rule in (x for x in sche... | [
" Expand agglutinated rules in a definition-schema.\n\n :param schema: The schema-definition to expand.\n :return: The expanded schema-definition.\n "
] |
Please provide a description of the function:def _validate(self, schema):
if isinstance(schema, _str_type):
schema = self.validator.schema_registry.get(schema, schema)
if schema is None:
raise SchemaError(errors.SCHEMA_ERROR_MISSING)
schema = copy(schema)
... | [
" Validates a schema that defines rules against supported rules.\n\n :param schema: The schema to be validated as a legal cerberus schema\n according to the rules of this Validator object.\n "
] |
Please provide a description of the function:def _validate_logical(self, rule, field, value):
if not isinstance(value, Sequence):
self._error(field, errors.BAD_TYPE)
return
validator = self._get_child_validator(
document_crumb=rule, allow_unknown=False,
... | [
" {'allowed': ('allof', 'anyof', 'noneof', 'oneof')} "
] |
Please provide a description of the function:def add(self, name, definition):
self._storage[name] = self._expand_definition(definition) | [
" Register a definition to the registry. Existing definitions are\n replaced silently.\n\n :param name: The name which can be used as reference in a validation\n schema.\n :type name: :class:`str`\n :param definition: The definition.\n :type definition: any :te... |
Please provide a description of the function:def extend(self, definitions):
for name, definition in dict(definitions).items():
self.add(name, definition) | [
" Add several definitions at once. Existing definitions are\n replaced silently.\n\n :param definitions: The names and definitions.\n :type definitions: a :term:`mapping` or an :term:`iterable` with\n two-value :class:`tuple` s "
] |
Please provide a description of the function:def export(self, location):
url, rev_options = self.get_url_rev_options(self.url)
logger.info('Exporting svn repository %s to %s', url, location)
with indent_log():
if os.path.exists(location):
# Subversion doesn'... | [
"Export the svn repository at the url to the destination location"
] |
Please provide a description of the function:def get_netloc_and_auth(self, netloc, scheme):
if scheme == 'ssh':
# The --username and --password options can't be used for
# svn+ssh URLs, so keep the auth information in the URL.
return super(Subversion, self).get_netlo... | [
"\n This override allows the auth information to be passed to svn via the\n --username and --password options instead of via the URL.\n "
] |
Please provide a description of the function:def cd(path):
if not path:
return
prev_cwd = Path.cwd().as_posix()
if isinstance(path, Path):
path = path.as_posix()
os.chdir(str(path))
try:
yield
finally:
os.chdir(prev_cwd) | [
"Context manager to temporarily change working directories\n\n :param str path: The directory to move into\n\n >>> print(os.path.abspath(os.curdir))\n '/home/user/code/myrepo'\n >>> with cd(\"/home/user/code/otherdir/subdir\"):\n ... print(\"Changed directory: %s\" % os.path.abspath(os.curdir))\n... |
Please provide a description of the function:def spinner(
spinner_name=None,
start_text=None,
handler_map=None,
nospin=False,
write_to_stdout=True,
):
from .spin import create_spinner
has_yaspin = None
try:
import yaspin
except ImportError:
has_yaspin = False
... | [
"Get a spinner object or a dummy spinner to wrap a context.\n\n :param str spinner_name: A spinner type e.g. \"dots\" or \"bouncingBar\" (default: {\"bouncingBar\"})\n :param str start_text: Text to start off the spinner with (default: {None})\n :param dict handler_map: Handler map for signals to be handle... |
Please provide a description of the function:def atomic_open_for_write(target, binary=False, newline=None, encoding=None):
mode = "w+b" if binary else "w"
f = NamedTemporaryFile(
dir=os.path.dirname(target),
prefix=".__atomic-write",
mode=mode,
encoding=encoding,
ne... | [
"Atomically open `target` for writing.\n\n This is based on Lektor's `atomic_open()` utility, but simplified a lot\n to handle only writing, and skip many multi-process/thread edge cases\n handled by Werkzeug.\n\n :param str target: Target filename to write\n :param bool binary: Whether to open in bi... |
Please provide a description of the function:def open_file(link, session=None, stream=True):
if not isinstance(link, six.string_types):
try:
link = link.url_without_fragment
except AttributeError:
raise ValueError("Cannot parse url from unkown type: {0!r}".format(link))
... | [
"\n Open local or remote file for reading.\n\n :type link: pip._internal.index.Link or str\n :type session: requests.Session\n :param bool stream: Try to stream if remote, default True\n :raises ValueError: If link points to a local directory.\n :return: a context manager to the opened file-like o... |
Please provide a description of the function:def replaced_stream(stream_name):
orig_stream = getattr(sys, stream_name)
new_stream = six.StringIO()
try:
setattr(sys, stream_name, new_stream)
yield getattr(sys, stream_name)
finally:
setattr(sys, stream_name, orig_stream) | [
"\n Context manager to temporarily swap out *stream_name* with a stream wrapper.\n\n :param str stream_name: The name of a sys stream to wrap\n :returns: A ``StreamWrapper`` replacement, temporarily\n\n >>> orig_stdout = sys.stdout\n >>> with replaced_stream(\"stdout\") as stdout:\n ... sys.st... |
Please provide a description of the function:def read_nonblocking(self, size=1, timeout=None):
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
... | [
"This reads data from the file descriptor.\n\n This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.\n\n The timeout parameter is ignored.\n "
] |
Please provide a description of the function:def compile_pattern_list(self, patterns):
'''This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
those. Patterns may also be None which results in an empty list (you
... | [] |
Please provide a description of the function:def expect(self, pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw):
'''This seeks through the stream until a pattern is matched. The
pattern is overloaded and may take several types. The pattern can be a
StringType, EOF, a compiled re, or ... | [] |
Please provide a description of the function:def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1,
async_=False, **kw):
'''This takes a list of compiled regular expressions and returns the
index into the pattern_list that matched the child output. The list may
... | [] |
Please provide a description of the function:def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
'''This is the common loop used inside expect. The 'searcher' should be
an instance of searcher_re or searcher_string, which describes how and
what to search for in the input.
... | [] |
Please provide a description of the function:def read(self, size=-1):
'''This reads at most "size" bytes from the file (less if the read hits
EOF before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached. The bytes are returned as
a str... | [] |
Please provide a description of the function:def readline(self, size=-1):
'''This reads and returns one entire line. The newline at the end of
line is returned as part of the string, unless the file ends without a
newline. An empty string is returned if EOF is encountered immediately.
Th... | [] |
Please provide a description of the function:def readlines(self, sizehint=-1):
'''This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored.
Remember, because this reads until EOF that means the child
process shou... | [] |
Please provide a description of the function:def _length_hint(obj):
try:
return len(obj)
except (AttributeError, TypeError):
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
exc... | [
"Returns the length hint of an object."
] |
Please provide a description of the function:def _tempfilepager(generator, cmd, color):
import tempfile
filename = tempfile.mktemp()
# TODO: This never terminates if the passed generator never terminates.
text = "".join(generator)
if not color:
text = strip_ansi(text)
encoding = get... | [
"Page through text by invoking a program on a temporary file."
] |
Please provide a description of the function:def _nullpager(stream, generator, color):
for text in generator:
if not color:
text = strip_ansi(text)
stream.write(text) | [
"Simply print unformatted text. This is the ultimate fallback."
] |
Please provide a description of the function:def generator(self):
if not self.entered:
raise RuntimeError('You need to use progress bars in a with block.')
if self.is_hidden:
for rv in self.iter:
yield rv
else:
for rv in self.iter:
... | [
"\n Returns a generator which yields the items added to the bar during\n construction, and updates the progress bar *after* the yielded block\n returns.\n "
] |
Please provide a description of the function:def bar(
it,
label="",
width=32,
hide=None,
empty_char=BAR_EMPTY_CHAR,
filled_char=BAR_FILLED_CHAR,
expected_size=None,
every=1,
):
count = len(it) if expected_size is None else expected_size
with Bar(
label=label,
... | [
"Progress iterator. Wrap your iterables with it."
] |
Please provide a description of the function:def dots(it, label="", hide=None, every=1):
count = 0
if not hide:
STREAM.write(label)
for i, item in enumerate(it):
if not hide:
if i % every == 0: # True every "every" updates
STREAM.write(DOTS_CHAR)
... | [
"Progress iterator. Prints a dot for each item being iterated"
] |
Please provide a description of the function:def parse(version):
match = _REGEX.match(version)
if match is None:
raise ValueError('%s is not valid SemVer string' % version)
version_parts = match.groupdict()
version_parts['major'] = int(version_parts['major'])
version_parts['minor'] = ... | [
"Parse version to major, minor, patch, pre-release, build parts.\n\n :param version: version string\n :return: dictionary with the keys 'build', 'major', 'minor', 'patch',\n and 'prerelease'. The prerelease or build keys can be None\n if not provided\n :rtype: dict\n\n >>> import... |
Please provide a description of the function:def parse_version_info(version):
parts = parse(version)
version_info = VersionInfo(
parts['major'], parts['minor'], parts['patch'],
parts['prerelease'], parts['build'])
return version_info | [
"Parse version string to a VersionInfo instance.\n\n :param version: version string\n :return: a :class:`VersionInfo` instance\n :rtype: :class:`VersionInfo`\n\n >>> import semver\n >>> version_info = semver.parse_version_info(\"3.4.5-pre.2+build.4\")\n >>> version_info.major\n 3\n >>> versi... |
Please provide a description of the function:def compare(ver1, ver2):
v1, v2 = parse(ver1), parse(ver2)
return _compare_by_keys(v1, v2) | [
"Compare two versions\n\n :param ver1: version string 1\n :param ver2: version string 2\n :return: The return value is negative if ver1 < ver2,\n zero if ver1 == ver2 and strictly positive if ver1 > ver2\n :rtype: int\n\n >>> import semver\n >>> semver.compare(\"1.0.0\", \"2.0.0\")\n ... |
Please provide a description of the function:def match(version, match_expr):
prefix = match_expr[:2]
if prefix in ('>=', '<=', '==', '!='):
match_version = match_expr[2:]
elif prefix and prefix[0] in ('>', '<'):
prefix = prefix[0]
match_version = match_expr[1:]
else:
... | [
"Compare two versions through a comparison\n\n :param str version: a version string\n :param str match_expr: operator and version; valid operators are\n < smaller than\n > greater than\n >= greator or equal than\n <= smaller or equal than\n == equal\n ... |
Please provide a description of the function:def max_ver(ver1, ver2):
cmp_res = compare(ver1, ver2)
if cmp_res == 0 or cmp_res == 1:
return ver1
else:
return ver2 | [
"Returns the greater version of two versions\n\n :param ver1: version string 1\n :param ver2: version string 2\n :return: the greater version of the two\n :rtype: :class:`VersionInfo`\n\n >>> import semver\n >>> semver.max_ver(\"1.0.0\", \"2.0.0\")\n '2.0.0'\n "
] |
Please provide a description of the function:def min_ver(ver1, ver2):
cmp_res = compare(ver1, ver2)
if cmp_res == 0 or cmp_res == -1:
return ver1
else:
return ver2 | [
"Returns the smaller version of two versions\n\n :param ver1: version string 1\n :param ver2: version string 2\n :return: the smaller version of the two\n :rtype: :class:`VersionInfo`\n\n >>> import semver\n >>> semver.min_ver(\"1.0.0\", \"2.0.0\")\n '1.0.0'\n "
] |
Please provide a description of the function:def format_version(major, minor, patch, prerelease=None, build=None):
version = "%d.%d.%d" % (major, minor, patch)
if prerelease is not None:
version = version + "-%s" % prerelease
if build is not None:
version = version + "+%s" % build
... | [
"Format a version according to the Semantic Versioning specification\n\n :param str major: the required major part of a version\n :param str minor: the required minor part of a version\n :param str patch: the required patch part of a version\n :param str prerelease: the optional prerelease part of a ver... |
Please provide a description of the function:def _make_eof_intr():
global _EOF, _INTR
if (_EOF is not None) and (_INTR is not None):
return
# inherit EOF and INTR definitions from controlling process.
try:
from termios import VEOF, VINTR
fd = None
for name in 'stdin... | [
"Set constants _EOF and _INTR.\n \n This avoids doing potentially costly operations on module load.\n "
] |
Please provide a description of the function:def spawn(
cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
dimensions=(24, 80)):
'''Start the given command in a child process in a pseudo terminal.
This does all the fork/exec type of stuff for a pty, and returns an
... | [] |
Please provide a description of the function:def close(self, force=True):
'''This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the ch... | [] |
Please provide a description of the function:def getecho(self):
'''This returns the terminal echo mode. This returns True if echo is
on or False if echo is off. Child applications that are expecting you
to enter a password often set ECHO False. See waitnoecho().
Not supported on platfor... | [] |
Please provide a description of the function:def setecho(self, state):
'''This sets the terminal echo mode on or off. Note that anything the
child sent before the echo will be lost, so you should be sure that
your input buffer is empty before you call setecho(). For example, the
followin... | [] |
Please provide a description of the function:def read(self, size=1024):
try:
s = self.fileobj.read1(size)
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError(... | [
"Read and return at most ``size`` bytes from the pty.\n\n Can block if there is nothing to read. Raises :exc:`EOFError` if the\n terminal was closed.\n \n Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal\n with the vagaries of EOF on platforms that do strange... |
Please provide a description of the function:def readline(self):
try:
s = self.fileobj.readline()
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of ... | [
"Read one line from the pseudoterminal, and return it as unicode.\n\n Can block if there is nothing to read. Raises :exc:`EOFError` if the\n terminal was closed.\n "
] |
Please provide a description of the function:def write(self, s, flush=True):
return self._writeb(s, flush=flush) | [
"Write bytes to the pseudoterminal.\n \n Returns the number of bytes written.\n "
] |
Please provide a description of the function:def sendcontrol(self, char):
'''Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
... | [] |
Please provide a description of the function:def wait(self):
'''This waits until the child exits. This is a blocking call. This will
not read any data from the child, so this will block forever if the
child has unread output and has terminated. In other words, the child
may have printed ... | [] |
Please provide a description of the function:def kill(self, sig):
# Same as os.kill, but the pid is given for you.
if self.isalive():
os.kill(self.pid, sig) | [
"Send the given signal to the child application.\n\n In keeping with UNIX tradition it has a misleading name. It does not\n necessarily kill the child unless you send the right signal. See the\n :mod:`signal` module for constants representing signal numbers.\n "
] |
Please provide a description of the function:def read(self, size=1024):
b = super(PtyProcessUnicode, self).read(size)
return self.decoder.decode(b, final=False) | [
"Read at most ``size`` bytes from the pty, return them as unicode.\n\n Can block if there is nothing to read. Raises :exc:`EOFError` if the\n terminal was closed.\n\n The size argument still refers to bytes, not unicode code points.\n "
] |
Please provide a description of the function:def readline(self):
b = super(PtyProcessUnicode, self).readline()
return self.decoder.decode(b, final=False) | [
"Read one line from the pseudoterminal, and return it as unicode.\n\n Can block if there is nothing to read. Raises :exc:`EOFError` if the\n terminal was closed.\n "
] |
Please provide a description of the function:def write(self, s):
b = s.encode(self.encoding)
return super(PtyProcessUnicode, self).write(b) | [
"Write the unicode string ``s`` to the pseudoterminal.\n\n Returns the number of bytes written.\n "
] |
Please provide a description of the function:def from_requirement(cls, provider, requirement, parent):
candidates = provider.find_matches(requirement)
if not candidates:
raise NoVersionsAvailable(requirement, parent)
return cls(
candidates=candidates,
... | [
"Build an instance from a requirement.\n "
] |
Please provide a description of the function:def merged_with(self, provider, requirement, parent):
infos = list(self.information)
infos.append(RequirementInformation(requirement, parent))
candidates = [
c for c in self.candidates
if provider.is_satisfied_by(requi... | [
"Build a new instance from this and a new requirement.\n "
] |
Please provide a description of the function:def _push_new_state(self):
try:
base = self._states[-1]
except IndexError:
graph = DirectedGraph()
graph.add(None) # Sentinel as root dependencies' parent.
state = State(mapping={}, graph=graph)
... | [
"Push a new state into history.\n\n This new state will be used to hold resolution results of the next\n coming round.\n "
] |
Please provide a description of the function:def resolve(self, requirements, max_rounds=20):
resolution = Resolution(self.provider, self.reporter)
resolution.resolve(requirements, max_rounds=max_rounds)
return resolution.state | [
"Take a collection of constraints, spit out the resolution result.\n\n The return value is a representation to the final resolution result. It\n is a tuple subclass with two public members:\n\n * `mapping`: A dict of resolved candidates. Each key is an identifier\n of a requirement (... |
Please provide a description of the function:def _strip_extra(elements):
extra_indexes = []
for i, element in enumerate(elements):
if isinstance(element, list):
cancelled = _strip_extra(element)
if cancelled:
extra_indexes.append(i)
elif isinstance(el... | [
"Remove the \"extra == ...\" operands from the list.\n\n This is not a comprehensive implementation, but relies on an important\n characteristic of metadata generation: The \"extra == ...\" operand is always\n associated with an \"and\" operator. This means that we can simply remove the\n operand and th... |
Please provide a description of the function:def get_without_extra(marker):
# TODO: Why is this very deep in the internals? Why is a better solution
# implementing it yourself when someone is already maintaining a codebase
# for this? It's literally a grammar implementation that is required to
# me... | [
"Build a new marker without the `extra == ...` part.\n\n The implementation relies very deep into packaging's internals, but I don't\n have a better way now (except implementing the whole thing myself).\n\n This could return `None` if the `extra == ...` part is the only one in the\n input marker.\n "... |
Please provide a description of the function:def get_contained_extras(marker):
if not marker:
return set()
marker = Marker(str(marker))
extras = set()
_markers_collect_extras(marker._markers, extras)
return extras | [
"Collect \"extra == ...\" operands from a marker.\n\n Returns a list of str. Each str is a speficied extra in this marker.\n "
] |
Please provide a description of the function:def contains_extra(marker):
if not marker:
return False
marker = Marker(str(marker))
return _markers_contains_extra(marker._markers) | [
"Check whehter a marker contains an \"extra == ...\" operand.\n "
] |
Please provide a description of the function:def get_errors(self):
result = []
while not self.errors.empty(): # pragma: no cover
try:
e = self.errors.get(False)
result.append(e)
except self.errors.Empty:
continue
... | [
"\n Return any errors which have occurred.\n "
] |
Please provide a description of the function:def get_project(self, name):
if self._cache is None: # pragma: no cover
result = self._get_project(name)
elif name in self._cache:
result = self._cache[name]
else:
self.clear_errors()
result = ... | [
"\n For a given project, get a dictionary mapping available versions to Distribution\n instances.\n\n This calls _get_project to do all the work, and just implements a caching layer on top.\n "
] |
Please provide a description of the function:def score_url(self, url):
t = urlparse(url)
basename = posixpath.basename(t.path)
compatible = True
is_wheel = basename.endswith('.whl')
is_downloadable = basename.endswith(self.downloadable_extensions)
if is_wheel:
... | [
"\n Give an url a score which can be used to choose preferred URLs\n for a given project release.\n "
] |
Please provide a description of the function:def prefer_url(self, url1, url2):
result = url2
if url1:
s1 = self.score_url(url1)
s2 = self.score_url(url2)
if s1 > s2:
result = url1
if result != url2:
logger.debug('No... | [
"\n Choose one of two URLs where both are candidates for distribution\n archives for the same version of a distribution (for example,\n .tar.gz vs. zip).\n\n The current implementation favours https:// URLs over http://, archives\n from PyPI over those from other locations, wheel ... |
Please provide a description of the function:def _get_digest(self, info):
result = None
for algo in ('sha256', 'md5'):
key = '%s_digest' % algo
if key in info:
result = (algo, info[key])
break
return result | [
"\n Get a digest from a dictionary by looking at keys of the form\n 'algo_digest'.\n\n Returns a 2-tuple (algo, digest) if found, else None. Currently\n looks only for SHA256, then MD5.\n "
] |
Please provide a description of the function:def links(self):
def clean(url):
"Tidy up an URL."
scheme, netloc, path, params, query, frag = urlparse(url)
return urlunparse((scheme, netloc, quote(path),
params, query, frag))
res... | [
"\n Return the URLs of all the links on a page together with information\n about their \"rel\" attribute, for determining which ones to treat as\n downloads and which ones to queue for further scraping.\n "
] |
Please provide a description of the function:def _prepare_threads(self):
self._threads = []
for i in range(self.num_workers):
t = threading.Thread(target=self._fetch)
t.setDaemon(True)
t.start()
self._threads.append(t) | [
"\n Threads are created only when get_project is called, and terminate\n before it returns. They are there primarily to parallelise I/O (i.e.\n fetching web pages).\n "
] |
Please provide a description of the function:def _wait_threads(self):
# Note that you need two loops, since you can't say which
# thread will get each sentinel
for t in self._threads:
self._to_fetch.put(None) # sentinel
for t in self._threads:
t.join()... | [
"\n Tell all the threads to terminate (by sending a sentinel value) and\n wait for them to do so.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.