code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not hasattr(state, "parent"): raise ValueError( "You can only use has_equal_value() on the state resulting from check_column, check_row or check_result." ) if incorrect_msg is None: incorrect_msg = "Column `{{col}}` seems to be incorrect.{{' Make sure you arranged t...
def has_equal_value(state, ordered=False, ndigits=None, incorrect_msg=None)
Verify if a student and solution query result match up. This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result). ``has_equal_value`` then goes over all columns that are still left in the solution query result, and compares each column with th...
3.90446
3.629215
1.075841
return state.to_child( student_result={k.lower(): v for k, v in state.student_result.items()}, solution_result={k.lower(): v for k, v in state.solution_result.items()}, )
def lowercase(state)
Convert all column names to their lower case versions to improve robustness :Example: Suppose we are testing the following SELECT statements * solution: ``SELECT artist_id as id FROM artists`` * student : ``SELECT artist_id as ID FROM artists`` We can write the following SCTs...
3.767578
4.397121
0.856828
state1 = lowercase(state) state2 = check_all_columns(state1) has_equal_value(state2) return state2
def check_result(state)
High level function which wraps other SCTs for checking results. ``check_result()`` * uses ``lowercase()``, then * runs ``check_all_columns()`` on the state produced by ``lowercase()``, then * runs ``has_equal_value`` on the state produced by ``check_all_columns()``.
11.774121
3.117747
3.776484
if error_msg is None: error_msg = "Running `{{query}}` after your submission generated an error." if expand_msg is None: expand_msg = "The autograder verified the result of running `{{query}}` against the database. " msg_kwargs = {"query": query} # before redoing the query, #...
def check_query(state, query, error_msg=None, expand_msg=None)
Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result. ``check_query()`` will rerun the solution query in the transactio...
5.026285
4.402292
1.141743
# if it has already been wrapped, we return original if hasattr(f, "lower_cased"): return f @wraps(f) def wrapper(*args, **kwargs): f.lower_cased = True return f(*args, **kwargs).lower() return wrapper
def lower_case(f)
Decorator specifically for turning mssql AST into lowercase
3.675702
3.489472
1.053369
startdir = argd['DIR'] or '/' if not os.path.isdir(startdir): raise InvalidArg('not a valid start directory: {}'.format(startdir)) if argd['--progress']: return walk_dir_progress(startdir) return walk_dir_animated(startdir)
def main(argd)
Main entry point, expects doctopt arg dict as argd.
5.339293
5.381363
0.992182
if kwargs.get('file', None) is None: kwargs['file'] = sys.stderr print(*args, **kwargs)
def print_err(*args, **kwargs)
A wrapper for print() that uses stderr by default.
2.640329
1.980264
1.333322
p = AnimatedProgress( 'Walking {}...'.format(path), frames=Frames.dots_orbit.as_rainbow(), show_time=True, ) rootcnt = 0 print('\nStarting animated progress.') with p: for root, dirs, files in os.walk(path): rootcnt += 1 if rootcnt % 50 ==...
def walk_dir_animated(path, maxdircnt=1000)
Walk a directory, printing status updates along the way.
5.102711
4.919632
1.037214
p = ProgressBar( 'Walking {}'.format(C(path, 'cyan')), bars=Bars.numbers_blue.with_wrapper(('(', ')')), show_time=True, file=file, ) rootcnt = 0 print('\nStarting progress bar...') p.start() for root, dirs, files in os.walk(path): rootcnt += 1 ...
def walk_dir_progress(path, maxdircnt=5000, file=sys.stdout)
Walk a directory, printing status updates along the way.
4.345921
4.311003
1.0081
newlines = [] bigindent = (' ' * 16) in_opts = False for line in s.split('\n'): linestripped = line.strip('\n').strip().strip(':') if linestripped == 'Usage': # label line = line.replace('Usage', str(C('Usage', **ARGS_LABEL))) elif linestripped == 'Op...
def _coloredhelp(s)
Colorize the usage string for docopt (ColorDocoptExit, docoptextras)
3.895509
3.9427
0.988031
# docopt documentation is appended programmatically after this func def. global SCRIPT global ARGS_DESC, ARGS_HEADER, ARGS_LABEL, ARGS_OPTIONS global ARGS_SCRIPT, ARGS_VERSION SCRIPT = script if colors: # Setup colors, if any were given. ARGS_DESC.update( color...
def docopt( doc, argv=None, help=True, version=None, options_first=False, script=None, colors=None)
This is a wrapper for docopt.docopt that also sets SCRIPT to `script`. When SCRIPT is set, it can be colorized for the usage string. A dict of Colr options can be passed with `colors` to alter the styles. Available color options keys: desc : Colr args for the description of options. ...
3.484301
2.787694
1.249886
accepted_methods = ('0', '1', '2', '3', '4') methodstr = str(method) if methodstr not in accepted_methods: raise ValueError('Invalid method, expected {}. Got: {!r}'.format( ', '.join(accepted_methods), method, )) if methods...
def display(method=EraseMethod.ALL_MOVE)
Clear the screen or part of the screen, and possibly moves the cursor to the "home" position (1, 1). See `method` argument below. Esc[<method>J Arguments: method: One of these possible values: EraseMethod.END or 0: ...
4.581668
3.898471
1.175247
methods = ('0', '1', '2') if str(method) not in methods: raise ValueError('Invalid method, expected {}. Got: {!r}'.format( ', '.join(methods), method, )) return EscapeCode('{}K'.format(method))
def line(method=EraseMethod.ALL)
Erase a line, or part of a line. See `method` argument below. Cursor position does not change. Esc[<method>K Arguments: method : One of these possible values: EraseMethod.END or 0: Clear from cursor to the ...
6.344834
5.683559
1.116349
try: fileno = file.fileno() except (AttributeError, UnsupportedOperation): # Unable to use fileno to re-open unbuffered. Oh well. # The output may be line buffered, which isn't that great for # repeatedly drawing and erasing text, or hiding/showing the cursor. return...
def try_unbuffered_file(file, _alreadyopen={})
Try re-opening a file in an unbuffered mode and return it. If that fails, just return the original file. This function remembers the file descriptors it opens, so it never opens the same one twice. This is meant for files like sys.stdout or sys.stderr.
6.323499
6.119498
1.033336
self.stop_flag.value = False self.time_started.value = time() self.time_elapsed.value = 0 while True: if self.stop_flag.value: break self.update_text() with self.time_started.get_lock(): start = self.time_start...
def _loop(self)
This is the loop that runs in the subproces. It is called from `run` and is responsible for all printing, text updates, and time management.
3.00961
2.816408
1.068599
try: self._loop() except Exception: # Send the exception through the exc_queue, so the parent # process can check it. typ, val, tb = sys.exc_info() tb_lines = traceback.format_exception(typ, val, tb) self.exc_queue.put((val...
def run(self)
Runs the printer loop in a subprocess. This is called by multiprocessing.
4.209608
4.137311
1.017474
self.stop_flag.value = True with self.lock: ( Control().text(C(' ', style='reset_all')) .pos_restore().move_column(1).erase_line() .write(self.file) )
def stop(self)
Stop this WriterProcessBase, and reset the cursor.
21.371321
16.091999
1.328071
self.write() try: newtext = self.text_queue.get_nowait() self._text = newtext except Empty: pass
def update_text(self)
Write the current text, and check for any new text changes. This also updates the elapsed time.
6.240669
4.968879
1.255951
if self._text is not None: with self.lock: self.file.write(str(self._text).encode()) self.file.flush() sleep(self.nice_delay)
def write(self)
Write the current text to self.file, and flush it. This can be overridden to handle custom writes.
5.411006
4.617328
1.171891
if self._exception is not None: return self._exception try: exc, tblines = self.exc_queue.get_nowait() except Empty: self._exception, self.tb_lines = None, None else: # Raise any exception that the subprocess encountered and sent. ...
def exception(self)
Try retrieving the last subprocess exception. If set, the exception is returned. Otherwise None is returned.
5.29432
4.875816
1.085833
if isinstance(value, str): value = value.split(self.join_str) if not (value and isinstance(value, (list, tuple))): raise TypeError( ' '.join(( 'Expecting str or list/tuple of formats {!r}.', 'Got: ({}) {!r}' ...
def fmt(self, value)
Sets self.fmt, with some extra help for plain format strings.
4.840201
4.490167
1.077956
try: Control().cursor_hide().write(file=self.file) super().run() except KeyboardInterrupt: self.stop() finally: Control().cursor_show().write(file=self.file)
def run(self)
Overrides WriterProcess.run, to handle KeyboardInterrupts better. This should not be called by any user. `multiprocessing` calls this in a subprocess. Use `self.start` to start this instance.
6.512777
5.216103
1.248591
super().stop() while not self.stopped: # stop() should block, so printing afterwards isn't interrupted. sleep(0.001) # Retrieve the latest exception, if any. exc = self.exception if exc is not None: raise exc
def stop(self)
Stop this animated progress, and block until it is finished.
9.751722
8.68409
1.122941
if self.text is None: # Text has not been sent through the pipe yet. # Do not write anything until it is set to non-None value. return None if self._last_text == self.text: char_delay = 0 else: char_delay = self.char_delay ...
def write(self)
Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning.
5.684389
5.521275
1.029543
self.current_frame += 1 if self.current_frame == self.frame_len: self.current_frame = 0
def _advance_frame(self)
Sets `self.current_frame` to the next frame, looping to the beginning if needed.
2.839183
2.331674
1.217659
# User frameslists might not be a FrameSet. delay = userdelay or getattr(frameslist, 'delay', None) delay = (delay or self.default_delay) - self.nice_delay if delay < 0: delay = 0 return delay
def _get_delay(self, userdelay, frameslist)
Get the appropriate delay value to use, trying in this order: userdelay frameslist.delay default_delay The user can override the frameslist's delay by specifiying a value, and if neither are given the default is used.
7.025011
7.09482
0.99016
for i, fmt in enumerate(self.fmt): if '{text' in fmt: # The text will use a write delay. ctl.text(fmt.format(text=self.text)) if i != (self.fmt_len - 1): ctl.text(self.join_str) ctl.write( ...
def write_char_delay(self, ctl, delay)
Write the formatted format pieces in order, applying a delay between characters for the text only.
4.356654
3.964998
1.098778
if percent is not None: self.percent = percent if text is not None: self.message = text super().update()
def update(self, percent=None, text=None)
Update the progress bar percentage and message.
2.676791
2.302816
1.162399
try: val = getattr(cls, name) except AttributeError: for attr in (a for a in dir(cls) if not a.startswith('_')): try: val = getattr(cls, attr) except AttributeError: # Is known to happen. continue valname = ...
def cls_get_by_name(cls, name)
Return a class attribute by searching the attributes `name` attribute.
3.122953
3.0735
1.01609
return [ fset.name for fset in cls_sets(cls, wanted_cls, registered=registered) ]
def cls_names(cls, wanted_cls, registered=True)
Return a list of attributes for all `wanted_cls` attributes in this class, where `wanted_cls` is the desired attribute type.
5.06405
8.172447
0.619649
name = name or getattr(frameset, 'name', None) if name is None: raise ValueError( '`name` is needed when the `frameset` has no name attribute.' ) kwargs = {'name': name} for initarg in init_args: kwargs[initarg] = getattr(frameset, initarg, None) newframeset...
def cls_register(cls, frameset, new_class, init_args, name=None)
Register a new FrameSet or FrameSet subclass as a member/attribute of a class. Returns the new FrameSet or FrameSet subclass. Arguments: frameset : An existing FrameSet, or an iterable of strings. init_args : A list of properties from the `frameset` to try to use ...
4.521895
3.994556
1.132014
sets = [] for attr in dir(cls): if attr.startswith('_'): continue val = getattr(cls, attr, None) if not isinstance(val, wanted_cls): continue if (not registered) and getattr(val, '_registered', False): continue sets.append(val) ...
def cls_sets(cls, wanted_cls, registered=True)
Return a list of all `wanted_cls` attributes in this class, where `wanted_cls` is the desired attribute type.
2.375473
2.550588
0.931343
# Get the basic frame types first. frametypes = cls.sets(registered=False) _colornames = [ # 'black', disabled for now, it won't show on my terminal. 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', ] _colornames.exte...
def _build_color_variants(cls)
Build colorized variants of all frames and return a list of all frame object names.
5.790921
5.630857
1.028426
if wrapper: data = tuple(barset.wrap_str(s, wrapper=wrapper) for s in barset) elif use_wrapper: data = tuple(barset.wrap_str(s) for s in barset) else: data = barset.data return cls( data, name=name, delay=de...
def from_barset( cls, barset, name=None, delay=None, use_wrapper=True, wrapper=None)
Copy a BarSet's frames to create a new FrameSet. Arguments: barset : An existing BarSet object to copy frames from. name : A name for the new FrameSet. delay : Delay for the animation. use_wrapper : Whether to use the old bar...
2.768843
3.107911
0.890902
return self._as_gradient( ('wrapper', ), name=name, style=style, rgb_mode=rgb_mode, )
def as_gradient(self, name=None, style=None, rgb_mode=False)
Wrap each frame in a Colr object, using `Colr.gradient`. Arguments: name : Starting color name. One of `Colr.gradient_names`.
5.241721
7.498338
0.699051
if not self: return self.wrap_str() length = len(self) # Using mod 100, to provide some kind of "auto reset". 0 is 0 though. percentmod = (int(percent) % 100) or min(percent, 100) index = int((length / 100) * percentmod) try: barstr = str...
def as_percent(self, percent)
Return a string representing a percentage of this progress bar. BarSet('1234567890', wrapper=('[, ']')).as_percent(50) >>> '[12345 ]'
6.677156
6.291315
1.061329
return self._as_rainbow( ('wrapper', ), offset=offset, style=style, rgb_mode=rgb_mode, )
def as_rainbow(self, offset=35, style=None, rgb_mode=False)
Wrap each frame in a Colr object, using `Colr.rainbow`.
5.227703
5.613727
0.931236
return cls( cls._generate_move( char, width=width or cls.default_width, fill_char=str(fill_char or cls.default_fill_char), bounce=bounce, reverse=reverse, back_char=back_char, ), ...
def from_char( cls, char, name=None, width=None, fill_char=None, bounce=False, reverse=False, back_char=None, wrapper=None)
Create progress bar frames from a "moving" character. The frames simulate movement of the character, from left to right through empty space (`fill_char`). Arguments: char : Character to move across the bar. name : Name for the new ...
2.506328
2.531013
0.990247
fill_char = fill_char or cls.default_fill_char maxlen = len(s) frames = [] for pos in range(1, maxlen): framestr = s[:pos] # Not using ljust, because fill_char may be a str, not a char. frames.append( ''.join(( ...
def from_str(cls, s, name=None, fill_char=None, wrapper=None)
Create progress bar frames from a single string. The frames simulate growth, from an empty string to the final string (`s`). Arguments: s : Final string for a complete progress bar. name : Name for the new BarSet. fill_c...
3.710456
3.832614
0.968127
width = width or cls.default_width char = str(char) filler = str(fill_char or cls.default_fill_char) * (width - len(char)) rangeargs = RangeMoveArgs( (0, width, 1), (width, 0, -1), ) if reverse: # Reverse the arguments for ran...
def _generate_move( cls, char, width=None, fill_char=None, bounce=False, reverse=True, back_char=None)
Yields strings that simulate movement of a character from left to right. For use with `BarSet.from_char`. Arguments: char : Character to move across the progress bar. width : Width for the progress bar. Default: cl...
3.271867
3.274803
0.999103
name = name or '{}_custom_wrapper'.format(self.name) return self.__class__(self.data, name=name, wrapper=wrapper)
def with_wrapper(self, wrapper=None, name=None)
Copy this BarSet, and return a new BarSet with the specified name and wrapper. If no name is given, `{self.name}_custom_wrapper` is used. If no wrapper is given, the new BarSet will have no wrapper.
4.401759
3.335721
1.319583
wrapper = wrapper or (self.wrapper or ('', '')) return str('' if s is None else s).join(wrapper)
def wrap_str(self, s=None, wrapper=None)
Wrap a string in self.wrapper, with some extra handling for empty/None strings. If `wrapper` is set, use it instead.
6.681264
6.985337
0.95647
return cls_register(cls, barset, BarSet, ('wrapper', ), name=name)
def register(cls, barset, name=None)
Register a new BarSet as a member/attribute of this class. Returns the new BarSet. Arguments: barset : An existing BarSet, or an iterable of strings. name : New name for the BarSet, also used as the classes attribute name. ...
20.735277
22.669001
0.914697
return cls_register(cls, frameset, FrameSet, ('delay', ), name=name)
def register(cls, frameset, name=None)
Register a new FrameSet as a member/attribute of this class. Returns the new FrameSet. Arguments: frameset : An existing FrameSet, or an iterable of strings. name : New name for the FrameSet, also used as the classes attribute nam...
19.365353
25.199245
0.768489
message = '{}: {}'.format(pyuv.errno.errorcode.get(errno, errno), pyuv.errno.strerror(errno)) return cls(message, errno)
def from_errno(cls, errno)
Create a new instance from a :mod:`pyuv.errno` error code.
4.251856
3.656586
1.162794
if self._protocol is not None: raise TransportError('already started') self._protocol = protocol self._protocol.connection_made(self) if self._readable: self.resume_reading() if self._writable: self._writing = True self._ca...
def start(self, protocol)
Bind to *protocol* and start calling callbacks on it.
3.356592
3.331861
1.007423
if high is None: high = self.write_buffer_size if low is None: low = high // 2 if low > high: low = high self._write_buffer_high = high self._write_buffer_low = low
def set_write_buffer_limits(self, high=None, low=None)
Set the low and high watermark for the write buffer.
2.137376
2.044427
1.045465
if self._closing or self._handle.closed: return elif self._protocol is None: raise TransportError('transport not started') # If the write buffer is empty, close now. Otherwise defer to # _on_write_complete that will close when the buffer is empty. ...
def close(self)
Close the transport after all oustanding data has been written.
4.946537
4.370385
1.131831
if self._handle.closed: return elif self._protocol is None: raise TransportError('transport not started') self._handle.close(self._on_close_complete) assert self._handle.closed
def abort(self)
Close the transport immediately.
6.812726
5.528955
1.232191
if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeError("data: expecting a bytes-like instance, got {!r}" .format(type(data).__name__)) if handle is not None and not isinstance(self._handle, pyuv.Pipe): raise ValueError('h...
def write(self, data, handle=None)
Write *data* to the transport.
3.790735
3.654834
1.037184
self._check_status() if not self._writable: raise TransportError('transport is not writable') if self._closing: raise TransportError('transport is closing') try: self._handle.shutdown(self._on_write_complete) except pyuv.error.UVError ...
def write_eof(self)
Shut down the write direction of the transport.
4.952156
4.385331
1.129255
if name == 'sockname': if not hasattr(self._handle, 'getsockname'): return default try: return self._handle.getsockname() except pyuv.error.UVError: return default elif name == 'peername': if not has...
def get_extra_info(self, name, default=None)
Get transport specific data. In addition to the fields from :meth:`BaseTransport.get_extra_info`, the following information is also available: ===================== =================================================== Name Description ===================== ==...
2.280204
1.90468
1.197158
assert handle is self._handle if error: self._log.warning('pyuv error {} in recv callback', error) self._protocol.error_received(TransportError.from_errno(error)) elif flags: assert flags & pyuv.UV_UDP_PARTIAL self._log.warning('ignoring p...
def _on_recv_complete(self, handle, addr, flags, data, error)
Callback used with handle.start_recv().
5.231097
5.321592
0.982995
assert handle is self._handle self._write_buffer_size -= 1 assert self._write_buffer_size >= 0 if self._error: self._log.debug('ignore sendto status {} after error', error) # See note in _on_write_complete() about UV_ECANCELED elif error and error != ...
def _on_send_complete(self, handle, error)
Callback used with handle.send().
6.285658
6.247882
1.006046
if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeError("data: expecting a bytes-like instance, got {!r}" .format(type(data).__name__)) self._check_status() if not self._writable: raise TransportError('transport is...
def sendto(self, data, addr=None)
Send a datagram containing *data* to *addr*. The *addr* argument may be omitted only if the handle was bound to a default remote address.
4.929618
5.054922
0.975212
if address == 'session': address = os.environ.get('DBUS_SESSION_BUS_ADDRESS') if not address: raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set') elif address == 'system': address = os.environ.get('DBUS_SYSTEM_BUS_ADDRESS', 'unix:path=/...
def parse_dbus_address(address)
Parse a D-BUS address string into a list of addresses.
2.109178
2.065866
1.020965
if six.indexbytes(header, 0) == ord('l'): endian = '<' elif six.indexbytes(header, 0) == ord('B'): endian = '>' else: raise ValueError('illegal endianness') if not 1 <= six.indexbytes(header, 1) <= 4: raise ValueError('illegel message type') if struct.unpack(endi...
def parse_dbus_header(header)
Parse a D-BUS header. Return the message size.
2.996689
2.829386
1.05913
if self._server_side: mech = self._authenticator.current_mech return mech.getMechanismName() if mech else None else: return getattr(self._authenticator, 'authMech', None)
def getMechanismName(self)
Return the authentication mechanism name.
4.972363
4.222811
1.177501
if not self._server_side: return mech = self._authenticator.current_mech return mech.getUserName() if mech else None
def getUserName(self)
Return the authenticated user name (server side).
9.013172
6.699678
1.345314
self._name_acquired.wait() if self._error: raise compat.saved_exc(self._error) elif self._transport is None: raise DbusError('not connected') return self._unique_name
def get_unique_name(self)
Return the unique name of the D-BUS connection.
10.26089
7.090471
1.447138
if not isinstance(message, txdbus.DbusMessage): raise TypeError('message: expecting DbusMessage instance (got {!r})', type(message).__name__) self._name_acquired.wait() if self._error: raise compat.saved_exc(self._error) el...
def send_message(self, message)
Send a D-BUS message. The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance.
7.563177
6.142924
1.231202
message = txdbus.MethodCallMessage(path, method, interface=interface, destination=service, signature=signature, body=args, expectReply=not no_reply, autoStart=auto_start) serial = message.serial if timeout == -1: ...
def call_method(self, service, path, interface, method, signature=None, args=None, no_reply=False, auto_start=False, timeout=-1)
Call a D-BUS method and wait for its reply. This method calls the D-BUS method with name *method* that resides on the object at bus address *service*, at path *path*, on interface *interface*. The *signature* and *args* are optional arguments that can be used to add parameters ...
4.197921
5.015608
0.836972
if isinstance(address, six.string_types): addresses = parse_dbus_address(address) else: addresses = [address] for addr in addresses: try: super(DbusClient, self).connect(addr) except pyuv.error.UVError: cont...
def connect(self, address='session')
Connect to *address* and wait until the connection is established. The *address* argument must be a D-BUS server address, in the format described in the D-BUS specification. It may also be one of the special addresses ``'session'`` or ``'system'``, to connect to the D-BUS session and sy...
3.816976
3.515142
1.085867
if isinstance(address, six.string_types): addresses = parse_dbus_address(address) else: addresses = [address] for addr in addresses: try: super(DbusServer, self).listen(addr) except pyuv.error.UVError: self....
def listen(self, address='session')
Start listening on *address* for new connection. The *address* argument must be a D-BUS server address, in the format described in the D-BUS specification. It may also be one of the special addresses ``'session'`` or ``'system'``, to connect to the D-BUS session and system bus, respecti...
4.904908
4.70348
1.042825
def setdoc(func): func.__doc__ = (getattr(base, '__doc__') or '') + (func.__doc__ or '') return func return setdoc
def docfrom(base)
Decorator to set a function's docstring from another function.
3.745609
2.998451
1.249181
ref = _objrefs.get(obj) if ref is None: clsname = obj.__class__.__name__.split('.')[-1] seqno = _lastids.setdefault(clsname, 1) ref = '{}-{}'.format(clsname, seqno) _objrefs[obj] = ref _lastids[clsname] += 1 return ref
def objref(obj)
Return a string that uniquely and compactly identifies an object.
2.965668
2.775548
1.068498
frame = sys._getframe(1) classdict = frame.f_locals @functools.wraps(method) def delegate(self, *args, **kwargs): other_self = other.__get__(self) return method(other_self, *args, **kwargs) if getattr(method, '__switchpoint__', False): delegate.__switchpoint__ = True ...
def delegate_method(other, method, name=None)
Add a method to the current class that delegates to another method. The *other* argument must be a property that returns the instance to delegate to. Due to an implementation detail, the property must be defined in the current class. The *method* argument specifies a method to delegate to. It can be an...
3.180135
3.666658
0.867312
match = re_ws.match(buf, pos) if not match: return None, pos return buf[match.start(0):match.end(0)], match.end(0)
def accept_ws(buf, pos)
Skip whitespace at the current buffer position.
2.462393
2.437401
1.010253
if pos >= len(buf) or buf[pos] != char: return None, pos return char, pos+1
def accept_lit(char, buf, pos)
Accept a literal character at the current buffer position.
3.005634
3.125483
0.961654
if pos >= len(buf) or buf[pos] != char: return None, len(buf) return char, pos+1
def expect_lit(char, buf, pos)
Expect a literal character at the current buffer position.
3.369905
3.410097
0.988214
match = regexp.match(buf, pos) if not match: return None, pos return buf[match.start(1):match.end(1)], match.end(0)
def accept_re(regexp, buf, pos)
Accept a regular expression at the current buffer position.
2.633519
2.820656
0.933655
match = regexp.match(buf, pos) if not match: return None, len(buf) return buf[match.start(1):match.end(1)], match.end(0)
def expect_re(regexp, buf, pos)
Require a regular expression at the current buffer position.
2.798397
2.890145
0.968255
typ = subtyp = None; options = {} typ, pos = expect_re(re_token, header, 0) _, pos = expect_lit('/', header, pos) subtyp, pos = expect_re(re_token, header, pos) ctype = header[:pos] if subtyp else '' while pos < len(header): _, pos = accept_ws(header, pos) _, pos = expect_li...
def parse_content_type(header)
Parse the "Content-Type" header.
3.157933
3.106361
1.016602
pos = 0 names = [] while pos < len(header): name, pos = expect_re(re_token, header, pos) _, pos = accept_ws(header, pos) _, pos = accept_lit(';', header, pos) _, pos = accept_ws(header, pos) qvalue, pos = accept_re(re_qvalue, header, pos) if name: ...
def parse_te(header)
Parse the "TE" header.
2.945363
2.829653
1.040892
pos = 0 names = [] while pos < len(header): name, pos = expect_re(re_token, header, pos) if name: names.append(name) _, pos = accept_ws(header, pos) _, pos = expect_lit(',', header, pos) _, pos = accept_ws(header, pos) return names
def parse_trailer(header)
Parse the "Trailer" header.
4.096409
3.989027
1.026919
if timestamp is None: timestamp = time.time() timestamp = int(timestamp) global _cached_timestamp, _cached_datestring if timestamp != _cached_timestamp: # The time stamp must be GMT, and cannot be localized. tm = time.gmtime(timestamp) s = rfc1123_fmt.replace('%a', w...
def rfc1123_date(timestamp=None)
Create a RFC1123 style Date header for *timestamp*.
3.221012
3.23152
0.996748
# If this is not in origin-form, authority-form or asterisk-form and no # scheme is present, assume it's in absolute-form with a missing scheme. # See RFC7230 section 5.3. if url[:1] not in '*/' and not is_connect and '://' not in url: url = '{}://{}'.format(default_scheme, url) burl = ...
def parse_url(url, default_scheme='http', is_connect=False)
Parse an URL and return its components. The *default_scheme* argument specifies the scheme in case URL is an otherwise valid absolute URL but with a missing scheme. The *is_connect* argument must be set to ``True`` if the URL was requested with the HTTP CONNECT method. These URLs have a different form...
4.617111
4.628054
0.997636
name = name.lower() for header in headers: if header[0].lower() == name: return header[1] return default
def get_header(headers, name, default=None)
Return the value of header *name*. The *headers* argument must be a list of ``(name, value)`` tuples. If the header is found its associated value is returned, otherwise *default* is returned. Header names are matched case insensitively.
2.3542
3.132214
0.751609
i = 0 name = name.lower() for j in range(len(headers)): if headers[j][0].lower() != name: if i != j: headers[i] = headers[j] i += 1 del headers[i:] return headers
def remove_headers(headers, name)
Remove all headers with name *name*. The list is modified in-place and the updated list is returned.
2.420341
2.707393
0.893975
chunk = [] chunk.append(s2b('{:X}\r\n'.format(len(buf)))) chunk.append(buf) chunk.append(b'\r\n') return b''.join(chunk)
def create_chunk(buf)
Create a chunk for the HTTP "chunked" transfer encoding.
2.816707
2.487188
1.132487
chunk = [] chunk.append('0\r\n') if trailers: for name, value in trailers: chunk.append(name) chunk.append(': ') chunk.append(value) chunk.append('\r\n') chunk.append('\r\n') return s2b(''.join(chunk))
def create_chunked_body_end(trailers=None)
Create the ending that terminates a chunked body.
2.225255
2.162971
1.028796
# According to my measurements using b''.join is faster that constructing a # bytearray. message = [] message.append('{} {} HTTP/{}\r\n'.format(method, url, version)) for name, value in headers: message.append(name) message.append(': ') message.append(value) mess...
def create_request(version, method, url, headers)
Create a HTTP request header.
4.322793
4.211825
1.026347
message = [] message.append('HTTP/{} {}\r\n'.format(version, status)) for name, value in headers: message.append(name) message.append(': ') message.append(value) message.append('\r\n') message.append('\r\n') return s2b(''.join(message))
def create_response(version, status, headers)
Create a HTTP response header.
2.306739
2.330462
0.98982
port = self.port if port: port = int(port) else: port = default_ports.get(self.scheme or 'http') return (self.host, port)
def addr(self)
Address tuple that can be used with :func:`~gruvi.create_connection`.
4.323232
4.136446
1.045156
target = self.path or '/' if self.query: target = '{}?{}'.format(target, self.query) return target
def target(self)
The "target" i.e. local part of the URL, consisting of the path and query.
5.297818
3.242431
1.633903
self._headers = headers or [] agent = host = clen = trailer = None # Check the headers provided, and capture some information about the # request from them. for name, value in self._headers: lname = name.lower() # Only HTTP applications are allowe...
def start_request(self, method, url, headers=None, bodylen=None)
Start a new HTTP request. The optional *headers* argument contains the headers to send. It must be a sequence of ``(name, value)`` tuples. The optional *bodylen* parameter is a hint that specifies the length of the body that will follow. A length of -1 indicates no body, 0 means an ...
3.06569
3.013492
1.017321
if not isinstance(buf, six.binary_type): raise TypeError('buf: must be a bytes instance') # Be careful not to write zero-length chunks as they indicate the end of a body. if len(buf) == 0: return if self._content_length and self._bytes_written > self._con...
def write(self, buf)
Write *buf* to the request body.
3.871878
3.744401
1.034045
if not self._chunked: return trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \ if self._trailer else None ending = create_chunked_body_end(trailers) self._protocol.writer.write(ending)
def end_request(self)
End the request body.
6.818199
6.289249
1.084104
if self._error: raise compat.saved_exc(self._error) elif self._transport is None: raise HttpError('not connected') request = HttpRequest(self) bodylen = -1 if body is None else \ len(body) if isinstance(body, bytes) else None ...
def request(self, method, url, headers=None, body=None)
Make a new HTTP request. The *method* argument is the HTTP method as a string, for example ``'GET'`` or ``'POST'``. The *url* argument specifies the URL. The optional *headers* argument specifies extra HTTP headers to use in the request. It must be a sequence of ``(name, value)`` tuple...
2.977873
2.972633
1.001763
if self._error: raise compat.saved_exc(self._error) elif self._transport is None: raise HttpError('not connected') message = self._queue.get(timeout=self._timeout) if isinstance(message, Exception): raise compat.saved_exc(message) retu...
def getresponse(self)
Wait for and return a HTTP response. The return value will be a :class:`HttpMessage`. When this method returns only the response header has been read. The response body can be read using :meth:`~gruvi.Stream.read` and similar methods on the message :attr:`~HttpMessage.body`. No...
4.742342
4.868966
0.973994
s = sha1() with open(filepath, "rb") as f: buf = f.read(blocksize) s.update(buf) return s.hexdigest()
def unique_hash(filepath: str, blocksize: int=80)->str
Small function to generate a hash to uniquely generate a file. Default blocksize is `500`
2.880836
2.435941
1.182638
audiofile = AudioSegment.from_file(filename) if limit: audiofile = audiofile[:limit * 1000] data = np.fromstring(audiofile._data, np.int16) channels = [] for chn in range(audiofile.channels): channels.append(data[chn::audiofile.channels]) fs = audiofile.frame_rate ...
def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]
Reads any file supported by pydub (ffmpeg) and returns the data contained within. returns: (channels, samplerate)
2.426962
2.304486
1.053147
return os.path.splitext(os.path.basename(path))[0]
def path_to_songname(path: str)->str
Extracts song name from a filepath. Used to identify which songs have already been fingerprinted on disk.
3.600737
3.859793
0.932883
server = Server(protocol_factory) server.listen(address, ssl=ssl, family=family, flags=flags, backlog=backlog) return server
def create_server(protocol_factory, address=None, ssl=False, family=0, flags=0, ipc=False, backlog=128)
Create a new network server. This creates one or more :class:`pyuv.Handle` instances bound to *address*, puts them in listen mode and starts accepting new connections. For each accepted connection, a new transport is created which is connected to a new protocol instance obtained by calling *protocol_fa...
2.760819
3.953817
0.698267
if self._transport: raise RuntimeError('already connected') kwargs.setdefault('timeout', self._timeout) conn = create_connection(self._protocol_factory, address, **kwargs) self._transport = conn[0] self._transport._log = self._log self._protocol = con...
def connect(self, address, **kwargs)
Connect to *address* and wait for the connection to be established. See :func:`~gruvi.create_connection` for a description of *address* and the supported keyword arguments.
3.115382
2.93069
1.06302
if self._transport is None: return self._transport.close() self._transport._closed.wait() self._transport = None self._protocol = None
def close(self)
Close the connection.
4.363168
3.664776
1.190569
if ssl: context = ssl if hasattr(ssl, 'set_ciphers') \ else ssl(client) if callable(ssl) \ else create_default_context(True) transport = SslTransport(client, context, True) else: transport = Transport(cl...
def handle_connection(self, client, ssl)
Handle a new connection with handle *client*. This method exists so that it can be overridden in subclass. It is not intended to be called directly.
3.752281
3.775993
0.99372
handles = [] handle_args = () if isinstance(address, six.string_types): handle_type = pyuv.Pipe handle_args = (ipc,) addresses = [address] elif isinstance(address, tuple): handle_type = pyuv.TCP result = getaddrinfo(add...
def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128)
Create a new transport, bind it to *address*, and start listening for new connections. See :func:`create_server` for a description of *address* and the supported keyword arguments.
3.40767
3.487212
0.97719
for handle in self._handles: if not handle.closed: handle.close() del self._handles[:] for transport, _ in self.connections: transport.close() self._all_closed.wait()
def close(self)
Close the listening sockets and all accepted connections.
4.988868
4.990569
0.999659
global DEBUG, debug # The argd parameter for main() is for testing purposes only. argd = argd or docopt( USAGESTR, version=VERSIONSTR, script=SCRIPT, # Example usage of colr_docopt colors. colors={ 'header': {'fore': 'yellow'}, 'script': ...
def main(argd=None)
Main entry point, expects doctopt arg dict as argd.
5.195676
5.091924
1.020376