INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Parse a URL into 5 components: <scheme >:// <netloc >/ <path > ?<query > #<fragment > Return a 5 - tuple: ( scheme netloc path query fragment ). Note that we don t break the components up in smaller bits ( e. g. netloc is a single string ) and we don t expand % escapes. | def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
Return a 5-tuple: (scheme, netloc, path, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expa... |
Put a parsed URL back together again. This may result in a slightly different but equivalent URL if the URL that was parsed originally had redundant delimiters e. g. a ? with an empty query ( the draft states that these are equivalent ). | def urlunparse(data):
"""Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent)."""
scheme, netloc, url, params, quer... |
Combine the elements of a tuple as returned by urlsplit () into a complete URL as a string. The data argument can be any five - item iterable. This may result in a slightly different but equivalent URL if the URL that was parsed originally had unnecessary delimiters ( for example a ? with an empty query ; the RFC state... | def urlunsplit(data):
"""Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example,... |
Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. | def urljoin(base, url, allow_fragments=True):
"""Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter."""
if not base:
return url
if not url:
return base
bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
urlparse(base, '', all... |
Removes any existing fragment from URL. | def urldefrag(url):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
"""
if '#' in url:
s, n, p, a, q, frag = urlparse(url)
defrag = urlunparse((s, n, ... |
unquote ( abc%20def ) - > abc def. | def unquote(s):
"""unquote('abc%20def') -> 'abc def'."""
if _is_unicode(s):
if '%' not in s:
return s
bits = _asciire.split(s)
res = [bits[0]]
append = res.append
for i in range(1, len(bits), 2):
append(unquote(str(bits[i])).decode('latin1'))
... |
Parse a query given as a string argument. | def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.... |
Parse a query given as a string argument. | def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings. A
tru... |
Return a new SplitResult object replacing specified fields with new values | def _replace(_self, **kwds):
'Return a new SplitResult object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('scheme', 'netloc', 'path', 'query', 'fragment'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
re... |
Get the lines for a file from the cache. Update the cache if it doesn t contain an entry for this file already. | def getlines(filename, module_globals=None):
"""Get the lines for a file from the cache.
Update the cache if it doesn't contain an entry for this file already."""
if filename in cache:
return cache[filename][2]
try:
return updatecache(filename, module_globals)
except MemoryError:
... |
Discard cache entries that are out of date. ( This is not checked upon each call! ) | def checkcache(filename=None):
"""Discard cache entries that are out of date.
(This is not checked upon each call!)"""
if filename is None:
filenames = cache.keys()
else:
if filename in cache:
filenames = [filename]
else:
return
for filename in filen... |
Update a cache entry and return its list of lines. If something s wrong print a message discard the cache entry and return an empty list. | def updatecache(filename, module_globals=None):
"""Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list."""
if filename in cache:
del cache[filename]
if not filename or (filename.startswith('<') and filen... |
Test whether a path is a regular file | def isfile(path):
"""Test whether a path is a regular file"""
try:
st = os.stat(path)
except os.error:
return False
return stat.S_ISREG(st.st_mode) |
Return true if the pathname refers to an existing directory. | def isdir(s):
"""Return true if the pathname refers to an existing directory."""
try:
st = os.stat(s)
except os.error:
return False
return stat.S_ISDIR(st.st_mode) |
Given a list of pathnames returns the longest common leading component | def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1 |
Split the extension from a pathname. | def _splitext(p, sep, altsep, extsep):
"""Split the extension from a pathname.
Extension is everything from the last dot to the end, ignoring
leading dots. Returns "(root, ext)"; ext may be empty."""
sepIndex = p.rfind(sep)
if altsep:
altsepIndex = p.rfind(altsep)
sepIndex = max(s... |
Wrap a single paragraph of text returning a list of wrapped lines. | def wrap(text, width=70, **kwargs):
"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), ... |
Fill a single paragraph of text returning a new string. | def fill(text, width=70, **kwargs):
"""Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whit... |
Remove any common leading whitespace from every line in text. | def dedent(text):
"""Remove any common leading whitespace from every line in `text`.
This can be used to make triple-quoted strings line up with the left
edge of the display, while still presenting them in the source code
in indented form.
Note that tabs and spaces are both treated as whitespace, ... |
_munge_whitespace ( text: string ) - > string | def _munge_whitespace(self, text):
"""_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz"
becomes " foo bar baz".
"""
if self.expand_tabs:
# tex... |
_split ( text: string ) - > [ string ] | def _split(self, text):
"""_split(text : string) -> [string]
Split the text to wrap into indivisible chunks. Chunks are
not quite the same as words; see _wrap_chunks() for full
details. As an example, the text
Look, goof-ball -- use the -b option!
breaks into the fol... |
_fix_sentence_endings ( chunks: [ string ] ) | def _fix_sentence_endings(self, chunks):
"""_fix_sentence_endings(chunks : [string])
Correct for sentence endings buried in 'chunks'. Eg. when the
original text contains "... foo.\\nBar ...", munge_whitespace()
and split() will convert that to [..., "foo.", " ", "Bar", ...]
whi... |
_handle_long_word ( chunks: [ string ] cur_line: [ string ] cur_len: int width: int ) | def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
"""_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long... |
_wrap_chunks ( chunks: [ string ] ) - > [ string ] | def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and... |
wrap ( text: string ) - > [ string ] | def wrap(self, text):
"""wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characte... |
Convert a long integer to a byte string. | def _long2bytesBigEndian(n, blocksize=0):
"""Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front
of the byte string with binary zeros so that the length is a multiple
of blocksize.
"""
# After much testing, this algorithm was deemed to b... |
Transform a list of characters into a list of longs. | def _bytelist2longBigEndian(list):
"Transform a list of characters into a list of longs."
imax = len(list) // 4
hl = [0] * imax
j = 0
i = 0
while i < imax:
b0 = ord(list[j]) << 24
b1 = ord(list[j+1]) << 16
b2 = ord(list[j+2]) << 8
b3 = ord(list[j+3])
hl[... |
Initialize the message - digest and set all fields to zero. | def init(self):
"Initialize the message-digest and set all fields to zero."
self.length = 0
self.input = []
# Initial 160 bit message digest (5 times 32 bit).
self.H0 = 0x67452301
self.H1 = 0xEFCDAB89
self.H2 = 0x98BADCFE
self.H3 = 0x10325476
sel... |
This loop was unrolled to gain about 10% in speed for t in range ( 0 80 ): TEMP = _rotateLeft ( A 5 ) + f [ t/ 20 ] + E + W [ t ] + K [ t/ 20 ] E = D D = C C = _rotateLeft ( B 30 ) & 0xffffffff B = A A = TEMP & 0xffffffff | def _transform(self, W):
for t in range(16, 80):
W.append(_rotateLeft(
W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1) & 0xffffffff)
A = self.H0
B = self.H1
C = self.H2
D = self.H3
E = self.H4
"""
This loop was unrolled to gain about... |
Terminate the message - digest computation and return digest. | def digest(self):
"""Terminate the message-digest computation and return digest.
Return the digest of the strings passed to the update()
method so far. This is a 16-byte string which may contain
non-ASCII characters, including null bytes.
"""
H0 = self.H0
H1 = s... |
Returns token at offset as a: class: Token and advances offset to point past the end of the token where the token has: | def next(self, eof_token=False):
"""
Returns token at ``offset`` as a :class:`Token` and advances ``offset``
to point past the end of the token, where the token has:
- *range* which is a :class:`pythonparser.source.Range` that includes
the token but not surrounding whitespace,... |
Same as: meth: next except the token is not dequeued. | def peek(self, eof_token=False):
"""Same as :meth:`next`, except the token is not dequeued."""
if len(self.queue) == 0:
self._refill(eof_token)
return self.queue[-1] |
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):
"""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.
"""
event = Event(time, priority, action, argument)
heapq.heappush(self._queue, event)
... |
Execute events until the queue is empty. When there is a positive delay until the first event the delay function is called and the event is left in the queue ; otherwise the event is removed from the queue and executed ( its action function is called passing it the argument ). If the delay function returns prematurely ... | def run(self):
"""Execute events until the queue is empty.
When there is a positive delay until the first event, the
delay function is called and the event is left in the queue;
otherwise, the event is removed from the queue and executed
(its action function is called, passing it... |
An ordered list of upcoming events. Events are named tuples with fields for: time priority action arguments | def queue(self):
"""An ordered list of upcoming events.
Events are named tuples with fields for:
time, priority, action, arguments
"""
# Use heapq to sort the queue rather than using 'sorted(self._queue)'.
# With heapq, two events scheduled at the same time will show ... |
Create a mapping from a string name to a dialect class. dialect = csv. register_dialect ( name dialect ) | def register_dialect(name, dialect=None, **kwargs):
"""Create a mapping from a string name to a dialect class.
dialect = csv.register_dialect(name, dialect)"""
if not isinstance(name, basestring):
raise TypeError("dialect name must be a string or unicode")
dialect = _call_dialect(dialect, kwarg... |
Sets an upper limit on parsed fields. csv. field_size_limit ( [ limit ] ) | def field_size_limit(limit=undefined):
"""Sets an upper limit on parsed fields.
csv.field_size_limit([limit])
Returns old limit. If limit is not given, no new limit is set and
the old limit is returned"""
global _field_limit
old_limit = _field_limit
if limit is not undefined:
if n... |
Shallow copy operation on arbitrary Python objects. | def copy(x):
"""Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
cls = type(x)
copier = _copy_dispatch.get(cls)
if copier:
return copier(x)
copier = getattr(cls, "__copy__", None)
if copier:
return copier(x)
r... |
Deep copy operation on arbitrary Python objects. | def deepcopy(x, memo=None, _nil=[]):
"""Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
if memo is None:
memo = {}
d = id(x)
y = memo.get(d, _nil)
if y is not _nil:
return y
cls = type(x)
copier = _deepcopy_disp... |
Keeps a reference to the object x in the memo. | def _keep_alive(x, memo):
"""Keeps a reference to the object x in the memo.
Because we remember objects by their id, we have
to assure that possibly temporary objects are kept
alive by referencing them.
We store a reference at the id of the memo, which should
normally not be used unless someone... |
Issue a deprecation warning for Python 3. x related changes. | def warnpy3k(message, category=None, stacklevel=1):
"""Issue a deprecation warning for Python 3.x related changes.
Warnings are omitted unless Python is started with the -3 option.
"""
if sys.py3kwarning:
if category is None:
category = DeprecationWarning
warn(message, categ... |
Hook to write a warning to a file ; replace if you like. | def _show_warning(message, category, filename, lineno, file=None, line=None):
"""Hook to write a warning to a file; replace if you like."""
if file is None:
file = sys.stderr
if file is None:
# sys.stderr is None - warnings get lost
return
try:
file.write(form... |
Function to format a warning the standard way. | def formatwarning(message, category, filename, lineno, line=None):
"""Function to format a warning the standard way."""
try:
unicodetype = unicode
except NameError:
unicodetype = ()
try:
message = str(message)
except UnicodeEncodeError:
pass
s = "%s: %s: %s\n" % ... |
Insert an entry into the list of warnings filters ( at the front ). | def filterwarnings(action, message="", category=Warning, module="", lineno=0,
append=0):
"""Insert an entry into the list of warnings filters (at the front).
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'message' -- a regex that the warni... |
Insert a simple entry into the list of warnings filters ( at the front ). | def simplefilter(action, category=Warning, lineno=0, append=0):
"""Insert a simple entry into the list of warnings filters (at the front).
A simple filter matches all modules and messages.
'action' -- one of "error", "ignore", "always", "default", "module",
or "once"
'category' -- a cla... |
Issue a warning or maybe ignore it or raise an exception. | def warn(message, category=None, stacklevel=1):
"""Issue a warning, or maybe ignore it or raise an exception."""
# Check if message is already a Warning object
if isinstance(message, Warning):
category = message.__class__
# Check category argument
if category is None:
category = User... |
Compute the hash value of a set. | def _hash(self):
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they co... |
Remove an element. If not a member raise a KeyError. | def remove(self, value):
"""Remove an element. If not a member, raise a KeyError."""
if value not in self:
raise KeyError(value)
self.discard(value) |
Return the popped value. Raise KeyError if empty. | def pop(self):
"""Return the popped value. Raise KeyError if empty."""
it = iter(self)
try:
value = next(it)
except StopIteration:
raise KeyError
self.discard(value)
return value |
D. update ( [ E ] ** F ) - > None. Update D from mapping/ iterable E and F. If E present and has a. keys () method does: for k in E: D [ k ] = E [ k ] If E present and lacks. keys () method does: for ( k v ) in E: D [ k ] = v In either case this is followed by: for k v in F. items (): D [ k ] = v | def update(*args, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is foll... |
S. index ( value ) - > integer -- return first index of value. Raises ValueError if the value is not present. | def index(self, value):
'''S.index(value) -> integer -- return first index of value.
Raises ValueError if the value is not present.
'''
for i, v in enumerate(self):
if v == value:
return i
raise ValueError |
S. reverse () -- reverse * IN PLACE * | def reverse(self):
'S.reverse() -- reverse *IN PLACE*'
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i] |
Returns value as a valid Go string literal. | def go_str(value):
"""Returns value as a valid Go string literal."""
io = StringIO.StringIO()
io.write('"')
for c in value:
if c in _ESCAPES:
io.write(_ESCAPES[c])
elif c in _SIMPLE_CHARS:
io.write(c)
else:
io.write(r'\x{:02x}'.format(ord(c)))
io.write('"')
return io.getvalue() |
Outputs the boilerplate necessary for code blocks like functions. | def write_block(self, block_, body):
"""Outputs the boilerplate necessary for code blocks like functions.
Args:
block_: The Block object representing the code block.
body: String containing Go code making up the body of the code block.
"""
self.write('for ; πF.State() >= 0; πF.PopCheckpoint... |
Acquire a lock blocking or non - blocking. | def acquire(self, blocking=1):
"""Acquire a lock, blocking or non-blocking.
When invoked without arguments: if this thread already owns the lock,
increment the recursion level by one, and return immediately. Otherwise,
if another thread owns the lock, block until the lock is unlocked. O... |
Release a lock decrementing the recursion level. | def release(self):
"""Release a lock, decrementing the recursion level.
If after the decrement it is zero, reset the lock to unlocked (not owned
by any thread), and if any other threads are blocked waiting for the
lock to become unlocked, allow exactly one of them to proceed. If after
... |
Wait until notified or until a timeout occurs. | def wait(self, timeout=None):
"""Wait until notified or until a timeout occurs.
If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is
awakened by a notify() or ... |
Wake up one or more threads waiting on this condition if any. | def notify(self, n=1):
"""Wake up one or more threads waiting on this condition, if any.
If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.
This method wakes up at most n of the threads waiting for the condition
variable; it is... |
Acquire a semaphore decrementing the internal counter by one. | def acquire(self, blocking=1):
"""Acquire a semaphore, decrementing the internal counter by one.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thre... |
Release a semaphore incrementing the internal counter by one. | def release(self):
"""Release a semaphore, incrementing the internal counter by one.
When the counter is zero on entry and another thread is waiting for it
to become larger than zero again, wake up that thread.
"""
with self.__cond:
self.__value = self.__value + 1
... |
Release a semaphore incrementing the internal counter by one. | def release(self):
"""Release a semaphore, incrementing the internal counter by one.
When the counter is zero on entry and another thread is waiting for it
to become larger than zero again, wake up that thread.
If the number of releases exceeds the number of acquires,
raise a V... |
Set the internal flag to true. | def set(self):
"""Set the internal flag to true.
All threads waiting for the flag to become true are awakened. Threads
that call wait() once the flag is true will not block at all.
"""
with self.__cond:
self.__flag = True
self.__cond.notify_all() |
Block until the internal flag is true. | def wait(self, timeout=None):
"""Block until the internal flag is true.
If the internal flag is true on entry, return immediately. Otherwise,
block until another thread calls set() to set the flag to true, or until
the optional timeout occurs.
When the timeout argument is prese... |
Start the thread s activity. | def start(self):
"""Start the thread's activity.
It must be called at most once per thread object. It arranges for the
object's run() method to be invoked in a separate thread of control.
This method will raise a RuntimeError if called more than once on the
same thread object.
... |
Method representing the thread s activity. | def run(self):
"""Method representing the thread's activity.
You may override this method in a subclass. The standard run() method
invokes the callable object passed to the object's constructor as the
target argument, if any, with sequential and keyword arguments taken
from the ... |
Wait until the thread terminates. | def join(self, timeout=None):
"""Wait until the thread terminates.
This blocks the calling thread until the thread whose join() method is
called terminates -- either normally or through an unhandled exception
or until the optional timeout occurs.
When the timeout argument is pr... |
Debug helper to print the ABC registry. | def _dump_registry(cls, file=None):
"""Debug helper to print the ABC registry."""
print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)
print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter
for name in sorted(cls.__dict__.keys()):
if name.startswith("_... |
quotetabs = True means that tab and space characters are always quoted. istext = False means that \ r and \ n are treated as regular characters header = True encodes space characters with _ and requires real _ characters to be quoted. | def b2a_qp(data, quotetabs=False, istext=True, header=False):
"""quotetabs=True means that tab and space characters are always
quoted.
istext=False means that \r and \n are treated as regular characters
header=True encodes space characters with '_' and requires
real '_' characters to be ... |
Run length encoding for binhex4. The CPython implementation does not do run length encoding of \ x90 characters. This implementation does. | def rlecode_hqx(s):
"""
Run length encoding for binhex4.
The CPython implementation does not do run length encoding
of \x90 characters. This implementation does.
"""
if not s:
return ''
result = []
prev = s[0]
count = 1
# Add a dummy character to get the loop to go one ex... |
_match_abbrev ( s: string wordmap: { string: Option } ) - > string | def _match_abbrev(s, wordmap):
"""_match_abbrev(s : string, wordmap : {string : Option}) -> string
Return the string key in 'wordmap' for which 's' is an unambiguous
abbreviation. If 's' is found to be ambiguous or doesn't match any of
'words', raise BadOptionError.
"""
# Is there an exact mat... |
Format a paragraph of free - form text for inclusion in the help output at the current indentation level. | def _format_text(self, text):
"""
Format a paragraph of free-form text for inclusion in the
help output at the current indentation level.
"""
text_width = max(self.width - self.current_indent, 11)
indent = " "*self.current_indent
return textwrap.fill(text,
... |
Return a comma - separated list of option strings & metavariables. | def format_option_strings(self, option):
"""Return a comma-separated list of option strings & metavariables."""
if option.takes_value():
metavar = option.metavar or option.dest.upper()
short_opts = [self._short_opt_fmt % (sopt, metavar)
for sopt in optio... |
Update the option values from an arbitrary dictionary but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored. | def _update_careful(self, dict):
"""
Update the option values from an arbitrary dictionary, but only
use keys from dict that already have a corresponding attribute
in self. Any keys in dict without a corresponding attribute
are silently ignored.
"""
for attr in d... |
add_option ( Option ) add_option ( opt_str... kwarg = val... ) | def add_option(self, *args, **kwargs):
"""add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)
"""
if type(args[0]) in types.StringTypes:
option = self.option_class(*args, **kwargs)
elif len(args) == 1 and not kwargs:
option = args[0]
... |
Declare that you are done with this OptionParser. This cleans up reference cycles so the OptionParser ( and all objects referenced by it ) can be garbage - collected promptly. After calling destroy () the OptionParser is unusable. | def destroy(self):
"""
Declare that you are done with this OptionParser. This cleans up
reference cycles so the OptionParser (and all objects referenced by
it) can be garbage-collected promptly. After calling destroy(), the
OptionParser is unusable.
"""
OptionCo... |
parse_args ( args: [ string ] = sys. argv [ 1: ] values: Values = None ) - > ( values: Values args: [ string ] ) | def parse_args(self, args=None, values=None):
"""
parse_args(args : [string] = sys.argv[1:],
values : Values = None)
-> (values : Values, args : [string])
Parse the command-line options found in 'args' (default:
sys.argv[1:]). Any errors result in a call to '... |
print_help ( file: file = stdout ) | def print_help(self, file=None):
"""print_help(file : file = stdout)
Print an extended help message, listing all options and any
help text provided with them, to 'file' (default stdout).
"""
if file is None:
file = sys.stdout
encoding = self._get_encoding(fil... |
reverse * IN PLACE * | def reverse(self):
"reverse *IN PLACE*"
leftblock = self.left
rightblock = self.right
leftindex = self.leftndx
rightindex = self.rightndx
for i in range(self.length // 2):
# Validate that pointers haven't met in the middle
assert leftblock != right... |
Insert item x in list a and keep it sorted assuming a is sorted. | def insort_right(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise V... |
Return the index where to insert item x in list a assuming a is sorted. | def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already ... |
Return the index where to insert item x in list a assuming a is sorted. | def bisect_left(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e < x, and all e in
a[i:] have e >= x. So if x already appears in the list, a.insert(x) will
insert just before the leftmost x already t... |
Lock a mutex call the function with supplied argument when it is acquired. If the mutex is already locked place function and argument in the queue. | def lock(self, function, argument):
"""Lock a mutex, call the function with supplied argument
when it is acquired. If the mutex is already locked, place
function and argument in the queue."""
if self.testandset():
function(argument)
else:
self.queue.appen... |
Unlock a mutex. If the queue is not empty call the next function with its argument. | def unlock(self):
"""Unlock a mutex. If the queue is not empty, call the next
function with its argument."""
if self.queue:
function, argument = self.queue.popleft()
function(argument)
else:
self.locked = False |
od. clear () - > None. Remove all items from od. | def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root[:] = [root, root, None]
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):
'''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.
'''
if not self:
raise KeyError('dictionary is empty')
key = next(reversed(self) if last else iter... |
OD. fromkeys ( S [ v ] ) - > New ordered dictionary with keys from S. If not specified the value defaults to None. | def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key in iterable:
self[key] = value
return self |
Like dict. update () but add counts instead of replacing them. | def update(*args, **kwds):
'''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'... |
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. | def subtract(*args, **kwds):
'''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.
... |
Terminate the message - digest computation and return digest. | def digest(self):
"""Terminate the message-digest computation and return digest.
Return the digest of the strings passed to the update()
method so far. This is a 16-byte string which may contain
non-ASCII characters, including null bytes.
"""
A = self.A
B = self.B
C = self.C
D = se... |
Return a clone object. | def copy(self):
"""Return a clone object.
Return a copy ('clone') of the md5 object. This can be used
to efficiently compute the digests of strings that share
a common initial substring.
"""
if 0: # set this to 1 to make the flow space crash
return copy.deepcopy(self)
clone = self.__... |
Compiles ( or rather just converts ) a pattern descriptor to a SRE_Pattern object. Actual compilation to opcodes happens in sre_compile. | def compile(pattern, flags, code, groups=0, groupindex={}, indexgroup=[None]):
"""Compiles (or rather just converts) a pattern descriptor to a SRE_Pattern
object. Actual compilation to opcodes happens in sre_compile."""
return SRE_Pattern(pattern, flags, code, groups, groupindex, indexgroup) |
Scan through string looking for a location where this regular expression produces a match and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern. | def search(self, string, pos=0, endpos=sys.maxint):
"""Scan through string looking for a location where this regular
expression produces a match, and return a corresponding MatchObject
instance. Return None if no position in the string matches the
pattern."""
state = _State(strin... |
Return a list of all non - overlapping matches of pattern in string. | def findall(self, string, pos=0, endpos=sys.maxint):
"""Return a list of all non-overlapping matches of pattern in string."""
matchlist = []
state = _State(string, pos, endpos, self.flags)
while state.start <= state.end:
state.reset()
state.string_position = state... |
Return the string obtained by replacing the leftmost non - overlapping occurrences of pattern in string by the replacement repl. | def sub(self, repl, string, count=0):
"""Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl."""
return self._subx(repl, string, count, False) |
Return the tuple ( new_string number_of_subs_made ) found by replacing the leftmost non - overlapping occurrences of pattern with the replacement repl. | def subn(self, repl, string, count=0):
"""Return the tuple (new_string, number_of_subs_made) found by replacing
the leftmost non-overlapping occurrences of pattern with the replacement
repl."""
return self._subx(repl, string, count, True) |
Split string by the occurrences of pattern. | def split(self, string, maxsplit=0):
"""Split string by the occurrences of pattern."""
splitlist = []
state = _State(string, 0, sys.maxint, self.flags)
n = 0
last = state.start
while not maxsplit or n < maxsplit:
state.reset()
state.string_position... |
Return a list of all non - overlapping matches of pattern in string. | def finditer(self, string, pos=0, endpos=sys.maxint):
"""Return a list of all non-overlapping matches of pattern in string."""
scanner = self.scanner(string, pos, endpos)
return iter(scanner.search, None) |
Creates a tuple of index pairs representing matched groups. | def _create_regs(self, state):
"""Creates a tuple of index pairs representing matched groups."""
regs = [(state.start, state.string_position)]
for group in range(self.re.groups):
mark_index = 2 * group
if mark_index + 1 < len(state.marks) \
... |
Returns a tuple containing all the subgroups of the match. The default argument is used for groups that did not participate in the match ( defaults to None ). | def groups(self, default=None):
"""Returns a tuple containing all the subgroups of the match. The
default argument is used for groups that did not participate in the
match (defaults to None)."""
groups = []
for indices in self.regs[1:]:
if indices[0] >= 0:
... |
Return a dictionary containing all the named subgroups of the match. The default argument is used for groups that did not participate in the match ( defaults to None ). | def groupdict(self, default=None):
"""Return a dictionary containing all the named subgroups of the match.
The default argument is used for groups that did not participate in the
match (defaults to None)."""
groupdict = {}
for key, value in self.re.groupindex.items():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.