code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def from_id(reddit_session, subreddit_id): pseudo_data = {'id': subreddit_id, 'permalink': '/comments/{0}'.format(subreddit_id)} return Submission(reddit_session, pseudo_data)
Return an edit-only submission object based on the id.
def unoptimize_scope(self, frame): if frame.identifiers.declared: self.writeline('%sdummy(%s)' % ( unoptimize_before_dead_code and 'if 0: ' or '', ', '.join('l_' + name for name in frame.identifiers.declared) ))
Disable Python optimizations for the frame.
def regions(self): regions = [] elem = self.dimensions["region"].elem for option_elem in elem.find_all("option"): region = option_elem.text.strip() regions.append(region) return regions
Get a list of all regions
def add_node(self, node): if self.controllers.get(node.controller_type, None): raise RuntimeError("Cannot add node {} to the node group. A node for {} group is already assigned".format( node, node.controller_type )) self.nodes.append(node) if node.controller: self.controllers[node.controller_type] = node.controller setattr(self, node.controller_type, node.controller)
A a Node object to the group. Only one node per cgroup is supported
def find_poor_default_arg(node): poor_defaults = [ ast.Call, ast.Dict, ast.DictComp, ast.GeneratorExp, ast.List, ast.ListComp, ast.Set, ast.SetComp, ] return ( isinstance(node, ast.FunctionDef) and any((n for n in node.args.defaults if type(n) in poor_defaults)) )
Finds poor default args
def fail_eof(self, end_tokens=None, lineno=None): stack = list(self._end_token_stack) if end_tokens is not None: stack.append(end_tokens) return self._fail_ut_eof(None, stack, lineno)
Like fail_unknown_tag but for end of template situations.
def write_def_decl(self, node, identifiers): funcname = node.funcname namedecls = node.get_argument_expressions() nameargs = node.get_argument_expressions(as_call=True) if not self.in_def and ( len(self.identifiers.locally_assigned) > 0 or len(self.identifiers.argument_declared) > 0): nameargs.insert(0, 'context._locals(__M_locals)') else: nameargs.insert(0, 'context') self.printer.writeline("def %s(%s):" % (funcname, ",".join(namedecls))) self.printer.writeline( "return render_%s(%s)" % (funcname, ",".join(nameargs))) self.printer.writeline(None)
write a locally-available callable referencing a top-level def
def pvalues(self): self.compute_statistics() lml_alts = self.alt_lmls() lml_null = self.null_lml() lrs = -2 * lml_null + 2 * asarray(lml_alts) from scipy.stats import chi2 chi2 = chi2(df=1) return chi2.sf(lrs)
Association p-value for candidate markers.
def convert(self, value, param, ctx): self.gandi = ctx.obj choices = [choice.replace('*', '') for choice in self.choices] value = value.replace('*', '') if value in choices: return value new_value = '%s 64 bits' % value if new_value in choices: return new_value p = re.compile(' (64|32) bits') new_value = p.sub('', value) if new_value in choices: return new_value self.fail('invalid choice: %s. (choose from %s)' % (value, ', '.join(self.choices)), param, ctx)
Try to find correct disk image regarding version.
def serialize(dictionary): data = [] for key, value in dictionary.items(): data.append('{0}="{1}"'.format(key, value)) return ', '.join(data)
Turn dictionary into argument like string.
def _index_local_ref(fasta_file, cortex_dir, stampy_dir, kmers): base_out = os.path.splitext(fasta_file)[0] cindexes = [] for kmer in kmers: out_file = "{0}.k{1}.ctx".format(base_out, kmer) if not file_exists(out_file): file_list = "{0}.se_list".format(base_out) with open(file_list, "w") as out_handle: out_handle.write(fasta_file + "\n") subprocess.check_call([_get_cortex_binary(kmer, cortex_dir), "--kmer_size", str(kmer), "--mem_height", "17", "--se_list", file_list, "--format", "FASTA", "--max_read_len", "30000", "--sample_id", base_out, "--dump_binary", out_file]) cindexes.append(out_file) if not file_exists("{0}.stidx".format(base_out)): subprocess.check_call([os.path.join(stampy_dir, "stampy.py"), "-G", base_out, fasta_file]) subprocess.check_call([os.path.join(stampy_dir, "stampy.py"), "-g", base_out, "-H", base_out]) return {"stampy": base_out, "cortex": cindexes, "fasta": [fasta_file]}
Pre-index a generated local reference sequence with cortex_var and stampy.
def _hashfile(self,filename,blocksize=65536): logger.debug("Hashing file %s"%(filename)) hasher=hashlib.sha256() afile=open(filename,'rb') buf=afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.hexdigest()
Hashes the file and returns hash
def url_prefixed(regex, view, name=None): return url(r'^%(app_prefix)s%(regex)s' % { 'app_prefix': APP_PREFIX, 'regex': regex}, view, name=name)
Returns a urlpattern prefixed with the APP_NAME in debug mode.
def _aggregate_func(self, aggregate): funcs = {"sum": add, "min": min, "max": max} func_name = aggregate.lower() if aggregate else 'sum' try: return funcs[func_name] except KeyError: raise TypeError("Unsupported aggregate: {}".format(aggregate))
Return a suitable aggregate score function.
def insertDatastore(self, index, store): if not isinstance(store, Datastore): raise TypeError("stores must be of type %s" % Datastore) self._stores.insert(index, store)
Inserts datastore `store` into this collection at `index`.
def get(search="unsigned"): plugins = [] for i in os.walk('/usr/lib/nagios/plugins'): for f in i[2]: plugins.append(f) return plugins
List all available plugins
def _convert_epoch_anchor(cls, reading): delta = datetime.timedelta(seconds=reading.value) return cls._EpochReference + delta
Convert a reading containing an epoch timestamp to datetime.
def _windowsLdmodSources(target, source, env, for_signature): return _dllSources(target, source, env, for_signature, 'LDMODULE')
Get sources for loadable modules.
def pretty_print(self): pt = PrettyTable() if len(self) == 0: pt._set_field_names(['Sorry,']) pt.add_row([TRAIN_NOT_FOUND]) else: pt._set_field_names(self.headers) for train in self.trains: pt.add_row(train) print(pt)
Use `PrettyTable` to perform formatted outprint.
def stop(self): if self.uiautomator_process and self.uiautomator_process.poll() is None: res = None try: res = urllib2.urlopen(self.stop_uri) self.uiautomator_process.wait() except: self.uiautomator_process.kill() finally: if res is not None: res.close() self.uiautomator_process = None try: out = self.adb.cmd("shell", "ps", "-C", "uiautomator").communicate()[0].decode("utf-8").strip().splitlines() if out: index = out[0].split().index("PID") for line in out[1:]: if len(line.split()) > index: self.adb.cmd("shell", "kill", "-9", line.split()[index]).wait() except: pass
Stop the rpc server.
def _uncamelize(self, s): res = '' if s: for i in range(len(s)): if i > 0 and s[i].lower() != s[i]: res += '_' res += s[i].lower() return res
Convert a camel-cased string to using underscores
def map(self, f, preservesPartitioning=False): def func(iterator): return map(f, iterator) return self.mapPartitions(func, preservesPartitioning)
Return a new DStream by applying a function to each element of DStream.
def parse_assembly(llvmir, context=None): if context is None: context = get_global_context() llvmir = _encode_string(llvmir) strbuf = c_char_p(llvmir) with ffi.OutputString() as errmsg: mod = ModuleRef( ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg), context) if errmsg: mod.close() raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg)) return mod
Create Module from a LLVM IR string
def wrap_stub(elf_file): print('Wrapping ELF file %s...' % elf_file) e = esptool.ELFFile(elf_file) text_section = e.get_section('.text') try: data_section = e.get_section('.data') except ValueError: data_section = None stub = { 'text': text_section.data, 'text_start': text_section.addr, 'entry': e.entrypoint, } if data_section is not None: stub['data'] = data_section.data stub['data_start'] = data_section.addr if len(stub['text']) % 4 != 0: stub['text'] += (4 - (len(stub['text']) % 4)) * '\0' print('Stub text: %d @ 0x%08x, data: %d @ 0x%08x, entry @ 0x%x' % ( len(stub['text']), stub['text_start'], len(stub.get('data', '')), stub.get('data_start', 0), stub['entry']), file=sys.stderr) return stub
Wrap an ELF file into a stub 'dict'
def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf): starttime = time.time() self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE, (snipp.BODY_VXLAN_STATE % "enabled")) self.send_edit_string(nexus_host, snipp.PATH_VNSEG_STATE, (snipp.BODY_VNSEG_STATE % "enabled")) self.send_edit_string( nexus_host, (snipp.PATH_NVE_CREATE % nve_int_num), (snipp.BODY_NVE_CREATE % nve_int_num)) self.send_edit_string( nexus_host, (snipp.PATH_NVE_CREATE % nve_int_num), (snipp.BODY_NVE_ADD_LOOPBACK % ("enabled", src_intf))) self.capture_and_print_timeshot( starttime, "enable_vxlan", switch=nexus_host)
Enable VXLAN on the switch.
def add_tracked_motors(self, tracked_motors): new_mockup_motors = map(self.get_mockup_motor, tracked_motors) self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors))
Add new motors to the recording
def read (self, stream): self._data = stream.read(self._size) if len(self._data) >= self._size: values = struct.unpack(self._format, self._data) else: values = None, None, None, None, None, None, None if values[0] == 0xA1B2C3D4 or values[0] == 0xA1B23C4D: self._swap = '@' elif values[0] == 0xD4C3B2A1 or values[0] == 0x4D3CB2A1: self._swap = EndianSwap if values[0] is not None: values = struct.unpack(self._swap + self._format, self._data) self.magic_number = values[0] self.version_major = values[1] self.version_minor = values[2] self.thiszone = values[3] self.sigfigs = values[4] self.snaplen = values[5] self.network = values[6]
Reads PCapGlobalHeader data from the given stream.
def update_name(self, force=False, create_term=False, report_unchanged=True): updates = [] self.ensure_identifier() name_term = self.find_first('Root.Name') if not name_term: if create_term: name_term = self['Root'].new_term('Root.Name','') else: updates.append("No Root.Name, can't update name") return updates orig_name = name_term.value identifier = self.get_value('Root.Identifier') datasetname = self.get_value('Root.Dataset') if datasetname: name = self._generate_identity_name() if name != orig_name or force: name_term.value = name updates.append("Changed Name") else: if report_unchanged: updates.append("Name did not change") elif not orig_name: if not identifier: updates.append("Failed to find DatasetName term or Identity term. Giving up") else: updates.append("Setting the name to the identifier") name_term.value = identifier elif orig_name == identifier: if report_unchanged: updates.append("Name did not change") else: updates.append("No Root.Dataset, so can't update the name") return updates
Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space
def write_pdb(self, mol, filename, name=None, num=None): scratch = tempfile.gettempdir() with ScratchDir(scratch, copy_to_current_on_exit=False) as _: mol.to(fmt="pdb", filename="tmp.pdb") bma = BabelMolAdaptor.from_file("tmp.pdb", "pdb") num = num or 1 name = name or "ml{}".format(num) pbm = pb.Molecule(bma._obmol) for i, x in enumerate(pbm.residues): x.OBResidue.SetName(name) x.OBResidue.SetNum(num) pbm.write(format="pdb", filename=filename, overwrite=True)
dump the molecule into pdb file with custom residue name and number.
def connection_class(self, adapter): if self.adapters.get(adapter): return self.adapters[adapter] try: class_prefix = getattr( __import__('db.' + adapter, globals(), locals(), ['__class_prefix__']), '__class_prefix__') driver = self._import_class('db.' + adapter + '.connection.' + class_prefix + 'Connection') except ImportError: raise DBError("Must install adapter `%s` or doesn't support" % (adapter)) self.adapters[adapter] = driver return driver
Get connection class by adapter
def add_person_entity(self, entity, instances_json): check_type(instances_json, dict, [entity.plural]) entity_ids = list(map(str, instances_json.keys())) self.persons_plural = entity.plural self.entity_ids[self.persons_plural] = entity_ids self.entity_counts[self.persons_plural] = len(entity_ids) for instance_id, instance_object in instances_json.items(): check_type(instance_object, dict, [entity.plural, instance_id]) self.init_variable_values(entity, instance_object, str(instance_id)) return self.get_ids(entity.plural)
Add the simulation's instances of the persons entity as described in ``instances_json``.
def deactivate(): if hasattr(_mode, "current_state"): del _mode.current_state if hasattr(_mode, "schema"): del _mode.schema for k in connections: con = connections[k] if hasattr(con, 'reset_schema'): con.reset_schema()
Deactivate a state in this thread.
def as_spinmode(cls, obj): if isinstance(obj, cls): return obj else: try: return _mode2spinvars[obj] except KeyError: raise KeyError("Wrong value for spin_mode: %s" % str(obj))
Converts obj into a `SpinMode` instance
def generate_matching_datasets(self, data_slug): matching_hubs = VERTICAL_HUB_MAP[data_slug]['hubs'] return Dataset.objects.filter(hub_slug__in=matching_hubs)
Return datasets that belong to a vertical by querying hubs.
def crypto_key_version_path( cls, project, location, key_ring, crypto_key, crypto_key_version ): return google.api_core.path_template.expand( "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}", project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, )
Return a fully-qualified crypto_key_version string.
def next(self): item = six.next(self._item_iter) result = self._item_to_value(self._parent, item) self._remaining -= 1 return result
Get the next value in the page.
def load(self): lg.info('Loading ' + str(self.xml_file)) update_annotation_version(self.xml_file) xml = parse(self.xml_file) return xml.getroot()
Load xml from file.
def _read_imu(self): self._init_imu() attempts = 0 success = False while not success and attempts < 3: success = self._imu.IMURead() attempts += 1 time.sleep(self._imu_poll_interval) return success
Internal. Tries to read the IMU sensor three times before giving up
def allocate_mid(mids): i = 0 while True: mid = str(i) if mid not in mids: mids.add(mid) return mid i += 1
Allocate a MID which has not been used yet.
def reward_bonus(self, assignment_id, amount, reason): from psiturk.amt_services import MTurkServices self.amt_services = MTurkServices( self.aws_access_key_id, self.aws_secret_access_key, self.config.getboolean( 'Shell Parameters', 'launch_in_sandbox_mode')) return self.amt_services.bonus_worker(assignment_id, amount, reason)
Reward the Turker with a bonus.
def _build_matrix_non_uniform(p, q, coords, k): A = [[1] * (p+q+1)] for i in range(1, p + q + 1): line = [(coords[k+j] - coords[k])**i for j in range(-p, q+1)] A.append(line) return np.array(A)
Constructs the equation matrix for the finite difference coefficients of non-uniform grids at location k
def scan(context, root_dir): root_dir = root_dir or context.obj['root'] config_files = Path(root_dir).glob('*/analysis/*_config.yaml') for config_file in config_files: LOG.debug("found analysis config: %s", config_file) with config_file.open() as stream: context.invoke(log_cmd, config=stream, quiet=True) context.obj['store'].track_update()
Scan a directory for analyses.
def parse_bookmark_node (node): if node["type"] == "url": yield node["url"], node["name"] elif node["type"] == "folder": for child in node["children"]: for entry in parse_bookmark_node(child): yield entry
Parse one JSON node of Chromium Bookmarks.
def info(ctx): dev = ctx.obj['dev'] controller = ctx.obj['controller'] slot1, slot2 = controller.slot_status click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty')) click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty')) if dev.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
Display status of YubiKey Slots.
def queue_stats(self, queue, tags): for mname, pymqi_value in iteritems(metrics.queue_metrics()): try: mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname) m = queue.inquire(pymqi_value) self.gauge(mname, m, tags=tags) except pymqi.Error as e: self.warning("Error getting queue stats for {}: {}".format(queue, e)) for mname, func in iteritems(metrics.queue_metrics_functions()): try: mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname) m = func(queue) self.gauge(mname, m, tags=tags) except pymqi.Error as e: self.warning("Error getting queue stats for {}: {}".format(queue, e))
Grab stats from queues
def main(path_dir, requirements_name): click.echo("\nWARNING: Uninstall libs it's at your own risk!") click.echo('\nREMINDER: After uninstall libs, update your requirements ' 'file.\nUse the `pip freeze > requirements.txt` command.') click.echo('\n\nList of installed libs and your dependencies added on ' 'project\nrequirements that are not being used:\n') check(path_dir, requirements_name)
Console script for imports.
def intSubset(self): ret = libxml2mod.xmlGetIntSubset(self._o) if ret is None:raise treeError('xmlGetIntSubset() failed') __tmp = xmlDtd(_obj=ret) return __tmp
Get the internal subset of a document
def shell(self): click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!") self.zappa.shell() return
Spawn a debug shell.
def resolve_config(self): conf = self.load_config(self.force_default) for k in conf['hues']: conf['hues'][k] = getattr(KEYWORDS, conf['hues'][k]) as_tuples = lambda name, obj: namedtuple(name, obj.keys())(**obj) self.hues = as_tuples('Hues', conf['hues']) self.opts = as_tuples('Options', conf['options']) self.labels = as_tuples('Labels', conf['labels'])
Resolve configuration params to native instances
def rollback(self, revision): print("Rolling back..") self.zappa.rollback_lambda_function_version( self.lambda_name, versions_back=revision) print("Done!")
Rollsback the currently deploy lambda code to a previous revision.
def start(self): setproctitle('oq-zworkerpool %s' % self.ctrl_url[6:]) self.workers = [] for _ in range(self.num_workers): sock = z.Socket(self.task_out_port, z.zmq.PULL, 'connect') proc = multiprocessing.Process(target=self.worker, args=(sock,)) proc.start() sock.pid = proc.pid self.workers.append(sock) with z.Socket(self.ctrl_url, z.zmq.REP, 'bind') as ctrlsock: for cmd in ctrlsock: if cmd in ('stop', 'kill'): msg = getattr(self, cmd)() ctrlsock.send(msg) break elif cmd == 'getpid': ctrlsock.send(self.pid) elif cmd == 'get_num_workers': ctrlsock.send(self.num_workers)
Start worker processes and a control loop
def attach(cls, name, vhost, remote_name): paas_access = cls.get('paas_access') if not paas_access: paas_info = cls.info(name) paas_access = '%s@%s' \ % (paas_info['user'], paas_info['git_server']) remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost) ret = cls.execute('git remote add %s %s' % (remote_name, remote_url,)) if ret: cls.echo('Added remote `%s` to your local git repository.' % (remote_name)) cls.echo('Use `git push %s master` to push your code to the ' 'instance.' % (remote_name)) cls.echo('Then `$ gandi deploy` to build and deploy your ' 'application.')
Attach an instance's vhost to a remote from the local repository.
def BytesIO(*args, **kwargs): raw = sync_io.BytesIO(*args, **kwargs) return AsyncBytesIOWrapper(raw)
BytesIO constructor shim for the async wrapper.
def strip_stop(tokens, start, result): for e in result: for child in e.iter(): if child.text.endswith('.'): child.text = child.text[:-1] return result
Remove trailing full stop from tokens.
def merge(a, b): "merges b into a recursively if a and b are dicts" for key in b: if isinstance(a.get(key), dict) and isinstance(b.get(key), dict): merge(a[key], b[key]) else: a[key] = b[key] return a
merges b into a recursively if a and b are dicts
def from_ip(cls, ip): result = cls.list({'items_per_page': 500}) webaccs = {} for webacc in result: for server in webacc['servers']: webaccs[server['ip']] = webacc['id'] return webaccs.get(ip)
Retrieve webacc id associated to a webacc ip
def apt_cache(in_memory=True, progress=None): from apt import apt_pkg apt_pkg.init() if in_memory: apt_pkg.config.set("Dir::Cache::pkgcache", "") apt_pkg.config.set("Dir::Cache::srcpkgcache", "") return apt_pkg.Cache(progress)
Build and return an apt cache.
def GetCalendarDatesFieldValuesTuples(self): result = [] for date_tuple in self.GenerateCalendarDatesFieldValuesTuples(): result.append(date_tuple) result.sort() return result
Return a list of date execeptions
def readfp(self, fp, filename=None): warnings.warn( "This method will be removed in future versions. " "Use 'parser.read_file()' instead.", DeprecationWarning, stacklevel=2 ) self.read_file(fp, source=filename)
Deprecated, use read_file instead.
def add_http_basic_auth(url, user=None, password=None, https_only=False): if user is None and password is None: return url else: urltuple = urlparse(url) if https_only and urltuple.scheme != 'https': raise ValueError('Basic Auth only supported for HTTPS') if password is None: netloc = '{0}@{1}'.format( user, urltuple.netloc ) urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple) else: netloc = '{0}:{1}@{2}'.format( user, password, urltuple.netloc ) urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple)
Return a string with http basic auth incorporated into it
def update_warning_menu(self): editor = self.get_current_editor() check_results = editor.get_current_warnings() self.warning_menu.clear() filename = self.get_current_filename() for message, line_number in check_results: error = 'syntax' in message text = message[:1].upper() + message[1:] icon = ima.icon('error') if error else ima.icon('warning') slot = lambda _checked, _l=line_number: self.load(filename, goto=_l) action = create_action(self, text=text, icon=icon, triggered=slot) self.warning_menu.addAction(action)
Update warning list menu
def _has_message(self): sep = protocol.MINIMAL_LINE_SEPARATOR.encode(self.encoding) return sep in self._receive_buffer
Whether or not we have messages available for processing.
def convex_hull_image(image): labels = image.astype(int) points, counts = convex_hull(labels, np.array([1])) output = np.zeros(image.shape, int) for i in range(counts[0]): inext = (i+1) % counts[0] draw_line(output, points[i,1:], points[inext,1:],1) output = fill_labeled_holes(output) return output == 1
Given a binary image, return an image of the convex hull
def move_examples(root, lib_dir): all_pde = files_multi_pattern(root, INO_PATTERNS) lib_pde = files_multi_pattern(lib_dir, INO_PATTERNS) stray_pde = all_pde.difference(lib_pde) if len(stray_pde) and not len(lib_pde): log.debug( 'examples found outside lib dir, moving them: %s', stray_pde) examples = lib_dir / EXAMPLES examples.makedirs() for x in stray_pde: d = examples / x.namebase d.makedirs() x.move(d)
find examples not under lib dir, and move into ``examples``
def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0): stepfiles = [] for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix): basename = filename[:-len(path_suffix)] if path_suffix else filename try: steps = int(basename.rsplit("-")[-1]) except ValueError: continue if steps < min_steps: continue if not os.path.exists(filename): tf.logging.info(filename + " was deleted, so skipping it") continue stepfiles.append(StepFile(basename, os.path.getmtime(filename), os.path.getctime(filename), steps)) return sorted(stepfiles, key=lambda x: -x.steps)
Return list of StepFiles sorted by step from files at path_prefix.
def skip_status(*skipped): def decorator(func): @functools.wraps(func) def _skip_status(self, *args, **kwargs): if self.status not in skipped: return func(self, *args, **kwargs) return _skip_status return decorator
Decorator to skip this call if we're in one of the skipped states.
def extract_tree_block(self): "iterate through data file to extract trees" lines = iter(self.data) while 1: try: line = next(lines).strip() except StopIteration: break if line.lower() == "begin trees;": while 1: sub = next(lines).strip().split() if not sub: continue if sub[0].lower() == "translate": while sub[0] != ";": sub = next(lines).strip().split() self.tdict[sub[0]] = sub[-1].strip(",") if sub[0].lower().startswith("tree"): self.newicks.append(sub[-1]) if sub[0].lower() == "end;": break
iterate through data file to extract trees
def call_spellchecker(cmd, input_text=None, encoding=None): process = get_process(cmd) if input_text is not None: for line in input_text.splitlines(): offset = 0 end = len(line) while True: chunk_end = offset + 0x1fff m = None if chunk_end >= end else RE_LAST_SPACE_IN_CHUNK.search(line, offset, chunk_end) if m: chunk_end = m.start(1) chunk = line[offset:m.start(1)] offset = m.end(1) else: chunk = line[offset:chunk_end] offset = chunk_end if chunk and not chunk.isspace(): process.stdin.write(chunk + b'\n') if offset >= end: break return get_process_output(process, encoding)
Call spell checker with arguments.
def _already_cutoff_filtered(in_file, filter_type): filter_file = "%s-filter%s.vcf.gz" % (utils.splitext_plus(in_file)[0], filter_type) return utils.file_exists(filter_file)
Check if we have a pre-existing cutoff-based filter file from previous VQSR failure.
def newline(self): self.write(self.term.move_down) self.write(self.term.clear_bol)
Effects a newline by moving the cursor down and clearing
def update_priority(self, tree_idx_list, priority_list): for tree_idx, priority, segment_tree in zip(tree_idx_list, priority_list, self.segment_trees): segment_tree.update(tree_idx, priority)
Update priorities of the elements in the tree
def autodecode(self, a_bytes): try: analysis = chardet.detect(a_bytes) if analysis["confidence"] >= 0.75: return (self.decode(a_bytes, analysis["encoding"])[0], analysis["encoding"]) else: raise Exception("Failed to detect encoding. (%s, %s)" % ( analysis["confidence"], analysis["encoding"])) except NameError: print( "Warning! chardet not found. Use utf-8 as default encoding instead.") return (a_bytes.decode("utf-8")[0], "utf-8")
Automatically detect encoding, and decode bytes.
def manifests_parse(self): self.manifests = [] for manifest_path in self.find_manifests(): if self.manifest_path_is_old(manifest_path): print("fw: Manifest (%s) is old; consider 'manifest download'" % (manifest_path)) manifest = self.manifest_parse(manifest_path) if self.semver_major(manifest["format-version"]) != 1: print("fw: Manifest (%s) has major version %d; MAVProxy only understands version 1" % (manifest_path,manifest["format-version"])) continue self.manifests.append(manifest)
parse manifests present on system
def resource_redirect(id): resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
Redirect to the latest version of a resource given its identifier.
def error_wrap(func): def f(*args, **kw): code = func(*args, **kw) check_error(code, context="client") return f
Parses a s7 error code returned the decorated function.
def parse_numtuple(s,intype,length=2,scale=1): if intype == int: numrx = intrx_s; elif intype == float: numrx = fltrx_s; else: raise NotImplementedError("Not implemented for type: {}".format( intype)); if parse_utuple(s, numrx, length=length) is None: raise ValueError("{} is not a valid number tuple.".format(s)); return [x*scale for x in evalt(s)];
parse a string into a list of numbers of a type
def convert(self, value, view): is_mapping = isinstance(self.template, MappingTemplate) for candidate in self.allowed: try: if is_mapping: if isinstance(candidate, Filename) and \ candidate.relative_to: next_template = candidate.template_with_relatives( view, self.template ) next_template.subtemplates[view.key] = as_template( candidate ) else: next_template = MappingTemplate({view.key: candidate}) return view.parent.get(next_template)[view.key] else: return view.get(candidate) except ConfigTemplateError: raise except ConfigError: pass except ValueError as exc: raise ConfigTemplateError(exc) self.fail( u'must be one of {0}, not {1}'.format( repr(self.allowed), repr(value) ), view )
Ensure that the value follows at least one template.
def run_console(*, locals=None, banner=None, serve=None, prompt_control=None): loop = InteractiveEventLoop( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control) asyncio.set_event_loop(loop) try: loop.run_forever() except KeyboardInterrupt: pass
Run the interactive event loop.
def paths(self): paths = self._cfg.get('paths') if not paths: raise ValueError('Paths Object has no values, You need to define them in your swagger file') for path in paths: if not path.startswith('/'): raise ValueError('Path object {0} should start with /. Please fix it'.format(path)) return six.iteritems(paths)
returns an iterator for the relative resource paths specified in the swagger file
def _follow_link(self, value): seen_keys = set() while True: link_key = self._link_for_value(value) if not link_key: return value assert link_key not in seen_keys, 'circular symlink reference' seen_keys.add(link_key) value = super(SymlinkDatastore, self).get(link_key)
Returns given `value` or, if it is a symlink, the `value` it names.
def zip(what, archive_zip='', risk_file=''): if os.path.isdir(what): oqzip.zip_all(what) elif what.endswith('.xml') and '<logicTree' in open(what).read(512): oqzip.zip_source_model(what, archive_zip) elif what.endswith('.xml') and '<exposureModel' in open(what).read(512): oqzip.zip_exposure(what, archive_zip) elif what.endswith('.ini'): oqzip.zip_job(what, archive_zip, risk_file) else: sys.exit('Cannot zip %s' % what)
Zip into an archive one or two job.ini files with all related files
def flush(self): now = time.time() to_remove = [] for k, entry in self.pool.items(): if entry.timestamp < now: entry.client.close() to_remove.append(k) for k in to_remove: del self.pool[k]
remove all stale clients from pool
def working_dir(val, **kwargs): try: is_abs = os.path.isabs(val) except AttributeError: is_abs = False if not is_abs: raise SaltInvocationError('\'{0}\' is not an absolute path'.format(val)) return val
Must be an absolute path
def save_text_to_file(content: str, path: str): with open(path, mode='w') as text_file: text_file.write(content)
Saves text to file
def survival(value=t, lam=lam, f=failure): return sum(f * log(lam) - lam * value)
Exponential survival likelihood, accounting for censoring
def delete_index(self, refresh=False, ignore=None): es = connections.get_connection("default") index = self.__class__.search_objects.mapping.index doc_type = self.__class__.search_objects.mapping.doc_type es.delete(index, doc_type, id=self.pk, refresh=refresh, ignore=ignore)
Removes the object from the index if `indexed=False`
def build_class_graph(modules, klass=None, graph=None): if klass is None: class_graph = nx.DiGraph() for name, classmember in inspect.getmembers(modules, inspect.isclass): if issubclass(classmember, Referent) and classmember is not Referent: TaxonomyCell.build_class_graph(modules, classmember, class_graph) return class_graph else: parents = getattr(klass, '__bases__') for parent in parents: if parent != Referent: graph.add_edge(parent.__name__, klass.__name__) graph.node[parent.__name__]['class'] = parent graph.node[klass.__name__]['class'] = klass if issubclass(parent, Referent): TaxonomyCell.build_class_graph(modules, parent, graph)
Builds up a graph of the DictCell subclass structure
def merge_consecutive_self_time(frame, options): if frame is None: return None previous_self_time_frame = None for child in frame.children: if isinstance(child, SelfTimeFrame): if previous_self_time_frame: previous_self_time_frame.self_time += child.self_time child.remove_from_parent() else: previous_self_time_frame = child else: previous_self_time_frame = None for child in frame.children: merge_consecutive_self_time(child, options=options) return frame
Combines consecutive 'self time' frames
def _check(self, accepted): total = [] if 1 in self.quickresponse: total = total + self.quickresponse[1] if (1, 0) in self.quickresponse: total = total + self.quickresponse[(1, 0)] for key in total: if (key.id == 1 or key.id == (1, 0)) and key.type == 3: if accepted is None: if 2 in key.trans: return key.trans[2] else: for state in accepted: if (2, state) in key.trans: return key.trans[(2, state)] return -1
_check for string existence
def parse_subcommands(parser, subcommands, argv): subparsers = parser.add_subparsers(dest='subparser_name') parser_help = subparsers.add_parser( 'help', help='Detailed help for actions using `help <action>`') parser_help.add_argument('action', nargs=1) modules = [ name for _, name, _ in pkgutil.iter_modules(subcommands.__path__)] commands = [m for m in modules if m in argv] actions = {} for name in commands or modules: try: imp = '{}.{}'.format(subcommands.__name__, name) mod = importlib.import_module(imp) except Exception as e: log.error(e) continue subparser = subparsers.add_parser( name, help=mod.__doc__.lstrip().split('\n', 1)[0], description=mod.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) mod.build_parser(subparser) subcommands.build_parser(subparser) actions[name] = mod.action return parser, actions
Setup all sub-commands
def _get_parselypage(self, body): parser = ParselyPageParser() ret = None try: parser.feed(body) except HTMLParseError: pass if parser.ppage is None: return ret = parser.ppage if ret: ret = {parser.original_unescape(k): parser.original_unescape(v) for k, v in iteritems(ret)} return ret
extract the parsely-page meta content from a page
def _method_complete(self, result): if isinstance(result, PrettyTensor): self._head = result return self elif isinstance(result, Loss): return result elif isinstance(result, PrettyTensorTupleMixin): self._head = result[0] return result else: self._head = self._head.with_tensor(result) return self
Called after an extention method with the result.
def _findObject(self, img): from imgProcessor.imgSignal import signalMinimum i = img > signalMinimum(img) i = minimum_filter(i, 4) return boundingBox(i)
Create a bounding box around the object within an image
def read_requirements(): reqs_path = os.path.join('.', 'requirements.txt') install_reqs = parse_requirements(reqs_path, session=PipSession()) reqs = [str(ir.req) for ir in install_reqs] return reqs
parses requirements from requirements.txt
def _parse_json(cls, resources, exactly_one=True): if not len(resources['features']): return None if exactly_one: return cls.parse_resource(resources['features'][0]) else: return [cls.parse_resource(resource) for resource in resources['features']]
Parse display name, latitude, and longitude from a JSON response.
def create_marking_iobject(self, uid=None, timestamp=timezone.now(), metadata_dict=None, id_namespace_uri=DINGOS_DEFAULT_ID_NAMESPACE_URI, iobject_family_name=DINGOS_IOBJECT_FAMILY_NAME, iobject_family_revison_name=DINGOS_REVISION_NAME, iobject_type_name=DINGOS_DEFAULT_IMPORT_MARKING_TYPE_NAME, iobject_type_namespace_uri=DINGOS_NAMESPACE_URI, iobject_type_revision_name=DINGOS_REVISION_NAME, ): if not uid: uid = uuid.uuid1() iobject, created = self.create_iobject(iobject_family_name=iobject_family_name, iobject_family_revision_name=iobject_family_revison_name, iobject_type_name=iobject_type_name, iobject_type_namespace_uri=iobject_type_namespace_uri, iobject_type_revision_name=iobject_type_revision_name, iobject_data=metadata_dict, uid=uid, identifier_ns_uri=id_namespace_uri, timestamp=timestamp, ) return iobject
A specialized version of create_iobject with defaults set such that a default marking object is created.
def refresh(self): table = self.tableType() search = nativestring(self._pywidget.text()) if search == self._lastSearch: return self._lastSearch = search if not search: return if search in self._cache: records = self._cache[search] else: records = table.select(where = self.baseQuery(), order = self.order()) records = list(records.search(search, limit=self.limit())) self._cache[search] = records self._records = records self.model().setStringList(map(str, self._records)) self.complete()
Refreshes the contents of the completer based on the current text.
def push(self, data): data, self._partial = self._partial + data, '' parts = NLCRE_crack.split(data) self._partial = parts.pop() if not self._partial and parts and parts[-1].endswith('\r'): self._partial = parts.pop(-2)+parts.pop() lines = [] for i in range(len(parts) // 2): lines.append(parts[i*2] + parts[i*2+1]) self.pushlines(lines)
Push some new data into this object.
def delete_attribute_group(group_id, **kwargs): user_id = kwargs['user_id'] try: group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==group_id).one() group_i.project.check_write_permission(user_id) db.DBSession.delete(group_i) db.DBSession.flush() log.info("Group %s in project %s deleted", group_i.id, group_i.project_id) except NoResultFound: raise HydraError('No Attribute Group %s was found', group_id) return 'OK'
Delete an attribute group.
def load(self, optional_cfg_files=None): optional_cfg_files = optional_cfg_files or [] if self._loaded: raise RuntimeError("INTERNAL ERROR: Attempt to load configuration twice!") try: namespace = {} self._set_defaults(namespace, optional_cfg_files) self._load_ini(namespace, os.path.join(self.config_dir, self.CONFIG_INI)) for cfg_file in optional_cfg_files: if not os.path.isabs(cfg_file): cfg_file = os.path.join(self.config_dir, cfg_file) if os.path.exists(cfg_file): self._load_ini(namespace, cfg_file) self._validate_namespace(namespace) self._load_py(namespace, namespace["config_script"]) self._validate_namespace(namespace) for callback in namespace["config_validator_callbacks"]: callback() except ConfigParser.ParsingError as exc: raise error.UserError(exc) self._loaded = True
Actually load the configuation from either the default location or the given directory.