desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Preconditions:
- our agent applies to this entry
- filename is URL decoded'
| def allowance(self, filename):
| for line in self.rulelines:
if line.applies_to(filename):
return line.allowance
return True
|
'Initializes a new ThreadPoolExecutor instance.
Args:
max_workers: The maximum number of threads that can be used to
execute the given calls.'
| def __init__(self, max_workers):
| self._max_workers = max_workers
self._work_queue = queue.Queue()
self._threads = set()
self._shutdown = False
self._shutdown_lock = threading.Lock()
|
'Initializes a new ProcessPoolExecutor instance.
Args:
max_workers: The maximum number of processes that can be used to
execute the given calls. If None or not given then as many
worker processes will be created as the machine has processors.'
| def __init__(self, max_workers=None):
| _check_system_limits()
if (max_workers is None):
self._max_workers = (os.cpu_count() or 1)
else:
self._max_workers = max_workers
self._call_queue = multiprocessing.Queue((self._max_workers + EXTRA_QUEUED_CALLS))
self._call_queue._ignore_epipe = True
self._result_queue = SimpleQue... |
'Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary.'
| def __init__(self, *args, **kwds):
| if (len(args) > 1):
raise TypeError(('expected at most 1 arguments, got %d' % len(args)))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map =... |
'od.__setitem__(i, y) <==> od[i]=y'
| def __setitem__(self, key, value, dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
| if (key not in self):
self.__map[key] = link = Link()
root = self.__root
last = root.prev
(link.prev, link.next, link.key) = (last, root, key)
last.next = link
root.prev = proxy(link)
dict_setitem(self, key, value)
|
'od.__delitem__(y) <==> del od[y]'
| def __delitem__(self, key, dict_delitem=dict.__delitem__):
| dict_delitem(self, key)
link = self.__map.pop(key)
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
|
'od.__iter__() <==> iter(od)'
| def __iter__(self):
| root = self.__root
curr = root.next
while (curr is not root):
(yield curr.key)
curr = curr.next
|
'od.__reversed__() <==> reversed(od)'
| def __reversed__(self):
| root = self.__root
curr = root.prev
while (curr is not root):
(yield curr.key)
curr = curr.prev
|
'od.clear() -> None. Remove all items from od.'
| def clear(self):
| root = self.__root
root.prev = root.next = root
self.__map.clear()
dict.clear(self)
|
'od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.'
| def popitem(self, last=True):
| if (not self):
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
else:
link = root.next
link_next = link.next
root.next = link_next
... |
'Move an existing element to the end (or beginning if last==False).
Raises KeyError if the element does not exist.
When last=True, acts like a fast version of self[key]=self.pop(key).'
| def move_to_end(self, key, last=True):
| link = self.__map[key]
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
root = self.__root
if last:
last = root.prev
link.prev = last
link.next = root
last.next = root.prev = link
else:
first = root.... |
'od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.'
| def pop(self, key, default=__marker):
| if (key in self):
result = self[key]
del self[key]
return result
if (default is self.__marker):
raise KeyError(key)
return default
|
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
| def setdefault(self, key, default=None):
| if (key in self):
return self[key]
self[key] = default
return default
|
'od.__repr__() <==> repr(od)'
| @_recursive_repr()
def __repr__(self):
| if (not self):
return ('%s()' % (self.__class__.__name__,))
return ('%s(%r)' % (self.__class__.__name__, list(self.items())))
|
'Return state information for pickling'
| def __reduce__(self):
| inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
return (self.__class__, (), (inst_dict or None), None, iter(self.items()))
|
'od.copy() -> a shallow copy of od'
| def copy(self):
| return self.__class__(self)
|
'OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.'
| @classmethod
def fromkeys(cls, iterable, value=None):
| self = cls()
for key in iterable:
self[key] = value
return self
|
'od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.'
| def __eq__(self, other):
| if isinstance(other, OrderedDict):
return (dict.__eq__(self, other) and all(map(_eq, self, other)))
return dict.__eq__(self, other)
|
'Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter(\'gallahad\') # a new counter from an iterable
>>> c =... | def __init__(self, iterable=None, **kwds):
| super().__init__()
self.update(iterable, **kwds)
|
'The count of elements not in the Counter is zero.'
| def __missing__(self, key):
| return 0
|
'List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter(\'abcdeabcdabcaba\').most_common(3)
[(\'a\', 5), (\'b\', 4), (\'c\', 3)]'
| def most_common(self, n=None):
| if (n is None):
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
|
'Iterator over elements repeating each as many times as its count.
>>> c = Counter(\'ABCABC\')
>>> sorted(c.elements())
[\'A\', \'A\', \'B\', \'B\', \'C\', \'C\']
# Knuth\'s example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_f... | def elements(self):
| return _chain.from_iterable(_starmap(_repeat, self.items()))
|
'Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter(\'which\')
>>> c.update(\'witch\') # add elements from another iterable
>>> d = Counter(\'watch\')
>>> c.update(d) # add elements from another cou... | def update(self, iterable=None, **kwds):
| if (iterable is not None):
if isinstance(iterable, Mapping):
if self:
self_get = self.get
for (elem, count) in iterable.items():
self[elem] = (count + self_get(elem, 0))
else:
super().update(iterable)
else:
... |
'Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter(\'which\')
>>> c.subtract(\'witch\') # sub... | def subtract(self, iterable=None, **kwds):
| if (iterable is not None):
self_get = self.get
if isinstance(iterable, Mapping):
for (elem, count) in iterable.items():
self[elem] = (self_get(elem, 0) - count)
else:
for elem in iterable:
self[elem] = (self_get(elem, 0) - 1)
if kwd... |
'Return a shallow copy.'
| def copy(self):
| return self.__class__(self)
|
'Like dict.__delitem__() but does not raise KeyError for missing values.'
| def __delitem__(self, elem):
| if (elem in self):
super().__delitem__(elem)
|
'Add counts from two counters.
>>> Counter(\'abbb\') + Counter(\'bcc\')
Counter({\'b\': 4, \'c\': 2, \'a\': 1})'
| def __add__(self, other):
| if (not isinstance(other, Counter)):
return NotImplemented
result = Counter()
for (elem, count) in self.items():
newcount = (count + other[elem])
if (newcount > 0):
result[elem] = newcount
for (elem, count) in other.items():
if ((elem not in self) and (count >... |
'Subtract count, but keep only results with positive counts.
>>> Counter(\'abbbc\') - Counter(\'bccd\')
Counter({\'b\': 2, \'a\': 1})'
| def __sub__(self, other):
| if (not isinstance(other, Counter)):
return NotImplemented
result = Counter()
for (elem, count) in self.items():
newcount = (count - other[elem])
if (newcount > 0):
result[elem] = newcount
for (elem, count) in other.items():
if ((elem not in self) and (count <... |
'Union is the maximum of value in either of the input counters.
>>> Counter(\'abbb\') | Counter(\'bcc\')
Counter({\'b\': 3, \'c\': 2, \'a\': 1})'
| def __or__(self, other):
| if (not isinstance(other, Counter)):
return NotImplemented
result = Counter()
for (elem, count) in self.items():
other_count = other[elem]
newcount = (other_count if (count < other_count) else count)
if (newcount > 0):
result[elem] = newcount
for (elem, count)... |
'Intersection is the minimum of corresponding counts.
>>> Counter(\'abbb\') & Counter(\'bcc\')
Counter({\'b\': 1})'
| def __and__(self, other):
| if (not isinstance(other, Counter)):
return NotImplemented
result = Counter()
for (elem, count) in self.items():
other_count = other[elem]
newcount = (count if (count < other_count) else other_count)
if (newcount > 0):
result[elem] = newcount
return result
|
'Adds an empty counter, effectively stripping negative and zero counts'
| def __pos__(self):
| return (self + Counter())
|
'Subtracts from an empty counter. Strips positive and zero counts,
and flips the sign on negative counts.'
| def __neg__(self):
| return (Counter() - self)
|
'Internal method to strip elements with a negative or zero count'
| def _keep_positive(self):
| nonpositive = [elem for (elem, count) in self.items() if (not (count > 0))]
for elem in nonpositive:
del self[elem]
return self
|
'Inplace add from another counter, keeping only positive counts.
>>> c = Counter(\'abbb\')
>>> c += Counter(\'bcc\')
>>> c
Counter({\'b\': 4, \'c\': 2, \'a\': 1})'
| def __iadd__(self, other):
| for (elem, count) in other.items():
self[elem] += count
return self._keep_positive()
|
'Inplace subtract counter, but keep only results with positive counts.
>>> c = Counter(\'abbbc\')
>>> c -= Counter(\'bccd\')
>>> c
Counter({\'b\': 2, \'a\': 1})'
| def __isub__(self, other):
| for (elem, count) in other.items():
self[elem] -= count
return self._keep_positive()
|
'Inplace union is the maximum of value from either counter.
>>> c = Counter(\'abbb\')
>>> c |= Counter(\'bcc\')
>>> c
Counter({\'b\': 3, \'c\': 2, \'a\': 1})'
| def __ior__(self, other):
| for (elem, other_count) in other.items():
count = self[elem]
if (other_count > count):
self[elem] = other_count
return self._keep_positive()
|
'Inplace intersection is the minimum of corresponding counts.
>>> c = Counter(\'abbb\')
>>> c &= Counter(\'bcc\')
>>> c
Counter({\'b\': 1})'
| def __iand__(self, other):
| for (elem, count) in self.items():
other_count = other[elem]
if (other_count < count):
self[elem] = other_count
return self._keep_positive()
|
'Initialize a ChainMap by setting *maps* to the given mappings.
If no mappings are provided, a single empty dictionary is used.'
| def __init__(self, *maps):
| self.maps = (list(maps) or [{}])
|
'Create a ChainMap with a single dict created from the iterable.'
| @classmethod
def fromkeys(cls, iterable, *args):
| return cls(dict.fromkeys(iterable, *args))
|
'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
| def copy(self):
| return self.__class__(self.maps[0].copy(), *self.maps[1:])
|
'New ChainMap with a new map followed by all previous maps. If no
map is provided, an empty dict is used.'
| def new_child(self, m=None):
| if (m is None):
m = {}
return self.__class__(m, *self.maps)
|
'New ChainMap from maps[1:].'
| @property
def parents(self):
| return self.__class__(*self.maps[1:])
|
'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
| def popitem(self):
| try:
return self.maps[0].popitem()
except KeyError:
raise KeyError('No keys found in the first mapping.')
|
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
| def pop(self, key, *args):
| try:
return self.maps[0].pop(key, *args)
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key))
|
'Clear maps[0], leaving maps[1:] intact.'
| def clear(self):
| self.maps[0].clear()
|
'Send user name, return response
(should indicate password required).'
| def user(self, user):
| return self._shortcmd(('USER %s' % user))
|
'Send password, return response
(response includes message count, mailbox size).
NB: mailbox is locked by server from here to \'quit()\''
| def pass_(self, pswd):
| return self._shortcmd(('PASS %s' % pswd))
|
'Get mailbox status.
Result is tuple of 2 ints (message count, mailbox size)'
| def stat(self):
| retval = self._shortcmd('STAT')
rets = retval.split()
if self._debugging:
print ('*stat*', repr(rets))
numMessages = int(rets[1])
sizeMessages = int(rets[2])
return (numMessages, sizeMessages)
|
'Request listing, return result.
Result without a message number argument is in form
[\'response\', [\'mesg_num octets\', ...], octets].
Result when a message number argument is given is a
single response: the "scan listing" for that message.'
| def list(self, which=None):
| if (which is not None):
return self._shortcmd(('LIST %s' % which))
return self._longcmd('LIST')
|
'Retrieve whole message number \'which\'.
Result is in form [\'response\', [\'line\', ...], octets].'
| def retr(self, which):
| return self._longcmd(('RETR %s' % which))
|
'Delete message number \'which\'.
Result is \'response\'.'
| def dele(self, which):
| return self._shortcmd(('DELE %s' % which))
|
'Does nothing.
One supposes the response indicates the server is alive.'
| def noop(self):
| return self._shortcmd('NOOP')
|
'Unmark all messages marked for deletion.'
| def rset(self):
| return self._shortcmd('RSET')
|
'Signoff: commit changes on server, unlock mailbox, close connection.'
| def quit(self):
| resp = self._shortcmd('QUIT')
self.close()
return resp
|
'Close the connection without assuming anything about it.'
| def close(self):
| if (self.file is not None):
self.file.close()
if (self.sock is not None):
try:
self.sock.shutdown(socket.SHUT_RDWR)
except OSError as e:
if (e.errno != errno.ENOTCONN):
raise
finally:
self.sock.close()
self.file = self.sock ... |
'Not sure what this does.'
| def rpop(self, user):
| return self._shortcmd(('RPOP %s' % user))
|
'Authorisation
- only possible if server has supplied a timestamp in initial greeting.
Args:
user - mailbox user;
password - mailbox password.
NB: mailbox is locked by server from here to \'quit()\''
| def apop(self, user, password):
| secret = bytes(password, self.encoding)
m = self.timestamp.match(self.welcome)
if (not m):
raise error_proto('-ERR APOP not supported by server')
import hashlib
digest = (m.group(1) + secret)
digest = hashlib.md5(digest).hexdigest()
return self._shortcmd(('APOP %s ... |
'Retrieve message header of message number \'which\'
and first \'howmuch\' lines of message body.
Result is in form [\'response\', [\'line\', ...], octets].'
| def top(self, which, howmuch):
| return self._longcmd(('TOP %s %s' % (which, howmuch)))
|
'Return message digest (unique id) list.
If \'which\', result contains unique id for that message
in the form \'response mesgnum uid\', otherwise result is
the list [\'response\', [\'mesgnum uid\', ...], octets]'
| def uidl(self, which=None):
| if (which is not None):
return self._shortcmd(('UIDL %s' % which))
return self._longcmd('UIDL')
|
'Return server capabilities (RFC 2449) as a dictionary
>>> c=poplib.POP3(\'localhost\')
>>> c.capa()
{\'IMPLEMENTATION\': [\'Cyrus\', \'POP3\', \'server\', \'v2.2.12\'],
\'TOP\': [], \'LOGIN-DELAY\': [\'0\'], \'AUTH-RESP-CODE\': [],
\'EXPIRE\': [\'NEVER\'], \'USER\': [], \'STLS\': [], \'PIPELINING\': [],
\'UIDL\': [], ... | def capa(self):
| def _parsecap(line):
lst = line.decode('ascii').split()
return (lst[0], lst[1:])
caps = {}
try:
resp = self._longcmd('CAPA')
rawcaps = resp[1]
for capline in rawcaps:
(capnm, capargs) = _parsecap(capline)
caps[capnm] = capargs
except error_... |
'Start a TLS session on the active connection as specified in RFC 2595.
context - a ssl.SSLContext'
| def stls(self, context=None):
| if (not HAVE_SSL):
raise error_proto('-ERR TLS support missing')
if self._tls_established:
raise error_proto('-ERR TLS session already established')
caps = self.capa()
if (not ('STLS' in caps)):
raise error_proto('-ERR STLS not supported by ser... |
'Set the input delimiter.
Can be a fixed string of any length, an integer, or None.'
| def set_terminator(self, term):
| if (isinstance(term, str) and self.use_encoding):
term = bytes(term, self.encoding)
elif (isinstance(term, int) and (term < 0)):
raise ValueError('the number of received bytes must be positive')
self.terminator = term
|
'predicate for inclusion in the readable for select()'
| def readable(self):
| return 1
|
'predicate for inclusion in the writable for select()'
| def writable(self):
| return (self.producer_fifo or (not self.connected))
|
'automatically close this channel once the outgoing queue is empty'
| def close_when_done(self):
| self.producer_fifo.append(None)
|
'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.