desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.
The optional `verbose` argument controls how detailed the
summary is. If the verbosity is not specified, then th... | def summarize(self, verbose=None):
| if (verbose is None):
verbose = self._verbose
notests = []
passed = []
failed = []
totalt = totalf = 0
for x in self._name2ft.items():
(name, (f, t)) = x
assert (f <= t)
totalt += t
totalf += f
if (t == 0):
notests.append(name)
... |
'Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See the
documentation for `TestRunner` for ... | def check_output(self, want, got, optionflags):
| if (got == want):
return True
if (not (optionflags & DONT_ACCEPT_TRUE_FOR_1)):
if ((got, want) == ('True\n', '1\n')):
return True
if ((got, want) == ('False\n', '0\n')):
return True
if (not (optionflags & DONT_ACCEPT_BLANKLINE)):
want = re.sub(('(?m)^%... |
'Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.'
| def output_difference(self, example, got, optionflags):
| want = example.want
if (not (optionflags & DONT_ACCEPT_BLANKLINE)):
got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
if self._do_a_fancy_diff(want, got, optionflags):
want_lines = want.splitlines(True)
got_lines = got.splitlines(True)
if (optionflags & REPORT_UDIFF):... |
'Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
T... | def debug(self):
| self.setUp()
runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False)
runner.run(self._dt_test)
self.tearDown()
|
'val -> _TestClass object with associated value val.
>>> t = _TestClass(123)
>>> print t.get()
123'
| def __init__(self, val):
| self.val = val
|
'square() -> square TestClass\'s associated value
>>> _TestClass(13).square().get()
169'
| def square(self):
| self.val = (self.val ** 2)
return self
|
'get() -> return TestClass\'s associated value.
>>> x = _TestClass(-42)
>>> print x.get()
-42'
| def get(self):
| return self.val
|
'a pth file manager should set dirty
if a distribution is in site but also the cwd'
| def test_add_from_cwd_site_sets_dirty(self):
| pth = PthDistributions('does-not_exist', [os.getcwd()])
self.assertTrue((not pth.dirty))
pth.add(PRDistribution(os.getcwd()))
self.assertTrue(pth.dirty)
|
'Regression test for Distribute issue #318
Ensure that a package with setup_requires can be installed when
setuptools is installed in the user site-packages without causing a
SandboxViolation.'
| def test_setup_requires(self):
| test_setup_attrs = {'name': 'test_pkg', 'version': '0.0', 'setup_requires': ['foobar'], 'dependency_links': [os.path.abspath(self.dir)]}
test_pkg = os.path.join(self.dir, 'test_pkg')
test_setup_py = os.path.join(test_pkg, 'setup.py')
os.mkdir(test_pkg)
f = open(test_setup_py, 'w')
f.write(textwr... |
'When easy_install installs a source distribution which specifies
setup_requires, it should honor the fetch parameters (such as
allow-hosts, index-url, and find-links).'
| def test_setup_requires_honors_fetch_params(self):
| p_index = setuptools.tests.server.MockServer()
p_index.start()
netloc = 1
p_index_loc = urlparse(p_index.url)[netloc]
if p_index_loc.endswith(':0'):
return
with TestSetupRequires.create_sdist() as dist_file:
with tempdir_context() as temp_install_dir:
with environment... |
'Return an sdist with a setup_requires dependency (of something that
doesn\'t exist)'
| @staticmethod
@contextlib.contextmanager
def create_sdist():
| with tempdir_context() as dir:
dist_path = os.path.join(dir, 'setuptools-test-fetcher-1.0.tar.gz')
make_trivial_sdist(dist_path, textwrap.dedent('\n import setuptools\n ... |
'Regression test for pull request #4: ensures that files listed in
package_data are included in the manifest even if they\'re not added to
version control.'
| def test_package_data_in_sdist(self):
| dist = Distribution(SETUP_ATTRS)
dist.script_name = 'setup.py'
cmd = sdist(dist)
cmd.ensure_finalized()
quiet()
try:
cmd.run()
finally:
unquiet()
manifest = cmd.filelist.files
self.assertTrue((os.path.join('sdist_test', 'a.txt') in manifest))
self.assertTrue((os.p... |
'Return full package/distribution name, w/version'
| def full_name(self):
| if (self.requested_version is not None):
return ('%s-%s' % (self.name, self.requested_version))
return self.name
|
'Is \'version\' sufficiently up-to-date?'
| def version_ok(self, version):
| return ((self.attribute is None) or (self.format is None) or ((str(version) != 'unknown') and (version >= self.requested_version)))
|
'Get version number of installed module, \'None\', or \'default\'
Search \'paths\' for module. If not found, return \'None\'. If found,
return the extracted version attribute, or \'default\' if no version
attribute was specified, or the value cannot be determined without
importing the module. The version is formatte... | def get_version(self, paths=None, default='unknown'):
| if (self.attribute is None):
try:
(f, p, i) = find_module(self.module, paths)
if f:
f.close()
return default
except ImportError:
return None
v = get_module_constant(self.module, self.attribute, default, paths)
if ((v is not None... |
'Return true if dependency is present on \'paths\''
| def is_present(self, paths=None):
| return (self.get_version(paths) is not None)
|
'Return true if dependency is present and up-to-date on \'paths\''
| def is_current(self, paths=None):
| version = self.get_version(paths)
if (version is None):
return False
return self.version_ok(version)
|
'Process features after parsing command line options'
| def parse_command_line(self):
| result = _Distribution.parse_command_line(self)
if self.features:
self._finalize_features()
return result
|
'Convert feature name to corresponding option attribute name'
| def _feature_attrname(self, name):
| return ('with_' + name.replace('-', '_'))
|
'Resolve pre-setup requirements'
| def fetch_build_eggs(self, requires):
| from pkg_resources import working_set, parse_requirements
for dist in working_set.resolve(parse_requirements(requires), installer=self.fetch_build_egg):
working_set.add(dist)
|
'Fetch an egg needed for building'
| def fetch_build_egg(self, req):
| try:
cmd = self._egg_fetcher
cmd.package_index.to_scan = []
except AttributeError:
from setuptools.command.easy_install import easy_install
dist = self.__class__({'script_args': ['easy_install']})
dist.parse_config_files()
opts = dist.get_option_dict('easy_install... |
'Add --with-X/--without-X options based on optional features'
| def _set_global_opts_from_features(self):
| go = []
no = self.negative_opt.copy()
for (name, feature) in self.features.items():
self._set_feature(name, None)
feature.validate(self)
if feature.optional:
descr = feature.description
incdef = ' (default)'
excdef = ''
if (not featu... |
'Add/remove features and resolve dependencies between them'
| def _finalize_features(self):
| for (name, feature) in self.features.items():
enabled = self.feature_is_included(name)
if (enabled or ((enabled is None) and feature.include_by_default())):
feature.include_in(self)
self._set_feature(name, 1)
for (name, feature) in self.features.items():
if (not s... |
'Pluggable version of get_command_class()'
| def get_command_class(self, command):
| if (command in self.cmdclass):
return self.cmdclass[command]
for ep in pkg_resources.iter_entry_points('distutils.commands', command):
ep.require(installer=self.fetch_build_egg)
self.cmdclass[command] = cmdclass = ep.load()
return cmdclass
else:
return _Distribution.g... |
'Set feature\'s inclusion status'
| def _set_feature(self, name, status):
| setattr(self, self._feature_attrname(name), status)
|
'Return 1 if feature is included, 0 if excluded, \'None\' if unknown'
| def feature_is_included(self, name):
| return getattr(self, self._feature_attrname(name))
|
'Request inclusion of feature named \'name\''
| def include_feature(self, name):
| if (self.feature_is_included(name) == 0):
descr = self.features[name].description
raise DistutilsOptionError((descr + ' is required, but was excluded or is not available'))
self.features[name].include_in(self)
self._set_feature(name, 1)
|
'Add items to distribution that are named in keyword arguments
For example, \'dist.exclude(py_modules=["x"])\' would add \'x\' to
the distribution\'s \'py_modules\' attribute, if it was not already
there.
Currently, this method only supports inclusion for attributes that are
lists or tuples. If you need to add support... | def include(self, **attrs):
| for (k, v) in attrs.items():
include = getattr(self, ('_include_' + k), None)
if include:
include(v)
else:
self._include_misc(k, v)
|
'Remove packages, modules, and extensions in named package'
| def exclude_package(self, package):
| pfx = (package + '.')
if self.packages:
self.packages = [p for p in self.packages if ((p != package) and (not p.startswith(pfx)))]
if self.py_modules:
self.py_modules = [p for p in self.py_modules if ((p != package) and (not p.startswith(pfx)))]
if self.ext_modules:
self.ext_modu... |
'Return true if \'exclude_package(package)\' would do something'
| def has_contents_for(self, package):
| pfx = (package + '.')
for p in self.iter_distribution_names():
if ((p == package) or p.startswith(pfx)):
return True
|
'Handle \'exclude()\' for list/tuple attrs without a special handler'
| def _exclude_misc(self, name, value):
| if (not isinstance(value, sequence)):
raise DistutilsSetupError(('%s: setting must be a list or tuple (%r)' % (name, value)))
try:
old = getattr(self, name)
except AttributeError:
raise DistutilsSetupError(('%s: No such distribution setting' % name... |
'Handle \'include()\' for list/tuple attrs without a special handler'
| def _include_misc(self, name, value):
| if (not isinstance(value, sequence)):
raise DistutilsSetupError(('%s: setting must be a list (%r)' % (name, value)))
try:
old = getattr(self, name)
except AttributeError:
raise DistutilsSetupError(('%s: No such distribution setting' % name))
if (old ... |
'Remove items from distribution that are named in keyword arguments
For example, \'dist.exclude(py_modules=["x"])\' would remove \'x\' from
the distribution\'s \'py_modules\' attribute. Excluding packages uses
the \'exclude_package()\' method, so all of the package\'s contained
packages, modules, and extensions are al... | def exclude(self, **attrs):
| for (k, v) in attrs.items():
exclude = getattr(self, ('_exclude_' + k), None)
if exclude:
exclude(v)
else:
self._exclude_misc(k, v)
|
'Return a \'{cmd: {opt:val}}\' map of all command-line options
Option names are all long, but do not include the leading \'--\', and
contain dashes rather than underscores. If the option doesn\'t take
an argument (e.g. \'--quiet\'), the \'val\' is \'None\'.
Note that options provided by config files are intentionally ... | def get_cmdline_options(self):
| d = {}
for (cmd, opts) in self.command_options.items():
for (opt, (src, val)) in opts.items():
if (src != 'command line'):
continue
opt = opt.replace('_', '-')
if (val == 0):
cmdobj = self.get_command_obj(cmd)
neg_opt... |
'Yield all packages, modules, and extension names in distribution'
| def iter_distribution_names(self):
| for pkg in (self.packages or ()):
(yield pkg)
for module in (self.py_modules or ()):
(yield module)
for ext in (self.ext_modules or ()):
if isinstance(ext, tuple):
(name, buildinfo) = ext
else:
name = ext.name
if name.endswith('module'):
... |
'If there were any non-global "display-only" options
(--help-commands or the metadata display options) on the command
line, display the requested info and return true; else return
false.'
| def handle_display_options(self, option_order):
| import sys
if ((sys.version_info < (3,)) or self.help_commands):
return _Distribution.handle_display_options(self, option_order)
import io
if (not isinstance(sys.stdout, io.TextIOWrapper)):
return _Distribution.handle_display_options(self, option_order)
if (sys.stdout.encoding.lower(... |
'Should this feature be included by default?'
| def include_by_default(self):
| return (self.available and self.standard)
|
'Ensure feature and its requirements are included in distribution
You may override this in a subclass to perform additional operations on
the distribution. Note that this method may be called more than once
per feature, and so should be idempotent.'
| def include_in(self, dist):
| if (not self.available):
raise DistutilsPlatformError((self.description + ' is required,but is not available on this platform'))
dist.include(**self.extras)
for f in self.require_features:
dist.include_feature(f)
|
'Ensure feature is excluded from distribution
You may override this in a subclass to perform additional operations on
the distribution. This method will be called at most once per
feature, and only after all included features have been asked to
include themselves.'
| def exclude_from(self, dist):
| dist.exclude(**self.extras)
if self.remove:
for item in self.remove:
dist.exclude_package(item)
|
'Verify that feature makes sense in context of distribution
This method is called by the distribution just before it parses its
command line. It checks to ensure that the \'remove\' attribute, if any,
contains only valid package/module names that are present in the base
distribution when \'setup()\' is called. You ma... | def validate(self, dist):
| for item in self.remove:
if (not dist.has_contents_for(item)):
raise DistutilsSetupError(("%s wants to be able to remove %s, but the distribution doesn't contain any packages or modules under %s" % (self.description, item, item)))
|
'Run \'func\' under os sandboxing'
| def run(self, func):
| try:
self._copy(self)
if _file:
builtins.file = self._file
builtins.open = self._open
self._active = True
return func()
finally:
self._active = False
if _file:
builtins.file = _file
builtins.open = _open
self._copy(_... |
'Called to remap or validate any path, whether input or output'
| def _validate_path(self, path):
| return path
|
'Called for path inputs'
| def _remap_input(self, operation, path, *args, **kw):
| return self._validate_path(path)
|
'Called for path outputs'
| def _remap_output(self, operation, path):
| return self._validate_path(path)
|
'Called for path pairs like rename, link, and symlink operations'
| def _remap_pair(self, operation, src, dst, *args, **kw):
| return (self._remap_input((operation + '-from'), src, *args, **kw), self._remap_input((operation + '-to'), dst, *args, **kw))
|
'Called for path inputs'
| def _remap_input(self, operation, path, *args, **kw):
| if ((operation in self.write_ops) and (not self._ok(path))):
self._violation(operation, os.path.realpath(path), *args, **kw)
return path
|
'Called for path pairs like rename, link, and symlink operations'
| def _remap_pair(self, operation, src, dst, *args, **kw):
| if ((not self._ok(src)) or (not self._ok(dst))):
self._violation(operation, src, dst, *args, **kw)
return (src, dst)
|
'Called for low-level os.open()'
| def open(self, file, flags, mode=511, *args, **kw):
| if ((flags & WRITE_FLAGS) and (not self._ok(file))):
self._violation('os.open', file, flags, mode, *args, **kw)
return _os.open(file, flags, mode, *args, **kw)
|
'convert .pyx extensions to .c'
| def _convert_pyx_sources_to_c(self):
| def pyx_to_c(source):
if source.endswith('.pyx'):
source = (source[:(-4)] + '.c')
return source
self.sources = list(map(pyx_to_c, self.sources))
|
'Feed a block of data to the hash.'
| def feed(self, block):
| return
|
'Check the hash. Return False if validation fails.'
| def is_valid(self):
| return True
|
'Call reporter with information about the checker (hash name)
substituted into the template.'
| def report(self, reporter, template):
| return
|
'Construct a (possibly null) ContentChecker from a URL'
| @classmethod
def from_url(cls, url):
| fragment = urlparse(url)[(-1)]
if (not fragment):
return ContentChecker()
match = cls.pattern.search(fragment)
if (not match):
return ContentChecker()
return cls(**match.groupdict())
|
'Evaluate a URL as a possible download, and maybe retrieve it'
| def process_url(self, url, retrieve=False):
| if ((url in self.scanned_urls) and (not retrieve)):
return
self.scanned_urls[url] = True
if (not URL_SCHEME(url)):
self.process_filename(url)
return
else:
dists = list(distros_for_url(url))
if dists:
if (not self.url_ok(url)):
return
... |
'Process the contents of a PyPI page'
| def process_index(self, url, page):
| def scan(link):
if link.startswith(self.index_url):
parts = list(map(unquote, link[len(self.index_url):].split('/')))
if ((len(parts) == 2) and ('#' not in parts[1])):
pkg = safe_name(parts[0])
ver = safe_version(parts[1])
self.package_... |
'checker is a ContentChecker'
| def check_hash(self, checker, filename, tfp):
| checker.report(self.debug, ('Validating %%s checksum for %s' % filename))
if (not checker.is_valid()):
tfp.close()
os.unlink(filename)
raise DistutilsError(('%s validation failed for %s; possible download problem?' % (checker.hash.name, os.path.basename(f... |
'Add `urls` to the list that will be prescanned for searches'
| def add_find_links(self, urls):
| for url in urls:
if ((self.to_scan is None) or (not URL_SCHEME(url)) or url.startswith('file:') or list(distros_for_url(url))):
self.scan_url(url)
else:
self.to_scan.append(url)
|
'Scan urls scheduled for prescanning (e.g. --find-links)'
| def prescan(self):
| if self.to_scan:
list(map(self.scan_url, self.to_scan))
self.to_scan = None
|
'Locate and/or download `spec` to `tmpdir`, returning a local path
`spec` may be a ``Requirement`` object, or a string containing a URL,
an existing local filename, or a project/version requirement spec
(i.e. the string form of a ``Requirement`` object). If it is the URL
of a .py file with an unambiguous ``#egg=name-v... | def download(self, spec, tmpdir):
| if (not isinstance(spec, Requirement)):
scheme = URL_SCHEME(spec)
if scheme:
found = self._download_url(scheme.group(1), spec, tmpdir)
(base, fragment) = egg_info_for_url(spec)
if base.endswith('.py'):
found = self.gen_setup(found, fragment, tmpdir... |
'Obtain a distribution suitable for fulfilling `requirement`
`requirement` must be a ``pkg_resources.Requirement`` instance.
If necessary, or if the `force_scan` flag is set, the requirement is
searched for in the (online) package index as well as the locally
installed packages. If a distribution matching `requirement... | def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None):
| self.info('Searching for %s', requirement)
skipped = {}
dist = None
def find(req, env=None):
if (env is None):
env = self
for dist in env[req.key]:
if ((dist.precedence == DEVELOP_DIST) and (not develop_ok)):
if (dist not in skipped):
... |
'Obtain a file suitable for fulfilling `requirement`
DEPRECATED; use the ``fetch_distribution()`` method now instead. For
backward compatibility, this routine is identical but returns the
``location`` of the downloaded distribution instead of a distribution
object.'
| def fetch(self, requirement, tmpdir, force_scan=False, source=False):
| dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
if (dist is not None):
return dist.location
return None
|
'Load from ~/.pypirc'
| def __init__(self):
| defaults = dict.fromkeys(['username', 'password', 'repository'], '')
ConfigParser.ConfigParser.__init__(self, defaults)
rc = os.path.join(os.path.expanduser('~'), '.pypirc')
if os.path.exists(rc):
self.read(rc)
|
'If the URL indicated appears to be a repository defined in this
config, return the credential for that repository.'
| def find_credential(self, url):
| for (repository, cred) in self.creds_by_repository.items():
if url.startswith(repository):
return cred
|
'Ensure statement only contains allowed nodes.'
| def visit(self, node):
| if (not isinstance(node, self.ALLOWED)):
raise SyntaxError(('Not allowed in environment markers.\n%s\n%s' % (self.statement, ((' ' * node.col_offset) + '^'))))
return ast.NodeTransformer.visit(self, node)
|
'Flatten one level of attribute access.'
| def visit_Attribute(self, node):
| new_node = ast.Name(('%s.%s' % (node.value.id, node.attr)), node.ctx)
return ast.copy_location(new_node, node)
|
'Create a UUID from either a string of 32 hexadecimal digits,
a string of 16 bytes as the \'bytes\' argument, a string of 16 bytes
in little-endian order as the \'bytes_le\' argument, a tuple of six
integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-b... | def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None):
| if ([hex, bytes, bytes_le, fields, int].count(None) != 4):
raise TypeError('need one of hex, bytes, bytes_le, fields, or int')
if (hex is not None):
hex = hex.replace('urn:', '').replace('uuid:', '')
hex = hex.strip('{}').replace('-', '')
if (len(hex) != 3... |
'Create a new completer for the command line.
Completer([namespace]) -> completer instance.
If unspecified, the default namespace where completions are performed
is __main__ (technically, __main__.__dict__). Namespaces should be
given as dictionaries.
Completer instances should be used as the completion mechanism of
re... | def __init__(self, namespace=None):
| if (namespace and (not isinstance(namespace, dict))):
raise TypeError('namespace must be a dictionary')
if (namespace is None):
self.use_main_ns = 1
else:
self.use_main_ns = 0
self.namespace = namespace
|
'Return the next possible completion for \'text\'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with \'text\'.'
| def complete(self, text, state):
| if self.use_main_ns:
self.namespace = __main__.__dict__
if (state == 0):
if ('.' in text):
self.matches = self.attr_matches(text)
else:
self.matches = self.global_matches(text)
try:
return self.matches[state]
except IndexError:
return None
|
'Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match.'
| def global_matches(self, text):
| import keyword
matches = []
n = len(text)
for word in keyword.kwlist:
if (word[:n] == text):
matches.append(word)
for nspace in [builtins.__dict__, self.namespace]:
for (word, val) in nspace.items():
if ((word[:n] == text) and (word != '__builtins__')):
... |
'Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluable in self.namespace, it will be evaluated and its attributes
(as revealed by dir()) are used as possible completions. (For class
instances, class members are also considered.)
WARNING: this can still invoke ... | def attr_matches(self, text):
| import re
m = re.match('(\\w+(\\.\\w+)*)\\.(\\w*)', text)
if (not m):
return []
(expr, attr) = m.group(1, 3)
try:
thisobject = eval(expr, self.namespace)
except Exception:
return []
words = dir(thisobject)
if ('__builtins__' in words):
words.remove('__buil... |
'Open a bzip2-compressed file.
If filename is a str or bytes object, it gives the name
of the file to be opened. Otherwise, it should be a file object,
which will be used to read or write the compressed data.
mode can be \'r\' for reading (default), \'w\' for (over)writing,
\'x\' for creating exclusively, or \'a\' for ... | def __init__(self, filename, mode='r', buffering=None, compresslevel=9):
| self._lock = RLock()
self._fp = None
self._closefp = False
self._mode = _MODE_CLOSED
self._pos = 0
self._size = (-1)
if (buffering is not None):
warnings.warn("Use of 'buffering' argument is deprecated", DeprecationWarning)
if (not (1 <= compresslevel <= 9)):
... |
'Flush and close the file.
May be called more than once without error. Once the file is
closed, any other operation on it will raise a ValueError.'
| def close(self):
| with self._lock:
if (self._mode == _MODE_CLOSED):
return
try:
if (self._mode in (_MODE_READ, _MODE_READ_EOF)):
self._decompressor = None
elif (self._mode == _MODE_WRITE):
self._fp.write(self._compressor.flush())
self... |
'True if this file is closed.'
| @property
def closed(self):
| return (self._mode == _MODE_CLOSED)
|
'Return the file descriptor for the underlying file.'
| def fileno(self):
| self._check_not_closed()
return self._fp.fileno()
|
'Return whether the file supports seeking.'
| def seekable(self):
| return (self.readable() and self._fp.seekable())
|
'Return whether the file was opened for reading.'
| def readable(self):
| self._check_not_closed()
return (self._mode in (_MODE_READ, _MODE_READ_EOF))
|
'Return whether the file was opened for writing.'
| def writable(self):
| self._check_not_closed()
return (self._mode == _MODE_WRITE)
|
'Return buffered data without advancing the file position.
Always returns at least one byte of data, unless at EOF.
The exact number of bytes returned is unspecified.'
| def peek(self, n=0):
| with self._lock:
self._check_can_read()
if (not self._fill_buffer()):
return ''
return self._buffer[self._buffer_offset:]
|
'Read up to size uncompressed bytes from the file.
If size is negative or omitted, read until EOF is reached.
Returns b\'\' if the file is already at EOF.'
| def read(self, size=(-1)):
| with self._lock:
self._check_can_read()
if (size == 0):
return ''
elif (size < 0):
return self._read_all()
else:
return self._read_block(size)
|
'Read up to size uncompressed bytes, while trying to avoid
making multiple reads from the underlying stream.
Returns b\'\' if the file is at EOF.'
| def read1(self, size=(-1)):
| with self._lock:
self._check_can_read()
if ((size == 0) or ((self._buffer_offset == len(self._buffer)) and (not self._fill_buffer()))):
return ''
if (size > 0):
data = self._buffer[self._buffer_offset:(self._buffer_offset + size)]
self._buffer_offset += le... |
'Read up to len(b) bytes into b.
Returns the number of bytes read (0 for EOF).'
| def readinto(self, b):
| with self._lock:
return io.BufferedIOBase.readinto(self, b)
|
'Read a line of uncompressed bytes from the file.
The terminating newline (if present) is retained. If size is
non-negative, no more than size bytes will be read (in which
case the line may be incomplete). Returns b\'\' if already at EOF.'
| def readline(self, size=(-1)):
| if (not isinstance(size, int)):
if (not hasattr(size, '__index__')):
raise TypeError('Integer argument expected')
size = size.__index__()
with self._lock:
self._check_can_read()
if (size < 0):
end = (self._buffer.find('\n', self._buffer_offset) + 1)
... |
'Read a list of lines of uncompressed bytes from the file.
size can be specified to control the number of lines read: no
further lines will be read once the total size of the lines read
so far equals or exceeds size.'
| def readlines(self, size=(-1)):
| if (not isinstance(size, int)):
if (not hasattr(size, '__index__')):
raise TypeError('Integer argument expected')
size = size.__index__()
with self._lock:
return io.BufferedIOBase.readlines(self, size)
|
'Write a byte string to the file.
Returns the number of uncompressed bytes written, which is
always len(data). Note that due to buffering, the file on disk
may not reflect the data written until close() is called.'
| def write(self, data):
| with self._lock:
self._check_can_write()
compressed = self._compressor.compress(data)
self._fp.write(compressed)
self._pos += len(data)
return len(data)
|
'Write a sequence of byte strings to the file.
Returns the number of uncompressed bytes written.
seq can be any iterable yielding byte strings.
Line separators are not added between the written byte strings.'
| def writelines(self, seq):
| with self._lock:
return io.BufferedIOBase.writelines(self, seq)
|
'Change the file position.
The new position is specified by offset, relative to the
position indicated by whence. Values for whence are:
0: start of stream (default); offset must not be negative
1: current stream position
2: end of stream; offset must not be positive
Returns the new file position.
Note that seeking is ... | def seek(self, offset, whence=0):
| with self._lock:
self._check_can_seek()
if (whence == 0):
pass
elif (whence == 1):
offset = (self._pos + offset)
elif (whence == 2):
if (self._size < 0):
self._read_all(return_data=False)
offset = (self._size + offset)
... |
'Return the current file position.'
| def tell(self):
| with self._lock:
self._check_not_closed()
return self._pos
|
'Compile a command and determine whether it is incomplete.
Arguments:
source -- the source string; may contain \n characters
filename -- optional filename from which source was read;
default "<input>"
symbol -- optional grammar start symbol; "single" (default) or
"eval"
Return value / exceptions raised:
- Return a code... | def __call__(self, source, filename='<input>', symbol='single'):
| return _maybe_compile(self.compiler, source, filename, symbol)
|
'Returns a dialect (or None) corresponding to the sample'
| def sniff(self, sample, delimiters=None):
| (quotechar, doublequote, delimiter, skipinitialspace) = self._guess_quote_and_delimiter(sample, delimiters)
if (not delimiter):
(delimiter, skipinitialspace) = self._guess_delimiter(sample, delimiters)
if (not delimiter):
raise Error('Could not determine delimiter')
class dialec... |
'Looks for text enclosed between two identical quotes
(the probable quotechar) which are preceded and followed
by the same character (the probable delimiter).
For example:
,\'some text\',
The quote with the most wins, same with the delimiter.
If there is no quotechar the delimiter can\'t be determined
this way.'
| def _guess_quote_and_delimiter(self, data, delimiters):
| matches = []
for restr in ('(?P<delim>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?P<delim>[^\\w\n"\'])(?P<space> ?)', '(?P<delim>>[^\\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?:$|\n)', '(?:^|\n)(?P<quote>["\']).*?(?P=quote)(?:$|\n... |
'The delimiter /should/ occur the same number of times on
each row. However, due to malformed data, it may not. We don\'t want
an all or nothing approach, so we allow for small variations in this
number.
1) build a table of the frequency of each character on every line.
2) build a table of frequencies of this frequency... | def _guess_delimiter(self, data, delimiters):
| data = list(filter(None, data.split('\n')))
ascii = [chr(c) for c in range(127)]
chunkLength = min(10, len(data))
iteration = 0
charFrequency = {}
modes = {}
delims = {}
(start, end) = (0, min(chunkLength, len(data)))
while (start < len(data)):
iteration += 1
for line... |
'Initialize a new instance, passing the time and delay
functions'
| def __init__(self, timefunc=_time, delayfunc=time.sleep):
| self._queue = []
self._lock = threading.RLock()
self.timefunc = timefunc
self.delayfunc = delayfunc
|
'Enter a new event in the queue at an absolute time.
Returns an ID for the event which can be used to remove it,
if necessary.'
| def enterabs(self, time, priority, action, argument=(), kwargs=_sentinel):
| if (kwargs is _sentinel):
kwargs = {}
event = Event(time, priority, action, argument, kwargs)
with self._lock:
heapq.heappush(self._queue, event)
return event
|
'A variant that specifies the time as a relative time.
This is actually the more commonly used interface.'
| def enter(self, delay, priority, action, argument=(), kwargs=_sentinel):
| time = (self.timefunc() + delay)
return self.enterabs(time, priority, action, argument, kwargs)
|
'Remove an event from the queue.
This must be presented the ID as returned by enter().
If the event is not in the queue, this raises ValueError.'
| def cancel(self, event):
| with self._lock:
self._queue.remove(event)
heapq.heapify(self._queue)
|
'Check whether the queue is empty.'
| def empty(self):
| with self._lock:
return (not self._queue)
|
'Execute events until the queue is empty.
If blocking is False executes the scheduled events due to
expire soonest (if any) and then return the deadline of the
next scheduled call in the scheduler.
When there is a positive delay until the first event, the
delay function is called and the event is left in the queue;
oth... | def run(self, blocking=True):
| lock = self._lock
q = self._queue
delayfunc = self.delayfunc
timefunc = self.timefunc
pop = heapq.heappop
while True:
with lock:
if (not q):
break
(time, priority, action, argument, kwargs) = q[0]
now = timefunc()
if (time >... |
'An ordered list of upcoming events.
Events are named tuples with fields for:
time, priority, action, arguments, kwargs'
| @property
def queue(self):
| with self._lock:
events = self._queue[:]
return list(map(heapq.heappop, ([events] * len(events))))
|
'Return the name (ID) of the current chunk.'
| def getname(self):
| return self.chunkname
|
'Return the size of the current chunk.'
| def getsize(self):
| return self.chunksize
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.