code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
with open(indexed_audio_file_abs_path, "wb") as f: pickle.dump(self.get_timestamps(), f, pickle.HIGHEST_PROTOCOL)
def save_indexed_audio(self, indexed_audio_file_abs_path)
Writes the corrected timestamps to a file. Timestamps are a python dictionary. Parameters ---------- indexed_audio_file_abs_path : str
2.847717
2.752114
1.034738
with open(indexed_audio_file_abs_path, "rb") as f: self.__timestamps = pickle.load(f)
def load_indexed_audio(self, indexed_audio_file_abs_path)
Parameters ---------- indexed_audio_file_abs_path : str
3.519301
4.098563
0.858667
return bool(re.search(".*".join(sub), sup))
def _is_subsequence_of(self, sub, sup)
Parameters ---------- sub : str sup : str Returns ------- bool
12.939256
15.153499
0.853879
def get_all_in(one, another): for element in one: if element in another: yield element def containment_check(sub, sup): return (set(Counter(sub).keys()).issubset( set(Counter(sup).keys()))) def containment_fre...
def _partial_search_validator(self, sub, sup, anagram=False, subsequence=False, supersequence=False)
It's responsible for validating the partial results of `search` method. If it returns True, the search would return its result. Else, search method would discard what it found and look for others. First, checks to see if all elements of `sub` is in `sup` with at least the same frequency...
4.292263
4.108762
1.044661
search_gen_rest_of_kwargs = { "audio_basename": audio_basename, "case_sensitive": case_sensitive, "subsequence": subsequence, "supersequence": supersequence, "timing_error": timing_error, "anagram": anagram, "missing_w...
def search_all(self, queries, audio_basename=None, case_sensitive=False, subsequence=False, supersequence=False, timing_error=0.0, anagram=False, missing_word_tolerance=0)
Returns a dictionary of all results of all of the queries for all of the audio files. All the specified parameters work per query. Parameters ---------- queries : [str] or str A list of the strings that'll be searched. If type of queries is `str`, it'll b...
2.442975
2.567037
0.951671
def indexes_in_transcript_to_start_end_second(index_tup, audio_basename): space_indexes = [i for i, x in enumerate( transcription[audio_basename]) if x == " "] space_indexes.sort(reverse=True) ...
def search_regexp(self, pattern, audio_basename=None)
First joins the words of the word_blocks of timestamps with space, per audio_basename. Then matches `pattern` and calculates the index of the word_block where the first and last word of the matched result appears in. Then presents the output like `search_all` method. Note that the leadi...
2.837855
2.648902
1.071333
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 ''' Returns a list of primes < n ''' sieve = [True] * (n/2) for i in xrange(3,int(n**0.5)+1,2): if sieve[i/2]: sieve[i*i/2::i] = [False] * ((n-i*i-1)/(2*i)+1) return [2]...
def rwh_primes1(n)
Returns a list of primes < n
1.65989
1.646753
1.007978
'''Multiplication in Galois Fields without using a precomputed look-up table (and thus it's slower) by using the standard carry-less multiplication + modular reduction using an irreducible prime polynomial.''' ### Define bitwise carry-less operations as inner functions ### def cl_mult(x,y): '''Bitw...
def gf_mult_noLUT_slow(x, y, prim=0)
Multiplication in Galois Fields without using a precomputed look-up table (and thus it's slower) by using the standard carry-less multiplication + modular reduction using an irreducible prime polynomial.
5.609053
4.525486
1.239436
'''Galois Field integer multiplication using Russian Peasant Multiplication algorithm (faster than the standard multiplication + modular reduction). If prim is 0 and carryless=False, then the function produces the result for a standard integers multiplication (no carry-less arithmetics nor modular reduction).''...
def gf_mult_noLUT(x, y, prim=0, field_charac_full=256, carryless=True)
Galois Field integer multiplication using Russian Peasant Multiplication algorithm (faster than the standard multiplication + modular reduction). If prim is 0 and carryless=False, then the function produces the result for a standard integers multiplication (no carry-less arithmetics nor modular reduction).
8.934613
5.246832
1.702859
'''Multiply two polynomials, inside Galois Field (but the procedure is generic). Optimized function by precomputation of log.''' # Pre-allocate the result array r = bytearray(len(p) + len(q) - 1) # Precompute the logarithm of p lp = [gf_log[p[i]] for i in xrange(len(p))] # Compute the polynomial...
def gf_poly_mul(p, q)
Multiply two polynomials, inside Galois Field (but the procedure is generic). Optimized function by precomputation of log.
5.15943
3.748172
1.376519
for i in xrange(len(p)): r[i + j] ^= gf_mul(p[i], q[j]) # equivalent to: r[i + j] = gf_add(r[i+j], gf_mul(p[i], q[j])) -- you can see it's your usual polynomial multiplication return r
def gf_poly_mul_simple(p, q): # simple equivalent way of multiplying two polynomials without precomputation, but thus it's slower '''Multiply two polynomials, inside Galois Field''' # Pre-allocate the result array r = bytearray(len(p) + len(q) - 1) # Compute the polynomial multiplication (just like the ...
Multiply two polynomials, inside Galois Field
3.737112
3.646304
1.024904
'''Fast polynomial division by using Extended Synthetic Division and optimized for GF(2^p) computations (doesn't work with standard polynomials outside of this galois field).''' # CAUTION: this function expects polynomials to follow the opposite convention at decoding: the terms must go from the biggest to lowe...
def gf_poly_div(dividend, divisor)
Fast polynomial division by using Extended Synthetic Division and optimized for GF(2^p) computations (doesn't work with standard polynomials outside of this galois field).
10.165225
8.431161
1.205673
'''Linear time implementation of polynomial squaring. For details, see paper: "A fast software implementation for arithmetic operations in GF (2n)". De Win, E., Bosselaers, A., Vandenberghe, S., De Gersem, P., & Vandewalle, J. (1996, January). In Advances in Cryptology - Asiacrypt'96 (pp. 65-76). Springer Berlin He...
def gf_poly_square(poly)
Linear time implementation of polynomial squaring. For details, see paper: "A fast software implementation for arithmetic operations in GF (2n)". De Win, E., Bosselaers, A., Vandenberghe, S., De Gersem, P., & Vandewalle, J. (1996, January). In Advances in Cryptology - Asiacrypt'96 (pp. 65-76). Springer Berlin Heidelber...
8.15899
3.022784
2.699164
'''Evaluates a polynomial in GF(2^p) given the value for x. This is based on Horner's scheme for maximum efficiency.''' y = poly[0] for i in xrange(1, len(poly)): y = gf_mul(y, x) ^ poly[i] return y
def gf_poly_eval(poly, x)
Evaluates a polynomial in GF(2^p) given the value for x. This is based on Horner's scheme for maximum efficiency.
4.576447
2.345882
1.950843
'''Generate an irreducible generator polynomial (necessary to encode a message into Reed-Solomon)''' g = bytearray([1]) for i in xrange(nsym): g = gf_poly_mul(g, [1, gf_pow(generator, i+fcr)]) return g
def rs_generator_poly(nsym, fcr=0, generator=2)
Generate an irreducible generator polynomial (necessary to encode a message into Reed-Solomon)
6.582948
3.825726
1.720706
'''Generate all irreducible generator polynomials up to max_nsym (usually you can use n, the length of the message+ecc). Very useful to reduce processing time if you want to encode using variable schemes and nsym rates.''' g_all = {} g_all[0] = g_all[1] = [1] for nsym in xrange(max_nsym): g_all[...
def rs_generator_poly_all(max_nsym, fcr=0, generator=2)
Generate all irreducible generator polynomials up to max_nsym (usually you can use n, the length of the message+ecc). Very useful to reduce processing time if you want to encode using variable schemes and nsym rates.
8.188491
2.173454
3.767502
'''Simple Reed-Solomon encoding (mainly an example for you to understand how it works, because it's slower than the inlined function below)''' global field_charac if (len(msg_in) + nsym) > field_charac: raise ValueError("Message is too long (%i when max is %i)" % (len(msg_in)+nsym, field_charac)) if gen...
def rs_simple_encode_msg(msg_in, nsym, fcr=0, generator=2, gen=None)
Simple Reed-Solomon encoding (mainly an example for you to understand how it works, because it's slower than the inlined function below)
6.929587
5.034453
1.376433
'''Reed-Solomon main encoding function, using polynomial division (Extended Synthetic Division, the fastest algorithm available to my knowledge), better explained at http://research.swtch.com/field''' global field_charac if (len(msg_in) + nsym) > field_charac: raise ValueError("Message is too long (%i when ...
def rs_encode_msg(msg_in, nsym, fcr=0, generator=2, gen=None)
Reed-Solomon main encoding function, using polynomial division (Extended Synthetic Division, the fastest algorithm available to my knowledge), better explained at http://research.swtch.com/field
9.054228
7.596738
1.191857
'''Given the received codeword msg and the number of error correcting symbols (nsym), computes the syndromes polynomial. Mathematically, it's essentially equivalent to a Fourrier Transform (Chien search being the inverse). ''' # Note the "[0] +" : we add a 0 coefficient for the lowest degree (the consta...
def rs_calc_syndromes(msg, nsym, fcr=0, generator=2)
Given the received codeword msg and the number of error correcting symbols (nsym), computes the syndromes polynomial. Mathematically, it's essentially equivalent to a Fourrier Transform (Chien search being the inverse).
21.563828
12.147223
1.775206
'''Compute the erasures/errors/errata locator polynomial from the erasures/errors/errata positions (the positions must be relative to the x coefficient, eg: "hello worldxxxxxxxxx" is tampered to "h_ll_ worldxxxxxxxxx" with xxxxxxxxx being the ecc of length n-k=9, here the string positions are [1, 4], but the coeffi...
def rs_find_errata_locator(e_pos, generator=2)
Compute the erasures/errors/errata locator polynomial from the erasures/errors/errata positions (the positions must be relative to the x coefficient, eg: "hello worldxxxxxxxxx" is tampered to "h_ll_ worldxxxxxxxxx" with xxxxxxxxx being the ecc of length n-k=9, here the string positions are [1, 4], but the coefficients ...
13.388133
5.623987
2.380541
'''Compute the error (or erasures if you supply sigma=erasures locator polynomial, or errata) evaluator polynomial Omega from the syndrome and the error/erasures/errata locator Sigma. Omega is already computed at the same time as Sigma inside the Berlekamp-Massey implemented above, but in case you modify Sigma, you...
def rs_find_error_evaluator(synd, err_loc, nsym)
Compute the error (or erasures if you supply sigma=erasures locator polynomial, or errata) evaluator polynomial Omega from the syndrome and the error/erasures/errata locator Sigma. Omega is already computed at the same time as Sigma inside the Berlekamp-Massey implemented above, but in case you modify Sigma, you can re...
13.017222
3.969483
3.279325
'''Find the roots (ie, where evaluation = zero) of error polynomial by bruteforce trial, this is a sort of Chien's search (but less efficient, Chien's search is a way to evaluate the polynomial such that each evaluation only takes constant time).''' # nmess = length of whole codeword (message + ecc symbols) ...
def rs_find_errors(err_loc, nmess, generator=2)
Find the roots (ie, where evaluation = zero) of error polynomial by bruteforce trial, this is a sort of Chien's search (but less efficient, Chien's search is a way to evaluate the polynomial such that each evaluation only takes constant time).
13.581536
9.130706
1.487457
'''Reed-Solomon main decoding function''' global field_charac if len(msg_in) > field_charac: # Note that it is in fact possible to encode/decode messages that are longer than field_charac, but because this will be above the field, this will generate more error positions during Chien Search than it s...
def rs_correct_msg(msg_in, nsym, fcr=0, generator=2, erase_pos=None, only_erasures=False)
Reed-Solomon main decoding function
7.257377
7.182334
1.010448
'''Reed-Solomon main decoding function, without using the modified Forney syndromes''' global field_charac if len(msg_in) > field_charac: raise ValueError("Message is too long (%i when max is %i)" % (len(msg_in), field_charac)) msg_out = bytearray(msg_in) # copy of message # erasures: s...
def rs_correct_msg_nofsynd(msg_in, nsym, fcr=0, generator=2, erase_pos=None, only_erasures=False)
Reed-Solomon main decoding function, without using the modified Forney syndromes
4.250029
4.033705
1.053629
'''Returns true if the message + ecc has no error of false otherwise (may not always catch a wrong decoding or a wrong message, particularly if there are too many errors -- above the Singleton bound --, but it usually does)''' return ( max(rs_calc_syndromes(msg, nsym, fcr, generator)) == 0 )
def rs_check(msg, nsym, fcr=0, generator=2)
Returns true if the message + ecc has no error of false otherwise (may not always catch a wrong decoding or a wrong message, particularly if there are too many errors -- above the Singleton bound --, but it usually does)
29.76466
2.585412
11.512542
'''Encode a message (ie, add the ecc symbols) using Reed-Solomon, whatever the length of the message because we use chunking''' if isinstance(data, str): data = bytearray(data, "latin-1") chunk_size = self.nsize - self.nsym enc = bytearray() for i in xrange(0, len(dat...
def encode(self, data)
Encode a message (ie, add the ecc symbols) using Reed-Solomon, whatever the length of the message because we use chunking
5.892349
3.000943
1.963499
'''Repair a message, whatever its size is, by using chunking''' # erase_pos is a list of positions where you know (or greatly suspect at least) there is an erasure (ie, wrong character but you know it's at this position). Just input the list of all positions you know there are errors, and this method wi...
def decode(self, data, erase_pos=None, only_erasures=False)
Repair a message, whatever its size is, by using chunking
7.317102
6.501808
1.125395
if already_seen is None: already_seen = set() if record['address'] not in already_seen: already_seen.add(record['address']) if 'refs' in record: for child in children( record, index, stop_types=stop_types ): if child['address'] not in already_seen: ...
def recurse( record, index, stop_types=STOP_TYPES,already_seen=None, type_group=False )
Depth first traversal of a tree, all children are yielded before parent record -- dictionary record to be recursed upon index -- mapping 'address' ids to dictionary records stop_types -- types which will *not* recurse already_seen -- set storing already-visited nodes yields the travers...
2.574896
2.447792
1.051926
if open is None: open = [] if seen is None: seen = set() for child in children( record, index, stop_types = stop_types ): if child['type'] in stop_types or child['type'] == LOOP_TYPE: continue if child['address'] in open: # loop has been found ...
def find_loops( record, index, stop_types = STOP_TYPES, open=None, seen = None )
Find all loops within the index and replace with loop records
2.491622
2.523758
0.987266
for loop in loops: loop = list(loop) members = [index[addr] for addr in loop] external_parents = list(set([ addr for addr in sum([shared.get(addr,[]) for addr in loop],[]) if addr not in loop ])) if external_parents: if len(external_p...
def promote_loops( loops, index, shared )
Turn loops into "objects" that can be processed normally
4.706289
4.711974
0.998793
result = [] for ref in record.get( key,[]): try: record = index[ref] except KeyError, err: #print 'No record for %s address %s in %s'%(key, ref, record['address'] ) pass # happens when an unreachable references a reachable that has been compressed out... ...
def children( record, index, key='refs', stop_types=STOP_TYPES )
Retrieve children records for given record
7.488065
7.402491
1.01156
types = {} for child in children( record, index, key, stop_types=stop_types ): types.setdefault(child['type'],[]).append( child ) return types
def children_types( record, index, key='refs', stop_types=STOP_TYPES )
Produce dictionary mapping type-key to instances for all children
2.961756
2.710263
1.092793
for record in recurse( overall_record, index, stop_types=stop_types, already_seen=already_seen, type_group=True, ): # anything with a totsize we've already processed... if record.get('totsize') is not None: continue rinfo = record ...
def recurse_module( overall_record, index, shared, stop_types=STOP_TYPES, already_seen=None, min_size=0 )
Creates a has-a recursive-cost hierarchy Mutates objects in-place to produce a hierarchy of memory usage based on reference-holding cost assignment
6.435147
6.580117
0.977968
for parent in targets: if not isinstance( parent, dict ): try: parent = index[parent] except KeyError, err: continue rewrite_references( parent[key], old, new, single_ref=single_ref )
def rewrite_refs( targets, old,new, index, key='refs', single_ref=False )
Rewrite key in all targets (from index if necessary) to replace old with new
4.312271
4.118441
1.047064
old,new = as_id(old),as_id(new) to_delete = [] for i,n in enumerate(sequence): if n == old: if new is None: to_delete.append( i ) else: sequence[i] = new if single_ref: new = None elif n == new ...
def rewrite_references( sequence, old, new, single_ref=False )
Rewrite parents to point to new in old sequence -- sequence of id references old -- old id new -- new id returns rewritten sequence
2.54213
2.634668
0.964877
return ( not child.get('refs',()) and ( not shared.get(child['address']) or shared.get(child['address']) == [parent['address']] ) )
def simple( child, shared, parent )
Return sub-set of children who are "simple" in the sense of group_children
7.32304
7.155785
1.023374
to_compress = [] for to_simplify in list(iterindex( index )): if not isinstance( to_simplify, dict ): continue for typ,kids in children_types( to_simplify, index, stop_types=stop_types ).items(): kids = [k for k in kids if k and simple(k,shared, to_simplify)] ...
def group_children( index, shared, min_kids=10, stop_types=STOP_TYPES, delete_children=True )
Collect like-type children into sub-groups of objects for objects with long children-lists Only group if: * there are more than X children of type Y * children are "simple" * individual children have no children themselves * individual children have no other parents...
3.577456
3.572908
1.001273
# things which will have their dictionaries compressed out to_delete = set() for to_simplify in iterindex(index): if to_simplify['address'] in to_delete: continue if to_simplify['type'] in simplify_dicts and not 'compressed' in to_simplify: refs =...
def simplify_dicts( index, shared, simplify_dicts=SIMPLIFY_DICTS, always_compress=ALWAYS_COMPRESS_DICTS )
Eliminate "noise" dictionary records from the index index -- overall index of objects (including metadata such as type records) shared -- parent-count mapping for records in index module/type/class dictionaries
4.159259
4.200969
0.990071
reachable = set() already_seen = set() for module in modules: for child in recurse( module, index, stop_types=stop_types, already_seen=already_seen): reachable.add( child['address'] ) return reachable
def find_reachable( modules, index, shared, stop_types=STOP_TYPES )
Find the set of all reachable objects from given root nodes (modules)
3.550405
3.265246
1.087331
for id,shares in shared.iteritems(): if id in reachable: # child is reachable filtered = [ x for x in shares if x in reachable # only those parents which are reachable ] if len(filtered) != len(shares): ...
def deparent_unreachable( reachable, shared )
Eliminate all parent-links from unreachable objects from reachable objects
6.227453
5.976416
1.042005
for v in iterindex( index ): v['parents'] = shared.get( v['address'], [] )
def bind_parents( index, shared )
Set parents on all items in index
10.933576
9.420609
1.160602
log.warn( '%s disconnected objects in %s total objects', len(disconnected), len(index)) natural_roots = [x for x in disconnected if x.get('refs') and not x.get('parents')] log.warn( '%s objects with no parents at all' ,len(natural_roots)) for natural_root in natural_roots: recurse_module( ...
def find_roots( disconnected, index, shared )
Find appropriate "root" objects from which to recurse the hierarchies Will generate a synthetic root for anything which doesn't have any parents...
5.25175
5.067362
1.036387
if key not in self.roots: root,self.rows = load( self.filename, include_interpreter = self.include_interpreter ) self.roots[key] = root return self.roots[key]
def get_root( self, key )
Retrieve the given root by type-key
6.216745
5.655668
1.099206
if not self.URL_TEMPLATE: raise NotImplementedError return self.URL_TEMPLATE.format(self=self)
def url(self)
The fetching target URL. The default behavior of this property is build URL string with the :const:`~brownant.dinergate.Dinergate.URL_TEMPLATE`. The subclasses could override :const:`~brownant.dinergate.Dinergate.URL_TEMPLATE` or use a different implementation.
6.743523
4.642512
1.452559
self.actions.append((method_name, args, kwargs))
def record_action(self, method_name, *args, **kwargs)
Record the method-calling action. The actions expect to be played on an target object. :param method_name: the name of called method. :param args: the general arguments for calling method. :param kwargs: the keyword arguments for calling method.
3.647785
5.210307
0.700109
for method_name, args, kwargs in self.actions: method = getattr(target, method_name) method(*args, **kwargs)
def play_actions(self, target)
Play record actions on the target object. :param target: the target which recive all record actions, is a brown ant app instance normally. :type target: :class:`~brownant.app.Brownant`
3.036921
3.97896
0.763245
def decorator(func): endpoint = "{func.__module__}:{func.__name__}".format(func=func) self.record_action("add_url_rule", host, rule, endpoint, **options) return func return decorator
def route(self, host, rule, **options)
The decorator to register wrapped function as the brown ant app. All optional parameters of this method are compatible with the :meth:`~brownant.app.Brownant.add_url_rule`. Registered functions or classes must be import-able with its qualified name. It is different from the :class:`~fl...
4.4113
4.809402
0.917224
if not isinstance(text, (bytes, text_type)): raise TypeError("must be string type") if isinstance(text, text_type): return text.encode(encoding) return text
def to_bytes_safe(text, encoding="utf-8")
Convert the input value into bytes type. If the input value is string type and could be encode as UTF-8 bytes, the encoded value will be returned. Otherwise, the encoding has failed, the origin value will be returned as well. :param text: the input value which could be string or bytes. :param enco...
3.487318
3.326035
1.048491
attr_name = self.attr_names[name] return getattr(obj, attr_name)
def get_attr(self, obj, name)
Get attribute of the target object with the configured attribute name in the :attr:`~brownant.pipeline.base.PipelineProperty.attr_names` of this instance. :param obj: the target object. :type obj: :class:`~brownant.dinergate.Dinergate` :param name: the internal name used in the ...
3.791746
4.172009
0.908854
rule = Rule(rule_string, host=host, endpoint=endpoint, **options) self.url_map.add(rule)
def add_url_rule(self, host, rule_string, endpoint, **options)
Add a url rule to the app instance. The url rule is the same with Flask apps and other Werkzeug apps. :param host: the matched hostname. e.g. "www.python.org" :param rule_string: the matched path pattern. e.g. "/news/<int:id>" :param endpoint: the endpoint name as a dispatching key suc...
2.527413
4.402966
0.574025
url = urllib.parse.urlparse(url_string) url = self.validate_url(url) url_adapter = self.url_map.bind(server_name=url.hostname, url_scheme=url.scheme, path_info=url.path) query_args = url_decode(url.q...
def parse_url(self, url_string)
Parse the URL string with the url map of this app instance. :param url_string: the origin URL string. :returns: the tuple as `(url, url_adapter, query_args)`, the url is parsed by the standard library `urlparse`, the url_adapter is from the werkzeug bound URL map, th...
3.142058
2.811693
1.117497
# fix up the non-ascii path url_path = to_bytes_safe(url.path) url_path = urllib.parse.quote(url_path, safe=b"/%") # fix up the non-ascii query url_query = to_bytes_safe(url.query) url_query = urllib.parse.quote(url_query, safe=b"?=&") url = urllib.pars...
def validate_url(self, url)
Validate the :class:`~urllib.parse.ParseResult` object. This method will make sure the :meth:`~brownant.app.BrownAnt.parse_url` could work as expected even meet a unexpected URL string. :param url: the parsed url. :type url: :class:`~urllib.parse.ParseResult`
2.57759
2.65108
0.972279
url, url_adapter, query_args = self.parse_url(url_string) try: endpoint, kwargs = url_adapter.match() except NotFound: raise NotSupported(url_string) except RequestRedirect as e: new_url = "{0.new_url}?{1}".format(e, url_encode(query_args)) ...
def dispatch_url(self, url_string)
Dispatch the URL string to the target endpoint function. :param url_string: the origin URL string. :returns: the return value of calling dispatched function.
3.208714
3.691072
0.869318
if isinstance(site, string_types): site = import_string(site) site.play_actions(target=self)
def mount_site(self, site)
Mount a supported site to this app instance. :param site: the site instance be mounted.
10.211308
14.238583
0.717158
return self._makeApiCall(self.funcinfo["ping"], *args, **kwargs)
def ping(self, *args, **kwargs)
Ping Server Respond without doing anything. This endpoint is used to check that the service is up. This method is ``stable``
15.555004
20.579929
0.755834
return self._makeApiCall(self.funcinfo["githubWebHookConsumer"], *args, **kwargs)
def githubWebHookConsumer(self, *args, **kwargs)
Consume GitHub WebHook Capture a GitHub event and publish it via pulse, if it's a push, release or pull request. This method is ``experimental``
12.283296
17.192822
0.714443
return self._makeApiCall(self.funcinfo["badge"], *args, **kwargs)
def badge(self, *args, **kwargs)
Latest Build Status Badge Checks the status of the latest build of a given branch and returns corresponding badge svg. This method is ``experimental``
17.162397
21.199625
0.809561
return self._makeApiCall(self.funcinfo["createComment"], *args, **kwargs)
def createComment(self, *args, **kwargs)
Post a comment on a given GitHub Issue or Pull Request For a given Issue or Pull Request of a repository, this will write a new message. This method takes input: ``v1/create-comment.json#`` This method is ``experimental``
13.110386
19.620392
0.668202
w = lambda l: l[random.randrange(len(l))] er = lambda w: w[:-1]+'ier' if w.endswith('y') else (w+'r' if w.endswith('e') else w+'er') s = lambda w: w+'s' punc = lambda c, *l: " ".join(l)+c sentence = lambda *l: lambda: " ".join(l) pick = lambda *l: (l[random.randrange(len(l))])() while T...
def lorem_gotham()
Cheesy Gothic Poetry Generator Uses Python generators to yield eternal angst. When you need to generate random verbiage to test your code or typographic design, let's face it... Lorem Ipsum and "the quick brown fox" are old and boring! What you need is something with *flavor*, the kind of thing a...
6.055866
6.065129
0.998473
w = lambda l: l[random.randrange(len(l))] sentence = lambda *l: lambda: " ".join(l) pick = lambda *l: (l[random.randrange(len(l))])() return pick( sentence('why i',w(me_verb)), sentence(w(place)), sentence('a',w(adj),w(adj),w(place)), sentence('the',w(them)))
def lorem_gotham_title()
Names your poem
7.508852
7.424128
1.011412
print() print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print(lorem_gotham_title().center(50)) print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print() poem = lorem_gotham() for n in range(16): if n in (4, 8, 12): print() print(next(poe...
def main()
I provide a command-line interface for this module
2.774493
2.7817
0.997409
return await self._makeApiCall(self.funcinfo["listWorkerTypes"], *args, **kwargs)
async def listWorkerTypes(self, *args, **kwargs)
See the list of worker types which are known to be managed This method is only for debugging the ec2-manager This method gives output: ``v1/list-worker-types.json#`` This method is ``experimental``
11.76386
14.655767
0.802678
return await self._makeApiCall(self.funcinfo["runInstance"], *args, **kwargs)
async def runInstance(self, *args, **kwargs)
Run an instance Request an instance of a worker type This method takes input: ``v1/run-instance-request.json#`` This method is ``experimental``
14.319862
22.150627
0.646477
return await self._makeApiCall(self.funcinfo["workerTypeStats"], *args, **kwargs)
async def workerTypeStats(self, *args, **kwargs)
Look up the resource stats for a workerType Return an object which has a generic state description. This only contains counts of instances This method gives output: ``v1/worker-type-resources.json#`` This method is ``experimental``
11.873431
17.092812
0.694645
return await self._makeApiCall(self.funcinfo["workerTypeHealth"], *args, **kwargs)
async def workerTypeHealth(self, *args, **kwargs)
Look up the resource health for a workerType Return a view of the health of a given worker type This method gives output: ``v1/health.json#`` This method is ``experimental``
12.592219
18.226162
0.690887
return await self._makeApiCall(self.funcinfo["workerTypeErrors"], *args, **kwargs)
async def workerTypeErrors(self, *args, **kwargs)
Look up the most recent errors of a workerType Return a list of the most recent errors encountered by a worker type This method gives output: ``v1/errors.json#`` This method is ``experimental``
13.59235
17.631807
0.770899
return await self._makeApiCall(self.funcinfo["workerTypeState"], *args, **kwargs)
async def workerTypeState(self, *args, **kwargs)
Look up the resource state for a workerType Return state information for a given worker type This method gives output: ``v1/worker-type-state.json#`` This method is ``experimental``
12.628479
16.56139
0.762525
return await self._makeApiCall(self.funcinfo["ensureKeyPair"], *args, **kwargs)
async def ensureKeyPair(self, *args, **kwargs)
Ensure a KeyPair for a given worker type exists Idempotently ensure that a keypair of a given name exists This method takes input: ``v1/create-key-pair.json#`` This method is ``experimental``
14.652827
23.665508
0.619164
return await self._makeApiCall(self.funcinfo["removeKeyPair"], *args, **kwargs)
async def removeKeyPair(self, *args, **kwargs)
Ensure a KeyPair for a given worker type does not exist Ensure that a keypair of a given name does not exist. This method is ``experimental``
14.370121
21.72608
0.661423
return await self._makeApiCall(self.funcinfo["terminateInstance"], *args, **kwargs)
async def terminateInstance(self, *args, **kwargs)
Terminate an instance Terminate an instance in a specified region This method is ``experimental``
13.152555
19.271217
0.682497
return await self._makeApiCall(self.funcinfo["getSpecificPrices"], *args, **kwargs)
async def getSpecificPrices(self, *args, **kwargs)
Request prices for EC2 Return a list of possible prices for EC2 This method takes input: ``v1/prices-request.json#`` This method gives output: ``v1/prices.json#`` This method is ``experimental``
10.376702
15.870541
0.653834
return await self._makeApiCall(self.funcinfo["getHealth"], *args, **kwargs)
async def getHealth(self, *args, **kwargs)
Get EC2 account health metrics Give some basic stats on the health of our EC2 account This method gives output: ``v1/health.json#`` This method is ``experimental``
12.868346
18.74979
0.686319
return await self._makeApiCall(self.funcinfo["getRecentErrors"], *args, **kwargs)
async def getRecentErrors(self, *args, **kwargs)
Look up the most recent errors in the provisioner across all worker types Return a list of recent errors encountered This method gives output: ``v1/errors.json#`` This method is ``experimental``
11.993319
19.613049
0.611497
return await self._makeApiCall(self.funcinfo["regions"], *args, **kwargs)
async def regions(self, *args, **kwargs)
See the list of regions managed by this ec2-manager This method is only for debugging the ec2-manager This method is ``experimental``
14.847516
17.857334
0.831452
return await self._makeApiCall(self.funcinfo["amiUsage"], *args, **kwargs)
async def amiUsage(self, *args, **kwargs)
See the list of AMIs and their usage List AMIs and their usage by returning a list of objects in the form: { region: string volumetype: string lastused: timestamp } This method is ``experimental``
12.543196
17.804184
0.704508
return await self._makeApiCall(self.funcinfo["ebsUsage"], *args, **kwargs)
async def ebsUsage(self, *args, **kwargs)
See the current EBS volume usage list Lists current EBS volume usage by returning a list of objects that are uniquely defined by {region, volumetype, state} in the form: { region: string, volumetype: string, state: string, totalcount: integer, tot...
12.550022
18.930984
0.662936
return await self._makeApiCall(self.funcinfo["dbpoolStats"], *args, **kwargs)
async def dbpoolStats(self, *args, **kwargs)
Statistics on the Database client pool This method is only for debugging the ec2-manager This method is ``experimental``
12.094499
14.63349
0.826494
return await self._makeApiCall(self.funcinfo["sqsStats"], *args, **kwargs)
async def sqsStats(self, *args, **kwargs)
Statistics on the sqs queues This method is only for debugging the ec2-manager This method is ``experimental``
13.580398
16.452261
0.825443
return await self._makeApiCall(self.funcinfo["purgeQueues"], *args, **kwargs)
async def purgeQueues(self, *args, **kwargs)
Purge the SQS queues This method is only for debugging the ec2-manager This method is ``experimental``
13.929899
15.53612
0.896614
ref = { 'exchange': 'pull-request', 'name': 'pullRequest', 'routingKey': [ { 'constant': 'primary', 'multipleWords': False, 'name': 'routingKeyKind', }, { ...
def pullRequest(self, *args, **kwargs)
GitHub Pull Request Event When a GitHub pull request event is posted it will be broadcast on this exchange with the designated `organization` and `repository` in the routing-key along with event specific metadata in the payload. This exchange outputs: ``v1/github-pull-request-message.j...
4.743968
3.114724
1.523078
ref = { 'exchange': 'push', 'name': 'push', 'routingKey': [ { 'constant': 'primary', 'multipleWords': False, 'name': 'routingKeyKind', }, { ...
def push(self, *args, **kwargs)
GitHub push Event When a GitHub push event is posted it will be broadcast on this exchange with the designated `organization` and `repository` in the routing-key along with event specific metadata in the payload. This exchange outputs: ``v1/github-push-message.json#``This exchange take...
6.341426
3.62078
1.751398
ref = { 'exchange': 'release', 'name': 'release', 'routingKey': [ { 'constant': 'primary', 'multipleWords': False, 'name': 'routingKeyKind', }, { ...
def release(self, *args, **kwargs)
GitHub release Event When a GitHub release event is posted it will be broadcast on this exchange with the designated `organization` and `repository` in the routing-key along with event specific metadata in the payload. This exchange outputs: ``v1/github-release-message.json#``This exch...
6.421085
3.58011
1.793544
ref = { 'exchange': 'task-group-creation-requested', 'name': 'taskGroupCreationRequested', 'routingKey': [ { 'constant': 'primary', 'multipleWords': False, 'name': 'routingKeyKind', ...
def taskGroupCreationRequested(self, *args, **kwargs)
tc-gh requested the Queue service to create all the tasks in a group supposed to signal that taskCreate API has been called for every task in the task group for this particular repo and this particular organization currently used for creating initial status indicators in GitHub UI using Statuse...
5.164251
3.238618
1.594585
degrees = 0 while True: t1 = time.time() with Frame() as frame: oval_width = frame.width oval_height = frame.height / 3.0 cube_height = int(oval_height * 2) (p1_x, p1_y) = ellipse_point(degrees, oval_width, oval_height) (p2_x, p2...
def rotating_cube(degree_change=3, frame_rate=3)
Rotating cube program How it works: 1. Create two imaginary ellipses 2. Sized to fit in the top third and bottom third of screen 3. Create four imaginary points on each ellipse 4. Make those points the top and bottom corners of your cube 5. Connect the lines and render 6. Rotat...
1.536965
1.497388
1.026431
r steep = abs(y1 - y0) > abs(x1 - x0) if steep: (x0, y0) = (y0, x0) (x1, y1) = (y1, x1) if x0 > x1: (x0, x1) = (x1, x0) (y0, y1) = (y1, y0) deltax = x1 - x0 deltay = abs(y1 - y0) error = deltax / 2 y = y0 ...
def line(self, x0, y0, x1, y1, c='*')
r"""Draws a line Who would have thought this would be so complicated? Thanks again Wikipedia_ <3 .. _Wikipedia: http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
1.594346
1.535929
1.038034
return self._makeApiCall(self.funcinfo["terminateWorkerType"], *args, **kwargs)
def terminateWorkerType(self, *args, **kwargs)
Terminate all resources from a worker type Terminate all instances for this worker type This method is ``experimental``
12.028389
15.930218
0.755067
return self._makeApiCall(self.funcinfo["getPrices"], *args, **kwargs)
def getPrices(self, *args, **kwargs)
Request prices for EC2 Return a list of possible prices for EC2 This method gives output: ``v1/prices.json#`` This method is ``experimental``
12.163607
16.255159
0.748292
return self._makeApiCall(self.funcinfo["allState"], *args, **kwargs)
def allState(self, *args, **kwargs)
List out the entire internal state This method is only for debugging the ec2-manager This method is ``experimental``
13.118561
14.940805
0.878036
return self._makeApiCall(self.funcinfo["task"], *args, **kwargs)
def task(self, *args, **kwargs)
Get Task Definition This end-point will return the task-definition. Notice that the task definition may have been modified by queue, if an optional property is not specified the queue may provide a default value. This method gives output: ``v1/task.json#`` This method is ``sta...
19.104469
24.327921
0.78529
return self._makeApiCall(self.funcinfo["defineTask"], *args, **kwargs)
def defineTask(self, *args, **kwargs)
Define Task **Deprecated**, this is the same as `createTask` with a **self-dependency**. This is only present for legacy. This method takes input: ``v1/create-task-request.json#`` This method gives output: ``v1/task-status-response.json#`` This method is ``deprecated``
15.445311
18.036623
0.856331
return self._makeApiCall(self.funcinfo["scheduleTask"], *args, **kwargs)
def scheduleTask(self, *args, **kwargs)
Schedule Defined Task scheduleTask will schedule a task to be executed, even if it has unresolved dependencies. A task would otherwise only be scheduled if its dependencies were resolved. This is useful if you have defined a task that depends on itself or on some other task tha...
16.058744
20.767347
0.773269
return self._makeApiCall(self.funcinfo["rerunTask"], *args, **kwargs)
def rerunTask(self, *args, **kwargs)
Rerun a Resolved Task This method _reruns_ a previously resolved task, even if it was _completed_. This is useful if your task completes unsuccessfully, and you just want to run it from scratch again. This will also reset the number of `retries` allowed. This method is deprecat...
12.936927
19.440821
0.665452
return self._makeApiCall(self.funcinfo["cancelTask"], *args, **kwargs)
def cancelTask(self, *args, **kwargs)
Cancel Task This method will cancel a task that is either `unscheduled`, `pending` or `running`. It will resolve the current run as `exception` with `reasonResolved` set to `canceled`. If the task isn't scheduled yet, ie. it doesn't have any runs, an initial run will be added and resolv...
14.122085
20.1134
0.702123
return self._makeApiCall(self.funcinfo["reportFailed"], *args, **kwargs)
def reportFailed(self, *args, **kwargs)
Report Run Failed Report a run failed, resolving the run as `failed`. Use this to resolve a run that failed because the task specific code behaved unexpectedly. For example the task exited non-zero, or didn't produce expected output. Do not use this if the task couldn't be run because ...
17.442177
17.939232
0.972292
return self._makeApiCall(self.funcinfo["reportException"], *args, **kwargs)
def reportException(self, *args, **kwargs)
Report Task Exception Resolve a run as _exception_. Generally, you will want to report tasks as failed instead of exception. You should `reportException` if, * The `task.payload` is invalid, * Non-existent resources are referenced, * Declared actions cannot be executed du...
17.474182
19.382813
0.90153
return self._makeApiCall(self.funcinfo["createArtifact"], *args, **kwargs)
def createArtifact(self, *args, **kwargs)
Create Artifact This API end-point creates an artifact for a specific run of a task. This should **only** be used by a worker currently operating on this task, or from a process running within the task (ie. on the worker). All artifacts must specify when they `expires`, the queue will ...
13.115017
30.167976
0.434733
return self._makeApiCall(self.funcinfo["completeArtifact"], *args, **kwargs)
def completeArtifact(self, *args, **kwargs)
Complete Artifact This endpoint finalises an upload done through the blob `storageType`. The queue will ensure that the task/run is still allowing artifacts to be uploaded. For single-part S3 blob artifacts, this endpoint will simply ensure the artifact is present in S3. For multipart...
13.476502
21.221769
0.635032
return self._makeApiCall(self.funcinfo["listProvisioners"], *args, **kwargs)
def listProvisioners(self, *args, **kwargs)
Get a list of all active provisioners Get all active provisioners. The term "provisioner" is taken broadly to mean anything with a provisionerId. This does not necessarily mean there is an associated service performing any provisioning activity. The response is paged. If this ...
11.052512
13.216747
0.836251
return self._makeApiCall(self.funcinfo["getProvisioner"], *args, **kwargs)
def getProvisioner(self, *args, **kwargs)
Get an active provisioner Get an active provisioner. The term "provisioner" is taken broadly to mean anything with a provisionerId. This does not necessarily mean there is an associated service performing any provisioning activity. This method gives output: ``v1/provisioner-re...
12.461894
13.479311
0.92452
return self._makeApiCall(self.funcinfo["declareProvisioner"], *args, **kwargs)
def declareProvisioner(self, *args, **kwargs)
Update a provisioner Declare a provisioner, supplying some details about it. `declareProvisioner` allows updating one or more properties of a provisioner as long as the required scopes are possessed. For example, a request to update the `aws-provisioner-v1` provisioner with a body `{de...
12.993777
16.638958
0.780925