INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Read data from the file. | def read(self, size=None):
"""Read data from the file.
"""
if size is None:
size = self.size - self.position
else:
size = min(size, self.size - self.position)
buf = b""
while size > 0:
while True:
data, start, stop, off... |
Read at most size bytes from the file. If size is not
present or None, read all data until EOF is reached. | def read(self, size=None):
"""Read at most size bytes from the file. If size is not
present or None, read all data until EOF is reached.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
buf = b""
if self.buffer:
if size is N... |
Read one entire line from the file. If size is present
and non-negative, return a string with at most that
size, which may be an incomplete line. | def readline(self, size=-1):
"""Read one entire line from the file. If size is present
and non-negative, return a string with at most that
size, which may be an incomplete line.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
pos = ... |
Seek to a position in the file. | def seek(self, pos, whence=os.SEEK_SET):
"""Seek to a position in the file.
"""
if self.closed:
raise ValueError("I/O operation on closed file")
if whence == os.SEEK_SET:
self.position = min(max(pos, 0), self.size)
elif whence == os.SEEK_CUR:
... |
Return the TarInfo's attributes as a dictionary. | def get_info(self):
"""Return the TarInfo's attributes as a dictionary.
"""
info = {
"name": self.name,
"mode": self.mode & 0o7777,
"uid": self.uid,
"gid": self.gid,
"size": self.size,
"mtime": self.... |
Return a tar header as a string of 512 byte blocks. | def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
"""Return a tar header as a string of 512 byte blocks.
"""
info = self.get_info()
if format == USTAR_FORMAT:
return self.create_ustar_header(info, encoding, errors)
elif format == GN... |
Return the object as a ustar header block. | def create_ustar_header(self, info, encoding, errors):
"""Return the object as a ustar header block.
"""
info["magic"] = POSIX_MAGIC
if len(info["linkname"]) > LENGTH_LINK:
raise ValueError("linkname is too long")
if len(info["name"]) > LENGTH_NAME:
info... |
Return the object as a GNU header block sequence. | def create_gnu_header(self, info, encoding, errors):
"""Return the object as a GNU header block sequence.
"""
info["magic"] = GNU_MAGIC
buf = b""
if len(info["linkname"]) > LENGTH_LINK:
buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding,... |
Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information. | def create_pax_header(self, info, encoding):
"""Return the object as a ustar header block. If it cannot be
represented this way, prepend a pax extended header sequence
with supplement information.
"""
info["magic"] = POSIX_MAGIC
pax_headers = self.pax_headers.copy()... |
Split a name longer than 100 chars into a prefix
and a name part. | def _posix_split_name(self, name):
"""Split a name longer than 100 chars into a prefix
and a name part.
"""
prefix = name[:LENGTH_PREFIX + 1]
while prefix and prefix[-1] != "/":
prefix = prefix[:-1]
name = name[len(prefix):]
prefix = prefix[:-1]
... |
Return a header block. info is a dictionary with file
information, format must be one of the *_FORMAT constants. | def _create_header(info, format, encoding, errors):
"""Return a header block. info is a dictionary with file
information, format must be one of the *_FORMAT constants.
"""
parts = [
stn(info.get("name", ""), 100, encoding, errors),
itn(info.get("mode", 0) & 0o7... |
Return the string payload filled with zero bytes
up to the next 512 byte border. | def _create_payload(payload):
"""Return the string payload filled with zero bytes
up to the next 512 byte border.
"""
blocks, remainder = divmod(len(payload), BLOCKSIZE)
if remainder > 0:
payload += (BLOCKSIZE - remainder) * NUL
return payload |
Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
for name. | def _create_gnu_long_header(cls, name, type, encoding, errors):
"""Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
for name.
"""
name = name.encode(encoding, errors) + NUL
info = {}
info["name"] = "././@LongLink"
info["type"] = type
info["size"]... |
Return a POSIX.1-2008 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be strings. | def _create_pax_generic_header(cls, pax_headers, type, encoding):
"""Return a POSIX.1-2008 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be strings.
"""
# Check if one of the fields contains surrogate characters and thereby... |
Construct a TarInfo object from a 512 byte bytes object. | def frombuf(cls, buf, encoding, errors):
"""Construct a TarInfo object from a 512 byte bytes object.
"""
if len(buf) == 0:
raise EmptyHeaderError("empty header")
if len(buf) != BLOCKSIZE:
raise TruncatedHeaderError("truncated header")
if buf.count(NUL) == ... |
Return the next TarInfo object from TarFile object
tarfile. | def fromtarfile(cls, tarfile):
"""Return the next TarInfo object from TarFile object
tarfile.
"""
buf = tarfile.fileobj.read(BLOCKSIZE)
obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
return obj._proc_mem... |
Choose the right processing method depending on
the type and call it. | def _proc_member(self, tarfile):
"""Choose the right processing method depending on
the type and call it.
"""
if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
return self._proc_gnulong(tarfile)
elif self.type == GNUTYPE_SPARSE:
return self._proc_sp... |
Process a builtin type or an unknown type which
will be treated as a regular file. | def _proc_builtin(self, tarfile):
"""Process a builtin type or an unknown type which
will be treated as a regular file.
"""
self.offset_data = tarfile.fileobj.tell()
offset = self.offset_data
if self.isreg() or self.type not in SUPPORTED_TYPES:
# Skip the f... |
Process the blocks that hold a GNU longname
or longlink member. | def _proc_gnulong(self, tarfile):
"""Process the blocks that hold a GNU longname
or longlink member.
"""
buf = tarfile.fileobj.read(self._block(self.size))
# Fetch the next header and process it.
try:
next = self.fromtarfile(tarfile)
except HeaderE... |
Process a GNU sparse header plus extra headers. | def _proc_sparse(self, tarfile):
"""Process a GNU sparse header plus extra headers.
"""
# We already collected some sparse structures in frombuf().
structs, isextended, origsize = self._sparse_structs
del self._sparse_structs
# Collect sparse structures from extended hea... |
Process an extended or global header as described in
POSIX.1-2008. | def _proc_pax(self, tarfile):
"""Process an extended or global header as described in
POSIX.1-2008.
"""
# Read the header information.
buf = tarfile.fileobj.read(self._block(self.size))
# A pax header stores supplemental information for either
# the following ... |
Process a GNU tar extended sparse header, version 0.0. | def _proc_gnusparse_00(self, next, pax_headers, buf):
"""Process a GNU tar extended sparse header, version 0.0.
"""
offsets = []
for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
offsets.append(int(match.group(1)))
numbytes = []
for match in re... |
Process a GNU tar extended sparse header, version 0.1. | def _proc_gnusparse_01(self, next, pax_headers):
"""Process a GNU tar extended sparse header, version 0.1.
"""
sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")]
next.sparse = list(zip(sparse[::2], sparse[1::2])) |
Process a GNU tar extended sparse header, version 1.0. | def _proc_gnusparse_10(self, next, pax_headers, tarfile):
"""Process a GNU tar extended sparse header, version 1.0.
"""
fields = None
sparse = []
buf = tarfile.fileobj.read(BLOCKSIZE)
fields, buf = buf.split(b"\n", 1)
fields = int(fields)
while len(sparse)... |
Replace fields with supplemental information from a previous
pax extended or global header. | def _apply_pax_info(self, pax_headers, encoding, errors):
"""Replace fields with supplemental information from a previous
pax extended or global header.
"""
for keyword, value in pax_headers.items():
if keyword == "GNU.sparse.name":
setattr(self, "path", va... |
Decode a single field from a pax record. | def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
"""Decode a single field from a pax record.
"""
try:
return value.decode(encoding, "strict")
except UnicodeDecodeError:
return value.decode(fallback_encoding, fallback_errors) |
Round up a byte count by BLOCKSIZE and return it,
e.g. _block(834) => 1024. | def _block(self, count):
"""Round up a byte count by BLOCKSIZE and return it,
e.g. _block(834) => 1024.
"""
blocks, remainder = divmod(count, BLOCKSIZE)
if remainder:
blocks += 1
return blocks * BLOCKSIZE |
Open a tar archive for reading, writing or appending. Return
an appropriate TarFile class.
mode:
'r' or 'r:*' open for reading with transparent compression
'r:' open for reading exclusively uncompressed
'r:gz' open for reading with gzip compression
... | def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
"""Open a tar archive for reading, writing or appending. Return
an appropriate TarFile class.
mode:
'r' or 'r:*' open for reading with transparent compression
'r:' open for readin... |
Open uncompressed tar archive name for reading or writing. | def taropen(cls, name, mode="r", fileobj=None, **kwargs):
"""Open uncompressed tar archive name for reading or writing.
"""
if len(mode) > 1 or mode not in "raw":
raise ValueError("mode must be 'r', 'a' or 'w'")
return cls(name, mode, fileobj, **kwargs) |
Open gzip compressed tar archive name for reading or writing.
Appending is not allowed. | def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
"""Open gzip compressed tar archive name for reading or writing.
Appending is not allowed.
"""
if len(mode) > 1 or mode not in "rw":
raise ValueError("mode must be 'r' or 'w'")
try:
... |
Open bzip2 compressed tar archive name for reading or writing.
Appending is not allowed. | def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
"""Open bzip2 compressed tar archive name for reading or writing.
Appending is not allowed.
"""
if len(mode) > 1 or mode not in "rw":
raise ValueError("mode must be 'r' or 'w'.")
try:
... |
Close the TarFile. In write-mode, two finishing zero blocks are
appended to the archive. | def close(self):
"""Close the TarFile. In write-mode, two finishing zero blocks are
appended to the archive.
"""
if self.closed:
return
if self.mode in "aw":
self.fileobj.write(NUL * (BLOCKSIZE * 2))
self.offset += (BLOCKSIZE * 2)
... |
Return a TarInfo object for member `name'. If `name' can not be
found in the archive, KeyError is raised. If a member occurs more
than once in the archive, its last occurrence is assumed to be the
most up-to-date version. | def getmember(self, name):
"""Return a TarInfo object for member `name'. If `name' can not be
found in the archive, KeyError is raised. If a member occurs more
than once in the archive, its last occurrence is assumed to be the
most up-to-date version.
"""
tarinfo... |
Return the members of the archive as a list of TarInfo objects. The
list has the same order as the members in the archive. | def getmembers(self):
"""Return the members of the archive as a list of TarInfo objects. The
list has the same order as the members in the archive.
"""
self._check()
if not self._loaded: # if we want to obtain a list of
self._load() # all members, we firs... |
Create a TarInfo object for either the file `name' or the file
object `fileobj' (using os.fstat on its file descriptor). You can
modify some of the TarInfo's attributes before you add it using
addfile(). If given, `arcname' specifies an alternative name for the
file in the ar... | def gettarinfo(self, name=None, arcname=None, fileobj=None):
"""Create a TarInfo object for either the file `name' or the file
object `fileobj' (using os.fstat on its file descriptor). You can
modify some of the TarInfo's attributes before you add it using
addfile(). If given, `... |
Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced. | def list(self, verbose=True):
"""Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced.
"""
self._check()
for tarinfo in self:
if verbose:
... |
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
given, tarinfo.size bytes are read from it and added to the archive.
You can create TarInfo objects using gettarinfo().
On Windows platforms, `fileobj' should always be opened with mode
'rb' to avoid irritation ... | def addfile(self, tarinfo, fileobj=None):
"""Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
given, tarinfo.size bytes are read from it and added to the archive.
You can create TarInfo objects using gettarinfo().
On Windows platforms, `fileobj' should always be ... |
Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmember... | def extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must... |
Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a TarInfo object. You can
specify a different directory using `path'. File attributes (owner,
mt... | def extract(self, member, path="", set_attrs=True):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a TarInfo object. You can
specify a differen... |
Extract the TarInfo object tarinfo to a physical
file called targetpath. | def _extract_member(self, tarinfo, targetpath, set_attrs=True):
"""Extract the TarInfo object tarinfo to a physical
file called targetpath.
"""
# Fetch the TarInfo object for the given name
# and build the destination pathname, replacing
# forward slashes to platform s... |
Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. If `member' is none of
the above... | def extractfile(self, member):
"""Extract a member from the archive as a file object. `member' may be
a filename or a TarInfo object. If `member' is a regular file, a
file-like object is returned. If `member' is a link, a file-like
object is constructed from the link's target. I... |
Make a directory called targetpath. | def makedir(self, tarinfo, targetpath):
"""Make a directory called targetpath.
"""
try:
# Use a safe mode for the directory, the real mode is set
# later in _extract_member().
os.mkdir(targetpath, 0o700)
except EnvironmentError as e:
if e.e... |
Make a file called targetpath. | def makefile(self, tarinfo, targetpath):
"""Make a file called targetpath.
"""
source = self.fileobj
source.seek(tarinfo.offset_data)
target = bltn_open(targetpath, "wb")
if tarinfo.sparse is not None:
for offset, size in tarinfo.sparse:
target... |
Make a file from a TarInfo object with an unknown type
at targetpath. | def makeunknown(self, tarinfo, targetpath):
"""Make a file from a TarInfo object with an unknown type
at targetpath.
"""
self.makefile(tarinfo, targetpath)
self._dbg(1, "tarfile: Unknown file type %r, " \
"extracted as regular file." % tarinfo.type) |
Make a fifo called targetpath. | def makefifo(self, tarinfo, targetpath):
"""Make a fifo called targetpath.
"""
if hasattr(os, "mkfifo"):
os.mkfifo(targetpath)
else:
raise ExtractError("fifo not supported by system") |
Make a character or block device called targetpath. | def makedev(self, tarinfo, targetpath):
"""Make a character or block device called targetpath.
"""
if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
raise ExtractError("special devices not supported by system")
mode = tarinfo.mode
if tarinfo.isblk():
... |
Make a (symbolic) link called targetpath. If it cannot be created
(platform limitation), we try to make a copy of the referenced file
instead of a link. | def makelink(self, tarinfo, targetpath):
"""Make a (symbolic) link called targetpath. If it cannot be created
(platform limitation), we try to make a copy of the referenced file
instead of a link.
"""
try:
# For systems that support symbolic and hard links.
... |
Set owner of targetpath according to tarinfo. | def chown(self, tarinfo, targetpath):
"""Set owner of targetpath according to tarinfo.
"""
if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
try:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
... |
Set file permissions of targetpath according to tarinfo. | def chmod(self, tarinfo, targetpath):
"""Set file permissions of targetpath according to tarinfo.
"""
if hasattr(os, 'chmod'):
try:
os.chmod(targetpath, tarinfo.mode)
except EnvironmentError as e:
raise ExtractError("could not change mode") |
Set modification time of targetpath according to tarinfo. | def utime(self, tarinfo, targetpath):
"""Set modification time of targetpath according to tarinfo.
"""
if not hasattr(os, 'utime'):
return
try:
os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
except EnvironmentError as e:
raise ExtractErro... |
Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available. | def next(self):
"""Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
"""
self._check("ra")
if self.firstmember is not None:
m = self.firstmember
self.firs... |
Find an archive member by name from bottom to top.
If tarinfo is given, it is used as the starting point. | def _getmember(self, name, tarinfo=None, normalize=False):
"""Find an archive member by name from bottom to top.
If tarinfo is given, it is used as the starting point.
"""
# Ensure that all members have been loaded.
members = self.getmembers()
# Limit the member searc... |
Read through the entire archive file and look for readable
members. | def _load(self):
"""Read through the entire archive file and look for readable
members.
"""
while True:
tarinfo = self.next()
if tarinfo is None:
break
self._loaded = True |
Check if TarFile is still open, and if the operation's mode
corresponds to TarFile's mode. | def _check(self, mode=None):
"""Check if TarFile is still open, and if the operation's mode
corresponds to TarFile's mode.
"""
if self.closed:
raise IOError("%s is closed" % self.__class__.__name__)
if mode is not None and self.mode not in mode:
raise I... |
Find the target member of a symlink or hardlink member in the
archive. | def _find_link_target(self, tarinfo):
"""Find the target member of a symlink or hardlink member in the
archive.
"""
if tarinfo.issym():
# Always search the entire archive.
linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname
limit = Non... |
Write debugging output to sys.stderr. | def _dbg(self, level, msg):
"""Write debugging output to sys.stderr.
"""
if level <= self.debug:
print(msg, file=sys.stderr) |
Returns the absolute path to a given relative path. | def path_to(self, p):
"""Returns the absolute path to a given relative path."""
if os.path.isabs(p):
return p
return os.sep.join([self._original_dir, p]) |
Returns a list of packages for pip-tools to consume. | def _build_package_list(self, package_section):
"""Returns a list of packages for pip-tools to consume."""
from pipenv.vendor.requirementslib.utils import is_vcs
ps = {}
# TODO: Separate the logic for showing packages from the filters for supplying pip-tools
for k, v in self.pars... |
Get the name of the virtualenv adjusted for windows if needed
Returns (name, encoded_hash) | def _get_virtualenv_hash(self, name):
"""Get the name of the virtualenv adjusted for windows if needed
Returns (name, encoded_hash)
"""
def get_name(name, location):
name = self._sanitize(name)
hash = hashlib.sha256(location.encode()).digest()[:6]
en... |
Registers a proper name to the database. | def register_proper_name(self, name):
"""Registers a proper name to the database."""
with self.proper_names_db_path.open("a") as f:
f.write(u"{0}\n".format(name)) |
Parse Pipfile into a TOMLFile and cache it
(call clear_pipfile_cache() afterwards if mutating) | def parsed_pipfile(self):
"""Parse Pipfile into a TOMLFile and cache it
(call clear_pipfile_cache() afterwards if mutating)"""
contents = self.read_pipfile()
# use full contents to get around str/bytes 2/3 issues
cache_key = (self.pipfile_location, contents)
if cache_key... |
Pipfile.lock divided by PyPI and external dependencies. | def _lockfile(self):
"""Pipfile.lock divided by PyPI and external dependencies."""
pfile = pipfile.load(self.pipfile_location, inject_env=False)
lockfile = json.loads(pfile.lock())
for section in ("default", "develop"):
lock_section = lockfile.get(section, {})
for... |
Returns a list of all packages. | def all_packages(self):
"""Returns a list of all packages."""
p = dict(self.parsed_pipfile.get("dev-packages", {}))
p.update(self.parsed_pipfile.get("packages", {}))
return p |
Creates the Pipfile, filled with juicy defaults. | def create_pipfile(self, python=None):
"""Creates the Pipfile, filled with juicy defaults."""
from .vendor.pip_shims.shims import (
ConfigOptionParser, make_option_group, index_group
)
config_parser = ConfigOptionParser(name=self.name)
config_parser.add_option_group(... |
Writes the given data structure out as TOML. | def write_toml(self, data, path=None):
"""Writes the given data structure out as TOML."""
if path is None:
path = self.pipfile_location
data = convert_toml_outline_tables(data)
try:
formatted_data = tomlkit.dumps(data).rstrip()
except Exception:
... |
Write out the lockfile. | def write_lockfile(self, content):
"""Write out the lockfile.
"""
s = self._lockfile_encoder.encode(content)
open_kwargs = {"newline": self._lockfile_newlines, "encoding": "utf-8"}
with vistir.contextmanagers.atomic_open_for_write(
self.lockfile_location, **open_kwarg... |
Given a source, find it.
source can be a url or an index name. | def find_source(self, source):
"""
Given a source, find it.
source can be a url or an index name.
"""
if not is_valid_url(source):
try:
source = self.get_source(name=source)
except SourceNotFound:
source = self.get_source(u... |
Get the equivalent package name in pipfile | def get_package_name_in_pipfile(self, package_name, dev=False):
"""Get the equivalent package name in pipfile"""
key = "dev-packages" if dev else "packages"
section = self.parsed_pipfile.get(key, {})
package_name = pep423_name(package_name)
for name in section.keys():
... |
Adds a given index to the Pipfile. | def add_index_to_pipfile(self, index, verify_ssl=True):
"""Adds a given index to the Pipfile."""
# Read and append Pipfile.
p = self.parsed_pipfile
try:
self.get_source(url=index)
except SourceNotFound:
source = {"url": index, "verify_ssl": verify_ssl}
... |
Ensures proper casing of Pipfile packages | def ensure_proper_casing(self):
"""Ensures proper casing of Pipfile packages"""
pfile = self.parsed_pipfile
casing_changed = self.proper_case_section(pfile.get("packages", {}))
casing_changed |= self.proper_case_section(pfile.get("dev-packages", {}))
return casing_changed |
Verify proper casing is retrieved, when available, for each
dependency in the section. | def proper_case_section(self, section):
"""Verify proper casing is retrieved, when available, for each
dependency in the section.
"""
# Casing for section.
changed_values = False
unknown_names = [k for k in section.keys() if k not in set(self.proper_names)]
# Repl... |
Return a native Python type from the list of compiled nodes. If the
result is a single node, its value is returned. Otherwise, the nodes are
concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise, the
string is returned. | def native_concat(nodes):
"""Return a native Python type from the list of compiled nodes. If the
result is a single node, its value is returned. Otherwise, the nodes are
concatenated as strings. If the result can be parsed with
:func:`ast.literal_eval`, the parsed value is returned. Otherwise, the
s... |
Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code. | def visit_Output(self, node, frame):
"""Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code.
"""
if self.has_known_extends and frame.require_output_check:
return
finalize = self.environment.finalize
fina... |
Clear all existing key:value items and import all key:value items from
<mapping>. If multiple values exist for the same key in <mapping>, they
are all be imported.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.load([(4,4), (4,44), (5,5)])
omd.al... | def load(self, *args, **kwargs):
"""
Clear all existing key:value items and import all key:value items from
<mapping>. If multiple values exist for the same key in <mapping>, they
are all be imported.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
... |
Update this dictionary with the items from <mapping>, replacing
existing key:value items with shared keys before adding new key:value
items.
Example:
omd = omdict([(1,1), (2,2)])
omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)])
omd.allitems() == [(1, 'one'),... | def updateall(self, *args, **kwargs):
"""
Update this dictionary with the items from <mapping>, replacing
existing key:value items with shared keys before adding new key:value
items.
Example:
omd = omdict([(1,1), (2,2)])
omd.updateall([(2,'two'), (1,'one'), (... |
<replacements and <leftovers> are modified directly, ala pass by
reference. | def _bin_update_items(self, items, replace_at_most_one,
replacements, leftovers):
"""
<replacements and <leftovers> are modified directly, ala pass by
reference.
"""
for key, value in items:
# If there are existing items with key <key> that h... |
Returns: The list of values for <key> if <key> is in the dictionary,
else <default>. If <default> is not provided, an empty list is
returned. | def getlist(self, key, default=[]):
"""
Returns: The list of values for <key> if <key> is in the dictionary,
else <default>. If <default> is not provided, an empty list is
returned.
"""
if key in self:
return [node.value for node in self._map[key]]
ret... |
Similar to setdefault() except <defaultlist> is a list of values to set
for <key>. If <key> already exists, its existing list of values is
returned.
If <key> isn't a key and <defaultlist> is an empty list, [], no values
are added for <key> and <key> will not be added as a key.
... | def setdefaultlist(self, key, defaultlist=[None]):
"""
Similar to setdefault() except <defaultlist> is a list of values to set
for <key>. If <key> already exists, its existing list of values is
returned.
If <key> isn't a key and <defaultlist> is an empty list, [], no values
... |
Add the values in <valuelist> to the list of values for <key>. If <key>
is not in the dictionary, the values in <valuelist> become the values
for <key>.
Example:
omd = omdict([(1,1)])
omd.addlist(1, [11, 111])
omd.allitems() == [(1, 1), (1, 11), (1, 111)]
... | def addlist(self, key, valuelist=[]):
"""
Add the values in <valuelist> to the list of values for <key>. If <key>
is not in the dictionary, the values in <valuelist> become the values
for <key>.
Example:
omd = omdict([(1,1)])
omd.addlist(1, [11, 111])
... |
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't have corresponding items with <key>
to repl... | def setlist(self, key, values):
"""
Sets <key>'s list of values to <values>. Existing items with key <key>
are first replaced with new values from <values>. Any remaining old
items that haven't been replaced with new values are deleted, and any
new values from <values> that don't... |
Removes all <values> from the values of <key>. If <key> has no
remaining values after removevalues(), the key is popped.
Example:
omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)])
omd.removevalues(1, [1, 111])
omd.allitems() == [(1, 11)]
Returns: <self>. | def removevalues(self, key, values):
"""
Removes all <values> from the values of <key>. If <key> has no
remaining values after removevalues(), the key is popped.
Example:
omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)])
omd.removevalues(1, [1, 111])
omd.al... |
If <key> is in the dictionary, pop it and return its list of values. If
<key> is not in the dictionary, return <default>. KeyError is raised if
<default> is not provided and <key> is not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.pop... | def poplist(self, key, default=_absent):
"""
If <key> is in the dictionary, pop it and return its list of values. If
<key> is not in the dictionary, return <default>. KeyError is raised if
<default> is not provided and <key> is not in the dictionary.
Example:
omd = omd... |
If <value> is provided, pops the first or last (key,value) item in the
dictionary if <key> is in the dictionary.
If <value> is not provided, pops the first or last value for <key> if
<key> is in the dictionary.
If <key> no longer has any values after a popvalue() call, <key> is
... | def popvalue(self, key, value=_absent, default=_absent, last=True):
"""
If <value> is provided, pops the first or last (key,value) item in the
dictionary if <key> is in the dictionary.
If <value> is not provided, pops the first or last value for <key> if
<key> is in the dictiona... |
Pop and return a key:value item.
If <fromall> is False, items()[0] is popped if <last> is False or
items()[-1] is popped if <last> is True. All remaining items with the
same key are removed.
If <fromall> is True, allitems()[0] is popped if <last> is False or
allitems()[-1] is p... | def popitem(self, fromall=False, last=True):
"""
Pop and return a key:value item.
If <fromall> is False, items()[0] is popped if <last> is False or
items()[-1] is popped if <last> is True. All remaining items with the
same key are removed.
If <fromall> is True, allitems... |
Pop and return a key:valuelist item comprised of a key and that key's
list of values. If <last> is False, a key:valuelist item comprised of
keys()[0] and its list of values is popped and returned. If <last> is
True, a key:valuelist item comprised of keys()[-1] and its list of
values is p... | def poplistitem(self, last=True):
"""
Pop and return a key:valuelist item comprised of a key and that key's
list of values. If <last> is False, a key:valuelist item comprised of
keys()[0] and its list of values is popped and returned. If <last> is
True, a key:valuelist item compr... |
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned. | def values(self, key=_absent):
"""
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
"""
if key is not _... |
Parity with dict.iteritems() except the optional <key> parameter has
been added. If <key> is provided, only items with the provided key are
iterated over. KeyError is raised if <key> is provided and not in the
dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (... | def iteritems(self, key=_absent):
"""
Parity with dict.iteritems() except the optional <key> parameter has
been added. If <key> is provided, only items with the provided key are
iterated over. KeyError is raised if <key> is provided and not in the
dictionary.
Example:
... |
Parity with dict.itervalues() except the optional <key> parameter has
been added. If <key> is provided, only values from items with the
provided key are iterated over. KeyError is raised if <key> is provided
and not in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,1... | def itervalues(self, key=_absent):
"""
Parity with dict.itervalues() except the optional <key> parameter has
been added. If <key> is provided, only values from items with the
provided key are iterated over. KeyError is raised if <key> is provided
and not in the dictionary.
... |
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3)
omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111)
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: An iterator over eve... | def iterallitems(self, key=_absent):
'''
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3)
omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111)
Raises: KeyError if <key> is provided and not... |
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3
Returns: An iterator over the values of every item in the dictionary. | def iterallvalues(self, key=_absent):
'''
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3
Returns: An iterator over the values of every item in the dictionary.
'''
if key is not _absent:
... |
Reverse the order of all items in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.reverse()
omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]
Returns: <self>. | def reverse(self):
"""
Reverse the order of all items in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.reverse()
omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]
Returns: <self>.
"""
for key in si... |
Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs | def check_requirements(self, reqs):
# type: (Iterable[str]) -> Tuple[Set[Tuple[str, str]], Set[str]]
"""Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = ... |
Given an iterable of arguments and an iterable of nargs specifications,
it returns a tuple with all the unpacked arguments at the first index
and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed
or `-1` to indicate that this position shou... | def _unpack_args(args, nargs_spec):
"""Given an iterable of arguments and an iterable of nargs specifications,
it returns a tuple with all the unpacked arguments at the first index
and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed
... |
Given an argument string this attempts to split it into small parts. | def split_arg_string(string):
"""Given an argument string this attempts to split it into small parts."""
rv = []
for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
r'|"([^"\\]*(?:\\.[^"\\]*)*)"'
r'|\S+)\s*', string, re.S):
arg = match.gr... |
Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
``append``, ``appnd_const`` or ``count``.
The `obj` can be used to identify the option in the orde... | def add_option(self, opts, dest, action=None, nargs=1, const=None,
obj=None):
"""Adds a new option named `dest` to the parser. The destination
is not inferred (unlike with optparse) and needs to be explicitly
provided. Action can be any of ``store``, ``store_const``,
... |
Adds a positional argument named `dest` to the parser.
The `obj` can be used to identify the option in the order list
that is returned from the parser. | def add_argument(self, dest, nargs=1, obj=None):
"""Adds a positional argument named `dest` to the parser.
The `obj` can be used to identify the option in the order list
that is returned from the parser.
"""
if obj is None:
obj = dest
self._args.append(Argume... |
Parses positional arguments and returns ``(values, args, order)``
for the parsed options and arguments as well as the leftover
arguments if there are any. The order is a list of objects as they
appear on the command line. If arguments appear multiple times they
will be memorized multip... | def parse_args(self, args):
"""Parses positional arguments and returns ``(values, args, order)``
for the parsed options and arguments as well as the leftover
arguments if there are any. The order is a list of objects as they
appear on the command line. If arguments appear multiple time... |
Makes a dependency graph from the given distributions.
:parameter dists: a list of distributions
:type dists: list of :class:`distutils2.database.InstalledDistribution` and
:class:`distutils2.database.EggInfoDistribution` instances
:rtype: a :class:`DependencyGraph` instance | def make_graph(dists, scheme='default'):
"""Makes a dependency graph from the given distributions.
:parameter dists: a list of distributions
:type dists: list of :class:`distutils2.database.InstalledDistribution` and
:class:`distutils2.database.EggInfoDistribution` instances
:rtype: a ... |
Recursively generate a list of distributions from *dists* that are
dependent on *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested | def get_dependent_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
dependent on *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibExcept... |
Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested | def get_required_dists(dists, dist):
"""Recursively generate a list of distributions from *dists* that are
required by *dist*.
:param dists: a list of distributions
:param dist: a distribution, member of *dists* for which we are interested
"""
if dist not in dists:
raise DistlibExceptio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.