code
stringlengths
1
18.2k
def warn_if_outdated(package, version, raise_exceptions=False, background=True, ): """ Higher level convenience function using check_outdated. The package and version arguments are the same. If the package is outdated, a warning (OutdatedPackageWarning) will be emitted. Any exception in check_outdated will be converted...
out of date. Your version is %s, the latest is %s.' % (package, version, latest), OutdatedPackageWarning, ) if background: thread = Thread(target=check) thread.start() else: check()
def _generate_sympify_namespace( independent_variables, dependent_variables, helper_functions ): """Generate the link between the symbols of the derivatives and the sympy Derivative operation. Parameters ---------- independent_variable : str name of the independant variable ("x") dependent_variables : iterable of str n...
order ) for order, var in product( range(1, 10), dependent_variables + helper_functions ) } ) logging.debug("sympy namespace: %s" % namespace) return namespace
def _prepare_output_multi(self, model): """If printing to a different file per model, change the file for the current model""" model_name = model.__name__ current_path = os.path.join(self._output_path, '{model}.{extension}'.format( model=model_name, extension=self.EXTENSION, )) self._outfile = codecs.open(current_path,...
def prepare_buckets(self): """ loads buckets to bucket cache. """ for mdl in self.registry.get_base_models(): bucket = mdl(super_context).objects.adapter.bucket self.buckets[bucket.name] = bucket
def _print_split_model(self, path, apps_models): """ Print each model in apps_models into its own file. """ for app, models in apps_models: for model in models: model_name = model().title if self._has_extension(path): model_path = re.sub(r'^(.*)[.](\w+)$', r'\1.%s.%s.\2' % (app, model_name), path) else: model_path = '%...
def _print_split_app(self, path, apps_models): """ Print each app in apps_models associative list into its own file. """ for app, models in apps_models: # Convert dir/file.puml to dir/file.app.puml to print to an app specific file if self._has_extension(path): app_path = re.sub(r'^(.*)[.](\w+)$', r'\1.%s.\2' % app, pat...
def _print_single_file(self, path, apps_models): """ Print apps_models which contains a list of 2-tuples containing apps and their models into a single file. """ if path: outfile = codecs.open(path, 'w', encoding='utf-8') self._print = lambda s: outfile.write(s + '\n') self._print(self._diagram_start) for app, app_mode...
def _print_app(self, app, models): """ Print the models of app, showing them in a package. """ self._print(self._app_start % app) self._print_models(models) self._print(self._app_end)
def _print_fields(self, fields): """Print the fields, padding the names as necessary to align them.""" # Prepare a formatting string that aligns the names and types based on the longest ones longest_name = max(fields, key=lambda f: len(f[1]))[1] longest_type = max(fields, key=lambda f: len(f[2]))[2] field_format = '%s%...
def _format_listnodes(self, listnodes): """ Format ListNodes and their fields into tuples that can be printed with _print_fields(). """ fields = list() for name, node in listnodes: fields.append(('--', '', '', '--')) fields.append(('', '**%s(ListNode)**' % name, '', '')) for link in node.get_links(): linked_model = lin...
def _get_model_fields(self, model, prefix=_field_prefix): """ Find all fields of given model that are not default models. """ fields = list() for field_name, field in model()._ordered_fields: # Filter the default fields if field_name not in getattr(model, '_DEFAULT_BASE_FIELDS', []): type_name = utils.to_camel(field.so...
def _get_model_nodes(self, model): """ Find all the non-auto created nodes of the model. """ nodes = [(name, node) for name, node in model._nodes.items() if node._is_auto_created is False] nodes.sort(key=lambda n: n[0]) return nodes
def _format_links_fields(self, links): """ Format the fields containing links into 4-tuples printable by _print_fields(). """ fields = list() for link in links: linked_model = link['mdl'](super_context) null = self._marker_true if link['null'] is True else self._marker_false # In LinkProxy, if reverse_name is empty the...
def _print_links(self, model, links): """ Print links that start from model. """ for link in links: if link['o2o'] is True: link_type = self._one_to_one elif link['m2m'] is True: link_type = self._many_to_many else: link_type = self._one_to_many linked_model = link['mdl'](super_context) self._print('%s %s %s' % (model....
def main(): """ Usage: with (--version | <command>) Arguments: command The command to use as prefix to your context. Options: -h --help Show this screen. --version Show the current version. """ arguments = docopt(main.__doc__) if arguments.get('--version'): print('with {}'.format(withtool.__version__)) sys.exit() while...
def printBasicInfo(onto): """ Terminal printing of basic ontology information """ rdfGraph = onto.rdfGraph print("_" * 50, "\n") print("TRIPLES = %s" % len(rdfGraph)) print("_" * 50) print("\nNAMESPACES:\n") for x in onto.ontologyNamespaces: print("%s : %s" % (x[0], x[1])) print("_" * 50, "\n") print("ONTOLOGY METADATA...
def entityTriples(rdfGraph, anEntity, excludeProps=False, excludeBNodes=False, orderProps=[RDF, RDFS, OWL.OWLNS, DC.DCNS]): """ Returns the pred-obj for any given resource, excluding selected ones.. Sorting: by default results are sorted alphabetically and according to namespaces: [RDF, RDFS, OWL.OWLNS, DC.DCNS] """ te...
elif orderProps: # default to alpha sorting unless False temp = sorted(temp, key=lambda tup: tup[0]) # if niceURI: # temp = [(uri2niceString(ontology, y), z) for y,z in temp] return temp
def _distinct(row1, row2): """ Returns a list of distinct (or none overlapping) intervals if two intervals are overlapping. Returns None if the two intervals are none overlapping. The list can have 2 or 3 intervals. :param tuple[int,int] row1: The first interval. :param tuple[int,int] row2: The second interval. :rtype:...
# row2: |-------| return None # [(row2[0], row2[1]), (row1[0], row1[1])] if relation == Allen.X_OVERLAPS_WITH_Y: # row1: |-----------| # row2: |----------| return [(row1[0], row2[0] - 1), (row2[0], row1[1]), (row1[1] + 1, row2[1])] if relation == Allen.X_OVERLAPS_WITH_Y_INVERSE: # row1: |----------| # row2: |----------...
if relation == Allen.X_FINISHES_Y: # row1: |------| # row2: |----------------| return [(row2[0], row1[0] - 1), (row1[0], row1[1])] if relation == Allen.X_FINISHES_Y_INVERSE: # row1: |----------------| # row2: |------| return [(row1[0], row2[0] - 1), (row2[0], row2[1])] if relation == Allen.X_EQUAL_Y: # row1: |---------...
def _add_interval(all_intervals, new_interval): """ Adds a new interval to a set of none overlapping intervals. :param set[(int,int)] all_intervals: The set of distinct intervals. :param (int,int) new_interval: The new interval. """ intervals = None old_interval = None for old_interval in all_intervals: intervals = Typ...
def _derive_distinct_intervals(self, rows): """ Returns the set of distinct intervals in a row set. :param list[dict[str,T]] rows: The rows set. :rtype: set[(int,int)] """ ret = set() for row in rows: self._add_interval(ret, (row[self._key_start_date], row[self._key_end_date])) return ret
def condense(self): """ Condense the data set to the distinct intervals based on the pseudo key. """ for pseudo_key, rows in self._rows.items(): tmp1 = [] intervals = sorted(self._derive_distinct_intervals(rows)) for interval in intervals: tmp2 = dict(zip(self._pseudo_key, pseudo_key)) tmp2[self._key_start_date] = inte...
def _terminate_procs(procs): """ Terminate all processes in the process dictionary """ logging.warn("Stopping all remaining processes") for proc, g in procs.values(): logging.debug("[%s] SIGTERM", proc.pid) try: proc.terminate() except OSError as e: # we don't care if the process we tried to kill didn't exist. if e.err...
def write_summary(all_procs, summary_file): """ Write a summary of all run processes to summary_file in tab-delimited format. """ if not summary_file: return with summary_file: writer = csv.writer(summary_file, delimiter='\t', lineterminator='\n') writer.writerow(('directory', 'command', 'start_time', 'end_time', 'run_...
def template_subs_file(in_file, out_fobj, d): """ Substitute template arguments in in_file from variables in d, write the result to out_fobj. """ with open(in_file, 'r') as in_fobj: for line in in_fobj: out_fobj.write(line.format(**d))
def worker(data, json_file): """ Handle parameter substitution and execute command as child process. """ # PERHAPS TODO: Support either full or relative paths. with open(json_file) as fp: d = json.load(fp) json_directory = os.path.dirname(json_file) def p(*parts): return os.path.join(json_directory, *parts) # STDOUT an...
" "Continuing with existing permissions", output_template) else: raise work = data['template'].format(**d) if savecmd_file: with open(p(savecmd_file), 'w') as command_file: command_file.write(work + "\n") # View what actions will take place in dry_run mode. if data['dry_run']: logging.info("%s - Dry run of %s\n", p(), ...
Error executing %s - %s", p(), work, e) raise e
def extant_file(x): """ 'Type' for argparse - checks that file exists but does not open. """ if not os.path.exists(x): raise argparse.ArgumentError("{0} does not exist".format(x)) return x
def parse_arguments(): """ Grab options and json files. """ max_procs = MAX_PROCS dry_run = DRY_RUN logging.basicConfig(level=logging.INFO, stream=sys.stdout, format='%(asctime)s * %(levelname)s * %(message)s') parser = argparse.ArgumentParser(description="""nestrun - substitute values into a template and run commands ...
help="""Don't create a log file""") parser.add_argument('--dry-run', action='store_true', help="""Dry run mode, does not execute commands.""", default=False) parser.add_argument('--summary-file', type=argparse.FileType('w'), help="""Write a summary of the run to the specified file""") ctrl_group = parser.add_argument_g...
if (not os.access(arguments.template_file, os.X_OK) and not arguments.dry_run): parser.error( "{0} is not executable. Specify a template.".format( arguments.template_file)) if not (arguments.template or arguments.template_file): parser.exit("Error: Please specify either a template " "or a template file") logging.info('...
def complete(self, return_code): """ Mark the process as complete with provided return_code """ self.return_code = return_code self.status = 'COMPLETE' if not return_code else 'FAILED' self.end_time = datetime.datetime.now()
def log_tail(self, nlines=10): """ Return the last ``nlines`` lines of the log file """ log_path = os.path.join(self.working_dir, self.log_name) with open(log_path) as fp: d = collections.deque(maxlen=nlines) d.extend(fp) return ''.join(d)
def list(self,table, **kparams): """ get a collection of records by table name. returns a collection of SnowRecord obj. """ records = self.api.list(table, **kparams) return records
def get(self,table, sys_id): """ get a single record by table name and sys_id returns a SnowRecord obj. """ record = self.api.get(table, sys_id) return record
def update(self,table, sys_id, **kparams): """ update a record via table api, kparams being the dict of PUT params to update. returns a SnowRecord obj. """ record = self.api.update(table, sys_id, **kparams) return record
def __sweeten(self, dumper: 'Dumper', class_: Type, node: Node) -> None: """Applies the user's yatiml_sweeten() function(s), if any. Sweetening is done for the base classes first, then for the \ derived classes, down the hierarchy to the class we're \ constructing. Args: dumper: The dumper that is dumping this object. ...
def select_product(): """ binds the frozen context the selected features should be called only once - calls after the first call have no effect """ global _product_selected if _product_selected: # tss already bound ... ignore return _product_selected = True from django_productline import context, template featuremonkey...
overextends import models
def serialize(self, format="turtle"): """ xml, n3, turtle, nt, pretty-xml, trix are built in""" if self.triples: if not self.rdfgraph: self._buildGraph() return self.rdfgraph.serialize(format=format) else: return None
def bestLabel(self, prefLanguage="en", qname_allowed=True, quotes=True): """ facility for extrating the best available label for an entity ..This checks RFDS.label, SKOS.prefLabel and finally the qname local component """ test = self.getValuesForProperty(rdflib.RDFS.label) out = "" if test: out = firstEnglishStringInLi...
def bestDescription(self, prefLanguage="en"): """ facility for extrating the best available description for an entity ..This checks RFDS.label, SKOS.prefLabel and finally the qname local component """ test_preds = [rdflib.RDFS.comment, rdflib.namespace.DCTERMS.description, rdflib.namespace.DC.description, rdflib.namesp...
def stats(self): """ shotcut to pull out useful info for interactive use """ printDebug("Classes.....: %d" % len(self.classes)) printDebug("Properties..: %d" % len(self.properties))
def mkp(*args, **kwargs): """ Generate a directory path, and create it if requested. .. code-block:: Python filepath = mkp('base', 'folder', 'file') dirpath = mkp('root', 'path', 'folder', mk=True) Args: \*args: File or directory path segments to be concatenated mk (bool): Make the directory (if it doesn't exist) Retur...
def convert_bytes(value): """ Reduces bytes to more convenient units (i.e. KiB, GiB, TiB, etc.). Args: values (int): Value in Bytes Returns: tup (tuple): Tuple of value, unit (e.g. (10, 'MiB')) """ n = np.rint(len(str(value))/4).astype(int) return value/(1024**n), sizes[n]
def get_internal_modules(key='exa'): """ Get a list of modules belonging to the given package. Args: key (str): Package or library name (e.g. "exa") """ key += '.' return [v for k, v in sys.modules.items() if k.startswith(key)]
def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None): """ animation happens between startframe and stopframe the value is None before aliveframe, and after deathframe * if aliveframe is not specified it defaults to startframe * if deathframe is not specified it defaults to stopfra...
else: noise_value = 0 return self.equation.evalf(subs={t: parameter_value}) + noise_value
def get_user_ip(request): """Return user ip :param request: Django request object :return: user ip """ ip = get_real_ip(request) if ip is None: ip = get_ip(request) if ip is None: ip = '127.0.0.1' return ip
def load_environment(global_conf, app_conf): """Configure the Pylons environment via the ``pylons.config`` object """ # Pylons paths root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paths = dict(root=root, controllers=os.path.join(root, 'controllers'), static_files=os.path.join(root, 'public'), templa...
def msvd(m): """Modified singular value decomposition. Returns U, S, V where Udagger M V = diag(S) and the singular values are sorted in ascending order (small to large). """ u, s, vdgr = np.linalg.svd(m) order = s.argsort() # reverse the n first columns of u s = s[order] u= u[:,order] vdgr = vdgr[order] return u, s, v...
def mtakfac(m): """Modified Takagi factorization of a (complex) symmetric matrix. Returns U, S where U^T M U = diag(S) and the singular values are sorted in ascending order (small to large). """ u, s, v = msvd(np.asarray(m, dtype=complex)) f = np.sqrt(u.conj().T @ v.conj()) w = v @ f return w, s
def _parse_parameters(self, resource, params): '''Creates a dictionary from query_string and `params` Transforms the `?key=value&...` to a {'key': 'value'} and adds (or overwrites if already present) the value with the dictionary in `params`. ''' # remove params from resource URI (needed for paginated stuff) parsed_uri...
def get_variant_dict(variant_line, header_line=None): """Parse a variant line Split a variant line and map the fields on the header columns Args: variant_line (str): A vcf variant line header_line (list): A list with the header columns Returns: variant_dict (dict): A variant dictionary """ if not header_line: logger.de...
def get_info_dict(info_line): """Parse a info field of a variant Make a dictionary from the info field of a vcf variant. Keys are the info keys and values are the raw strings from the vcf If the field only have a key (no value), value of infodict is True. Args: info_line (str): The info field of a vcf variant Returns: ...
def get_variant_id(variant_dict=None, variant_line=None): """Build a variant id The variant id is a string made of CHROM_POS_REF_ALT Args: variant_dict (dict): A variant dictionary Returns: variant_id (str) """ if variant_dict: chrom = variant_dict['CHROM'] position = variant_dict['POS'] ref = variant_dict['REF'] alt =...
def get_vep_info(vep_string, vep_header): """Make the vep annotations into a dictionaries A vep dictionary will have the vep column names as keys and the vep annotations as values. The dictionaries are stored in a list Args: vep_string (string): A string with the CSQ annotation vep_header (list): A list with the vep he...
def get_snpeff_info(snpeff_string, snpeff_header): """Make the vep annotations into a dictionaries A snpeff dictionary will have the snpeff column names as keys and the vep annotations as values. The dictionaries are stored in a list. One dictionary for each transcript. Args: snpeff_string (string): A string with the A...
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. kqueue timeout param is a integer number of nanoseconds (seconds/10**9). """ ptimeout = int( timeout.days*86400000000000 + timeout.microseconds*1000 + timeout.seconds*1000000000 if...
ret else: if not self.handle_event(act): ev.flags = EV_ADD | EV_ENABLE | EV_ONESHOT self.kq.kevent(ev) else: sleep(timeout)
def profile(name='stats', _stats=stats): """Calculates a duration (wall clock time, not the CPU time) and a memory size.""" def _profile(function): def __profile(*args, **kw): start_time = timer() start_memory = _get_memory_usage() try: return function(*args, **kw) finally: total = timer() - start_time kstones = _secon...
def match(self, row): """ Returns True if the field matches the regular expression of this simple condition. Returns False otherwise. :param dict row: The row. :rtype: bool """ if re.search(self._expression, row[self._field]): return True return False
def _get_horoscope(self, day='today'): """gets a horoscope from site html :param day: day for which to get horoscope. Default is 'today' :returns: dictionary of horoscope details """ if not is_valid_day(day): raise HoroscopeException("Invalid day. Allowed days: [today|yesterday|tomorrow]" ) horoscope = ''.join([str(s)....
def _get_horoscope_meta(self, day='today'): """gets a horoscope meta from site html :param day: day for which to get horoscope meta. Default is 'today' :returns: dictionary of horoscope mood details """ if not is_valid_day(day): raise HoroscopeException("Invalid day. Allowed days: [today|yesterday|tomorrow]" ) return {...
def heapremove(heap,item): """ Removes item from heap. (This function is missing from the standard heapq package.) """ i=heap.index(item) lastelt=heap.pop() if item==lastelt: return heap[i]=lastelt heapq._siftup(heap,i) if i: heapq._siftdown(heap,0,i)
def process(self, sched, coro): """This is called when the operation is to be processed by the scheduler. Code here works modifies the scheduler and it's usualy very crafty. Subclasses usualy overwrite this method and call it from the superclass.""" if self.prio == priority.DEFAULT: self.prio = sched.default_priority
def process(self, sched, coro): """Add the timeout in the scheduler, check for defaults.""" super(TimedOperation, self).process(sched, coro) if sched.default_timeout and not self.timeout: self.set_timeout(sched.default_timeout) if self.timeout and self.timeout != -1: self.coro = coro if self.weak_timeout: self.last_che...
def process(self, sched, coro): """Add the calling coro in a waiting for signal queue.""" super(WaitForSignal, self).process(sched, coro) waitlist = sched.sigwait[self.name] waitlist.append((self, coro)) if self.name in sched.signals: sig = sched.signals[self.name] if sig.recipients <= len(waitlist): sig.process(sched,...
def cleanup(self, sched, coro): """Remove this coro from the waiting for signal queue.""" try: sched.sigwait[self.name].remove((self, coro)) except ValueError: pass return True
def process(self, sched, coro): """If there aren't enough coroutines waiting for the signal as the recipicient param add the calling coro in another queue to be activated later, otherwise activate the waiting coroutines.""" super(Signal, self).process(sched, coro) self.result = len(sched.sigwait[self.name]) if self.res...
def finalize(self, sched): """Return a reference to the instance of the newly added coroutine.""" super(AddCoro, self).finalize(sched) return self.result
def process(self, sched, coro): """Add the given coroutine in the scheduler.""" super(AddCoro, self).process(sched, coro) self.result = sched.add(self.coro, self.args, self.kwargs, self.prio & priority.OP) if self.prio & priority.CORO: return self, coro else: sched.active.append( (None, coro))
def process(self, sched, coro): """Add the calling coroutine as a waiter in the coro we want to join. Also, doesn't keep the called active (we'll be activated back when the joined coro dies).""" super(Join, self).process(sched, coro) self.coro.add_waiter(coro)
def curve_points(self, beginframe, endframe, framestep, birthframe, startframe, stopframe, deathframe, filternone=False, noiseframe=None): """ returns a list of frames from startframe to stopframe, in steps of framestep :param beginframe: first frame to include in list of points :param endframe: last frame to include i...
current time for which the noise must be evaluated :return: list of tweened values """ return None
def curve_points(self, beginframe, endframe, framestep, birthframe, startframe, stopframe, deathframe, filternone=True, noiseframe=None): """ returns a list of frames from startframe to stopframe, in steps of framestepj warning: the list of points may include "None" elements :param beginframe: first frame to include in...
assert False, "infinite loop: beginframe = {0}, endframe = {1}, framestep = {2}".format(beginframe, endframe, framestep) if endframe > beginframe and framestep < 0: assert False, "infinite loop: beginframe = {0}, endframe = {1}, framestep = {2}".format(beginframe, endframe, framestep) i = beginframe result = [self.make...
def addToStore(store, identifier, name): """Adds a persisted factory with given identifier and object name to the given store. This is intended to have the identifier and name partially applied, so that a particular module with an exercise in it can just have an ``addToStore`` function that remembers it in the store. I...
def p_ty_funty_complex(self, p): "ty : '(' maybe_arg_types ')' ARROW ty" argument_types=p[2] return_type=p[5] # Check here whether too many kwarg or vararg types are present # Each item in the list uses the dictionary encoding of tagged variants arg_types = [argty['arg_type'] for argty in argument_types if 'arg_type' i...
def p_object_ty(self, p): """ object_ty : OBJECT '(' ID ')' | OBJECT '(' ID ',' obj_fields ')' """ field_types = {} if len(p) == 5 else p[5] p[0] = Object(p[3], **field_types)
def p_obj_fields(self, p): """ obj_fields : obj_fields ',' obj_field | obj_field """ p[0] = dict([p[1]] if len(p) == 2 else p[1] + [p[3]])
def parse_owl_xml(url): """Downloads and parses an OWL resource in OWL/XML format using the :class:`OWLParser`. :param str url: The URL to the OWL resource :return: A directional graph representing the OWL document's hierarchy :rtype: networkx.DiGraph """ res = download(url) owl = OWLParser(content=res.content) return ...
def retrieve_object(model, *args, **kwargs): """ Retrieves a specific object from a given model by primary-key lookup, and stores it in a context variable. Syntax:: {% retrieve_object [app_name].[model_name] [lookup kwargs] as [varname] %} Example:: {% retrieve_object flatpages.flatpage pk=12 as my_flat_page %} """ if ...
def request_generic(self, act, coro, perform, complete): """ Performs an overlapped request (via `perform` callable) and saves the token and the (`overlapped`, `perform`, `complete`) trio. """ overlapped = pywintypes.OVERLAPPED() overlapped.object = act self.add_token(act, coro, (overlapped, perform, complete)) try: rc...
def process_op(self, rc, nbytes, overlap): """ Handles the possible completion or re-queueing if conditions haven't been met (the `complete` callable returns false) of a overlapped request. """ act = overlap.object overlap.object = None if act in self.tokens: ol, perform, complete = self.tokens[act] assert ol is overla...
SocketError, SocketError( (rc, "%s on %r" % (ctypes.FormatError(rc), act)) ) )), act.coro else: import warnings warnings.warn("Unknown token %s" % act)
def run(self, timeout = 0): """ Calls GetQueuedCompletionStatus and handles completion via IOCPProactor.process_op. """ # same resolution as epoll ptimeout = int( timeout.days * 86400000 + timeout.microseconds / 1000 + timeout.seconds * 1000 if timeout else (self.m_resolution if timeout is None else 0) ) if self.tokens...
garbage collected and the overlapped completes # afterwards break # well, this is a bit weird, if we get a aborted rc (via CancelIo #i suppose) evaluating the overlap crashes the interpeter #with a memory read error if rc != win32file.WSA_OPERATION_ABORTED and overlap: if urgent: op, coro = urgent urgent = None if op.p...
def html_from_markdown(markdown): """ Takes raw markdown, returns html result from GitHub api """ if login: r = requests.get(gh_url+"/rate_limit", auth=login.auth()) if r.status_code >= 400: if r.status_code != 401: err = RequestError('Bad HTTP Status Code: %s' % r.status_code) raise err if verbose: sys.stderr.write('U...
def standalone(body): """ Returns complete html document given markdown html """ with open(_ROOT + '/html.dat', 'r') as html_template: head = html_title() html = "".join(html_template.readlines()) \ .replace("{{HEAD}}", head) \ .replace("{{BODY}}", body) return html
def run_server(port=8000): """ Runs server on port with html response """ from http.server import BaseHTTPRequestHandler, HTTPServer class VerboseHTMLHandler(BaseHTTPRequestHandler): def do_HEAD(s): s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() def do_GET(s): global html data = changed...
def rate_limit_info(): """ Returns (requests_remaining, minutes_to_reset) """ import json import time r = requests.get(gh_url + "/rate_limit", auth=login.auth()) out = json.loads(r.text) mins = (out["resources"]["core"]["reset"]-time.time())/60 return out["resources"]["core"]["remaining"], mins
def set(parser, token): """ Usage: {% set templ_tag var1 var2 ... key %} {% set variable key %} This tag save result of {% templ_tag var1 var2 ... %} to variable with name key, Or will save value of variable to new variable with name key. """ bits = token.contents.split(' ')[1:] new_token = Token(TOKEN_BLOCK, ' '.join(...
def stringClade(taxrefs, name, at): '''Return a Newick string from a list of TaxRefs''' string = [] for ref in taxrefs: # distance is the difference between the taxonomic level of the ref # and the current level of the tree growth d = float(at-ref.level) # ensure no spaces in ident, Newick tree cannot have spaces ident...
def taxTree(taxdict): """Return taxonomic Newick tree""" # the taxonomic dictionary holds the lineage of each ident in # the same order as the taxonomy # use hierarchy to construct a taxonomic tree for rank in taxdict.taxonomy: current_level = float(taxdict.taxonomy.index(rank)) # get clades at this rank in hierarchy c...