code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
MISSING_AA_VALUE = 0 propertyClusters = clustersForSequence(sequence, propertyNames, missingAAValue=MISSING_AA_VALUE) if showFigure: minCluster = 1 maxCluster = -1 legend = [] x = np.arange(0, len(sequence)) plot = plt.p...
def plotAAClusters(sequence, propertyNames, showLines=True, showFigure=True)
Plot amino acid property cluster numbers for a sequence. @param sequence: An C{AARead} (or a subclass) instance. @param propertyNames: An iterable of C{str} property names (each of which must be a key of a key in the C{dark.aa.PROPERTY_CLUSTERS} C{dict}). @param showLines: If C{True}, lines will be...
2.589431
2.468991
1.048781
BITS = len(bv_di) assert (BITS % 8)==0, "byteorder: expects len(bv_in)=8*x, but len(bv_in)={}".format(BITS) if REVERSE: BYTES = BITS//8 y = ConcatSignal(*[bv_di(8*(b+1),8*b) for b in range(BYTES)]) @always_comb def _reverse(): bv_do.next = y else: ...
def byteorder(bv_di, bv_do, REVERSE=True)
Reverses the byte order of an input bit-vector bv_di - (i) input bit-vector bv_do - (o) output bit-vector
4.863934
5.352417
0.908736
completed = set() failed = set() exceptions = [] def collect(task): args = [] kwargs = {} for arg in task.args: if isinstance(arg, Task): args.append(store.get(arg.name)) else: args.append(arg) for key in tas...
def task_loop(tasks, execute, wait=None, store=TaskStore())
The inner task loop for a task runner. execute: A function that runs a task. It should take a task as its sole argument, and may optionally return a TaskResult. wait: (optional, None) A function to run whenever there aren't any runnable tasks (but there are still tasks listed as running). ...
3.180855
3.309191
0.961218
aa = find(s) if aa: return aa else: print('Unknown amino acid or codon: %s' % s, file=sys.stderr) print('Valid arguments are: %s.' % list(CODONS.keys()), file=sys.stderr) sys.exit(1)
def findOrDie(s)
Look up an amino acid. @param s: A C{str} amino acid specifier. This may be a full name, a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored. @return: An C{AminoAcid} instance, if one can be found. Else exit.
4.288963
4.056008
1.057435
assert isinstance(url, (str, _oldstr)) assert isinstance(download_file, (str, _oldstr)) assert isinstance(overwrite, bool) assert isinstance(raise_http_exception, bool) u = urlparse.urlparse(url) assert u.scheme in ['http', 'https'] if os.path.isfile(download_file) and not overwrite:...
def http_download(url, download_file, overwrite=False, raise_http_exception=True)
Download a file over HTTP(S). See: http://stackoverflow.com/a/13137873/5651021 Parameters ---------- url : str The URL. download_file : str The path of the local file to write to. overwrite : bool, optional Whether to overwrite an existing file (if present). [False...
1.982406
1.970548
1.006018
assert isinstance(url, (str, _oldstr)) assert isinstance(download_file, (str, _oldstr)) assert isinstance(if_exists, (str, _oldstr)) assert isinstance(user_name, (str, _oldstr)) assert isinstance(password, (str, _oldstr)) u = urlparse.urlparse(url) assert u.scheme == 'ftp' if if_e...
def ftp_download(url, download_file, if_exists='error', user_name='anonymous', password='', blocksize=4194304)
Downloads a file from an FTP server. Parameters ---------- url : str The URL of the file to download. download_file : str The path of the local file to download to. if_exists : str, optional Desired behavior when the download file already exists. One of: 'error' ...
1.730203
1.783339
0.970204
#species_list, release=None, ftp=None # type checks assert isinstance(species, (str, _oldstr)) if release is not None: assert isinstance(release, int) if ftp is not None: assert isinstance(ftp, ftplib.FTP) # open FTP connection, if necessary close_connection = Fals...
def get_cdna_url(species, release=None, ftp=None)
Returns the URL for a cDNA file hosted on the Ensembl FTP server. Parameters ---------- species: str The scientific name of the species. It should be all lower-case, and the genus and species parts should be separated by an underscore (e.g., "homo_sapiens"). release: int or ``No...
2.545689
2.438583
1.043921
logger.info('Writing pickle to "%s"...', path) if compress: with gzip.open(path, 'wb') as ofh: pickle.dump(self, ofh, pickle.HIGHEST_PROTOCOL) else: with open(path, 'wb') as ofh: pickle.dump(self, ofh, pickle.HIGHEST_PROTOCOL)
def write_pickle(self, path, compress=False)
Serialize the current `GOParser` object and store it in a pickle file. Parameters ---------- path: str Path of the output file. compress: bool, optional Whether to compress the file using gzip. Returns ------- None Notes ...
1.910289
1.942505
0.983415
with misc.open_plain_or_gzip(fn, 'rb') as fh: parser = pickle.load(fh) return parser
def read_pickle(fn)
Load a GOParser object from a pickle file. The function automatically detects whether the file is compressed with gzip. Parameters ---------- fn: str Path of the pickle file. Returns ------- `GOParser` The GOParser object stored ...
7.893611
8.660032
0.911499
term = None try: term = self.terms[self.name2id[name]] except KeyError: try: term = self.terms[self.syn2id[name]] except KeyError: pass else: logger.info('GO term name "%s" is a synonym for "...
def get_term_by_name(self, name)
Get the GO term with the given GO term name. If the given name is not associated with any GO term, the function will search for it among synonyms. Parameters ---------- name: str The name of the GO term. Returns ------- `GOTerm` ...
2.821791
2.841566
0.993041
name2id = {} alt_id = {} syn2id = {} terms = [] with open(path) as fh: n = 0 while True: try: nextline = next(fh) except StopIteration: break if nextline == ...
def read_obo(cls, path, flatten=True, part_of_cc_only=False)
Parse an OBO file and store GO term information. Parameters ---------- path: str Path of the OBO file. flatten: bool, optional If set to False, do not generate a list of all ancestors and descendants for each GO term. part_of_cc_only: bool, op...
2.609225
2.533756
1.029785
def get_all_descendants(term): descendants = set() for id_ in term.children: descendants.add(id_) descendants.update(get_all_descendants(self[id_])) if include_parts: for id_ in term.parts: descendan...
def _flatten_descendants(self, include_parts=True)
Determines and stores all descendants of each GO term. Parameters ---------- include_parts: bool, optional Whether to include ``part_of`` relations in determining descendants. Returns ------- None
2.037729
1.955853
1.041862
op_name = create_instance( credentials, self.project, self.zone, name, machine_type=self.machine_type, disk_size_gb=self.disk_size_gb, **kwargs) return op_name
def create_instance(self, credentials, name, **kwargs)
Create an instance based on the configuration data. TODO: docstring
3.46014
3.578666
0.96688
op_name = delete_instance( credentials, self.project, self.zone, name, **kwargs) return op_name
def delete_instance(self, credentials, name, **kwargs)
Delete an instance based on the configuration data. TODO: docstring
7.315989
7.338697
0.996906
op_name = wait_for_instance_deletion( credentials, self.project, self.zone, name, **kwargs) return op_name
def wait_for_instance_deletion(self, credentials, name, **kwargs)
Wait for deletion of instance based on the configuration data. TODO: docstring
5.675078
5.616904
1.010357
return [ n.replace(".json.gz", "") for n in pkg_resources.resource_listdir(__name__, _data_dir) if n.endswith(".json.gz") ]
def get_cytoband_names()
Returns the names of available cytoband data files >> get_cytoband_names() ['ucsc-hg38', 'ucsc-hg19']
4.437261
5.356629
0.828368
fn = pkg_resources.resource_filename( __name__, _data_path_fmt.format(name=name)) return json.load(gzip.open(fn, mode="rt", encoding="utf-8"))
def get_cytoband_map(name)
Fetch one cytoband map by name >>> map = get_cytoband_map("ucsc-hg38") >>> map["1"]["p32.2"] [55600000, 58500000, 'gpos50']
4.492656
6.364593
0.705883
if names == []: names = get_cytoband_names() return {name: get_cytoband_map(name) for name in names}
def get_cytoband_maps(names=[])
Load all cytoband maps >>> maps = get_cytoband_maps() >>> maps["ucsc-hg38"]["1"]["p32.2"] [55600000, 58500000, 'gpos50'] >>> maps["ucsc-hg19"]["1"]["p32.2"] [56100000, 59000000, 'gpos50']
2.222021
3.19166
0.696196
''' Example: absolute_file_path = "/home/xxx/Dev/openfisca/openfisca-france/openfisca_france/param/param.xml" result = "openfisca_france/param/param.xml" ''' global country_package_dir_path assert country_package_dir_path is not None relative_file_path = absolute_file_path[len(country_pa...
def get_relative_file_path(absolute_file_path)
Example: absolute_file_path = "/home/xxx/Dev/openfisca/openfisca-france/openfisca_france/param/param.xml" result = "openfisca_france/param/param.xml"
3.442737
1.807097
1.905121
filt = self.loc[self.index & gene_names] return filt
def filter_genes(self, gene_names : Iterable[str])
Filter the expression matrix against a set of genes. Parameters ---------- gene_names: list of str The genome to filter the genes against. Returns ------- ExpMatrix The filtered expression matrix.
21.07539
22.252176
0.947116
# "squeeze = True" ensures that a pd.read_tsv returns a series # as long as there is only one column e = cls(pd.read_csv(filepath_or_buffer, sep='\t', index_col=0, header=0, encoding=encoding, squeeze=True)) if gene_table ...
def read_tsv(cls, filepath_or_buffer: str, gene_table: ExpGeneTable = None, encoding='UTF-8')
Read expression profile from a tab-delimited text file. Parameters ---------- path: str The path of the text file. gene_table: `ExpGeneTable` object, optional The set of valid genes. If given, the genes in the text file will be filtered against this s...
4.109046
4.284523
0.959044
assert isinstance(path, (str, _oldstr)) assert isinstance(encoding, (str, _oldstr)) sep = '\t' if six.PY2: sep = sep.encode('UTF-8') self.to_csv( path, sep=sep, float_format='%.5f', mode='w', encoding=encoding, header=True ) ...
def write_tsv(self, path, encoding='UTF-8')
Write expression matrix to a tab-delimited text file. Parameters ---------- path: str The path of the output file. encoding: str, optional The file encoding. ("UTF-8") Returns ------- None
4.072933
4.605071
0.884445
if self.storage_callable is not None and not self.storage_per_field: self.storage = self.get_storage_from_callable(field=None) super(override_storage, self).setup_storage()
def setup_storage(self)
Save existing FileField storages and patch them with test instance(s). If storage_per_field is False (default) this function will create a single instance here and assign it to self.storage to be used for all filefields. If storage_per_field is True, an independent storage instance will...
7.121432
5.319315
1.338787
template = _TEMPLATE_ENV.get_template('fastqc.sh') startup_script = template.render( script_dir=script_dir, input_file=input_file, output_dir=output_dir, self_destruct=self_destruct) if len(startup_script) > 32768: raise ValueError('Startup script larger than 32...
def run_fastqc(credentials, instance_config, instance_name, script_dir, input_file, output_dir, self_destruct=True, **kwargs)
Run FASTQC. TODO: docstring
2.769874
2.85354
0.97068
raise ValueError('Startup script larger than 32,768 bytes!') #print(startup_script) instance_config.create_instance( credentials, instance_name, startup_script=startup_script, **kwargs)
def sra_download_paired_end(credentials, instance_config, instance_name, script_dir, sra_run_acc, output_dir, **kwargs): template = _TEMPLATE_ENV.get_template('sra_download_paired-end.sh') startup_script = template.render( script_dir=script_dir, sra_run_acc=...
Download paired-end reads from SRA and convert to gzip'ed FASTQ files. TODO: docstring
4.425321
4.642084
0.953305
template = _TEMPLATE_ENV.get_template('trim_fastq.sh') startup_script = template.render( script_dir=script_dir, input_file=input_file, output_file=output_file, trim_crop=trim_crop, trim_headcrop=trim_headcrop, self_destruct=self_destruct) if len(startup_...
def trim_fastq(credentials, instance_config, instance_name, script_dir, input_file, output_file, trim_crop, trim_headcrop=0, self_destruct=True, **kwargs)
Trims a FASTQ file. TODO: docstring
2.371582
2.412998
0.982836
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p.wait() != 0: raise BridgeException(exception) return p
def _runshell(cmd, exception)
Run a shell command. if fails, raise a proper exception.
2.947526
2.853431
1.032976
_runshell([brctlexe, 'addif', self.name, iname], "Could not add interface %s to %s." % (iname, self.name))
def addif(self, iname)
Add an interface to the bridge
11.368037
9.17956
1.238408
_runshell([brctlexe, 'delif', self.name, iname], "Could not delete interface %s from %s." % (iname, self.name))
def delif(self, iname)
Delete an interface from the bridge.
11.807383
8.737185
1.351394
if val: state = 'on' else: state = 'off' _runshell([brctlexe, 'hairpin', self.name, port, state], "Could not set hairpin in port %s in %s." % (port, self.name))
def hairpin(self, port, val=True)
Turn harpin on/off on a port.
8.691872
8.593153
1.011488
if val: state = 'on' else: state = 'off' _runshell([brctlexe, 'stp', self.name, state], "Could not set stp on %s." % self.name)
def stp(self, val=True)
Turn STP protocol on/off.
11.813546
10.84422
1.089386
_runshell([brctlexe, 'setageing', self.name, str(time)], "Could not set ageing time in %s." % self.name)
def setageing(self, time)
Set bridge ageing time.
14.161199
12.176271
1.163016
_runshell([brctlexe, 'setbridgeprio', self.name, str(prio)], "Could not set bridge priority in %s." % self.name)
def setbridgeprio(self, prio)
Set bridge priority value.
12.14883
10.913602
1.113182
_runshell([brctlexe, 'setfd', self.name, str(time)], "Could not set forward delay in %s." % self.name)
def setfd(self, time)
Set bridge forward delay time value.
18.428286
14.795994
1.245492
_runshell([brctlexe, 'sethello', self.name, str(time)], "Could not set hello time in %s." % self.name)
def sethello(self, time)
Set bridge hello time value.
16.455271
14.114673
1.165827
_runshell([brctlexe, 'setmaxage', self.name, str(time)], "Could not set max message age in %s." % self.name)
def setmaxage(self, time)
Set bridge max message age time.
16.045176
11.446974
1.401696
_runshell([brctlexe, 'setpathcost', self.name, port, str(cost)], "Could not set path cost in port %s in %s." % (port, self.name))
def setpathcost(self, port, cost)
Set port path cost value for STP protocol.
9.431185
9.362057
1.007384
_runshell([brctlexe, 'setportprio', self.name, port, str(prio)], "Could not set priority in port %s in %s." % (port, self.name))
def setportprio(self, port, prio)
Set port priority value.
11.132848
10.593004
1.050962
p = _runshell([brctlexe, 'show', self.name], "Could not show %s." % self.name) return p.stdout.read().split()[7:]
def _show(self)
Return a list of unsorted bridge details.
19.161686
13.273584
1.443595
_runshell([brctlexe, 'addbr', name], "Could not create bridge %s." % name) _runshell([ipexe, 'link', 'set', 'dev', name, 'up'], "Could not set link up for %s." % name) return Bridge(name)
def addbr(self, name)
Create a bridge and set the device up.
7.85218
6.284054
1.24954
self.getbr(name) # Check if exists _runshell([ipexe, 'link', 'set', 'dev', name, 'down'], "Could not set link down for %s." % name) _runshell([brctlexe, 'delbr', name], "Could not delete bridge %s." % name)
def delbr(self, name)
Set the device down and delete the bridge.
8.236711
6.699068
1.229531
p = _runshell([brctlexe, 'show'], "Could not show bridges.") wlist = map(str.split, p.stdout.read().splitlines()[1:]) brwlist = filter(lambda x: len(x) != 1, wlist) brlist = map(lambda x: x[0], brwlist) return map(Bridge, brlist)
def showall(self)
Return a list of all available bridges.
7.35713
6.152517
1.195792
for br in self.showall(): if br.name == name: return br raise BridgeException("Bridge does not exist.")
def getbr(self, name)
Return a bridge object.
7.031415
5.436982
1.293257
if ( self.base_type is not None and value is not None and not isinstance(value, self.base_type) ): if isinstance(self.base_type, tuple): allowed_types = [typ.__name__ for typ in self.base_type] allowed_types_text = ...
def clean(self, value)
Take a dirty value and clean it.
2.451335
2.448154
1.001299
value = self.schema_class(value).full_clean() return self.object_class(**value)
def clean_new(self, value)
Return a new object instantiated with cleaned data.
9.76149
7.873009
1.239868
existing_pk = value[self.pk_field] try: obj = self.fetch_existing(existing_pk) except ReferenceNotFoundError: raise ValidationError('Object does not exist.') orig_data = self.get_orig_data_from_existing(obj) # Clean the data (passing the new data...
def clean_existing(self, value)
Clean the data and return an existing document with its fields updated based on the cleaned values.
4.354355
4.081582
1.06683
fields = {} for field_name in dir(cls): if isinstance(getattr(cls, field_name), Field): field = getattr(cls, field_name) field_name = field.field_name or field_name fields[field_name] = field return fields
def get_fields(cls)
Returns a dictionary of fields and field instances for this schema.
2.071356
1.795217
1.153819
data = {} for field_name in cls.get_fields(): try: value = getattr(obj, field_name) except AttributeError: # If the field doesn't exist on the object, fail gracefully # and don't include the field in the data dict at all. F...
def obj_to_dict(cls, obj)
Takes a model object and converts it into a dictionary suitable for passing to the constructor's data attribute.
5.471641
5.244226
1.043365
return asarray([value.toarray() for (key, value) in sorted(self.transformations.items())])
def toarray(self)
Return transformations as an array with shape (n,x1,x2,...) where n is the number of images, and remaining dimensions depend on the particular transformations
8.797321
8.444587
1.04177
images = check_images(images) def apply(item): (k, v) = item return self.transformations[k].apply(v) return images.map(apply, value_shape=images.value_shape, dtype=images.dtype, with_keys=True)
def transform(self, images)
Apply the transformation to an Images object. Will apply the underlying dictionary of transformations to the images or volumes of the Images object. The dictionary acts as a lookup table specifying which transformation should be applied to which record of the Images object based on the ...
4.969386
6.188918
0.802949
modname = resolve_name(name, package) if modname in sys.modules: return sys.modules[modname] if env is None: try: import builtins env = getattr(builtins, '__xonsh_env__', os.environ) except: return os.environ if env.get(debug, None): ...
def load_module_in_background(name, package=None, debug='DEBUG', env=None, replacements=None)
Entry point for loading modules in background thread. Parameters ---------- name : str Module name to load in background thread. package : str or None, optional Package name, has the same meaning as in importlib.import_module(). debug : str, optional Debugging symbol name to...
3.404035
3.890119
0.875046
if self.__token is not None: return self.__token url = "https://api.neur.io/v1/oauth2/token" creds = b64encode(":".join([self.__key,self.__secret]).encode()).decode() headers = { "Authorization": " ".join(["Basic", creds]), } payload = { "grant_type": "client_credential...
def get_token(self)
Performs Neurio API token authentication using provided key and secret. Note: This method is generally not called by hand; rather it is usually called as-needed by a Neurio Client object. Returns: string: the access token
2.894415
2.522513
1.147433
url_parts = list(urlparse(url)) query = dict(parse_qsl(url_parts[4])) query.update(params) url_parts[4] = urlencode(query) return urlunparse(url_parts)
def __append_url_params(self, url, params)
Utility method formatting url request parameters.
1.945622
1.788501
1.087851
url = "https://api.neur.io/v1/appliances/%s"%(appliance_id) headers = self.__gen_headers() headers["Content-Type"] = "application/json" r = requests.get(url, headers=headers) return r.json()
def get_appliance(self, appliance_id)
Get the information for a specified appliance Args: appliance_id (string): identifiying string of appliance Returns: list: dictionary object containing information about the specified appliance
3.377635
3.728653
0.905859
url = "https://api.neur.io/v1/appliances" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "locationId": location_id, } url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) return r.json()
def get_appliances(self, location_id)
Get the appliances added for a specified location. Args: location_id (string): identifiying string of appliance Returns: list: dictionary objects containing appliances data
3.157869
3.356295
0.940879
url = "https://api.neur.io/v1/appliances/events" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "locationId": location_id, "since": since } if min_power: params["minPower"] = min_power if per_page: params["perPage"] = per...
def get_appliance_event_after_time(self, location_id, since, per_page=None, page=None, min_power=None)
Get appliance events by location Id after defined time. Args: location_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` since (string): ISO 8601 start time for getting the events that are created or updated after it. Maxiumim value allowe...
2.178546
2.450385
0.889063
url = "https://api.neur.io/v1/appliances/stats" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "locationId": location_id, "start": start, "end": end } if granularity: params["granularity"] = granularity if min_power: ...
def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None, min_power=None)
Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the supplied criteria and then aggregating them together based on the granularity specified with the request. Note: This endpoint uses the location's time zone when...
2.048579
2.273966
0.900884
valid_ip_pat = re.compile( "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" ) if not valid_ip_pat.match(ip): raise ValueError("ip address invalid") url = "http://%s/current-sample" % (ip) headers = { "Content-Type": "application/json" } r...
def get_local_current_sample(ip)
Gets current sample from *local* Neurio device IP address. This is a static method. It doesn't require a token to authenticate. Note, call get_user_information to determine local Neurio IP addresses. Args: ip (string): address of local Neurio device Returns: dictionary object containing ...
1.884874
1.948057
0.967566
url = "https://api.neur.io/v1/samples/live" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "sensorId": sensor_id } if last: params["last"] = last url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) retur...
def get_samples_live(self, sensor_id, last=None)
Get recent samples, one sample per second for up to the last 2 minutes. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` last (string): starting range, as ISO8601 timestamp Returns: list: dictionary objects containing sample data
3.145567
3.479675
0.903983
url = "https://api.neur.io/v1/samples/live/last" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "sensorId": sensor_id } url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) return r.json()
def get_samples_live_last(self, sensor_id)
Get the last sample recorded by the sensor. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` Returns: list: dictionary objects containing sample data
3.328519
3.830948
0.86885
url = "https://api.neur.io/v1/samples" if full: url = "https://api.neur.io/v1/samples/full" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "sensorId": sensor_id, "start": start, "granularity": granularity } if end: ...
def get_samples(self, sensor_id, start, granularity, end=None, frequency=None, per_page=None, page=None, full=False)
Get a sensor's samples for a specified time interval. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` start (string): ISO 8601 start time of sampling; depends on the ``granularity`` parameter value, the maximum supported tim...
2.02595
2.164663
0.935919
url = "https://api.neur.io/v1/users/current" headers = self.__gen_headers() headers["Content-Type"] = "application/json" r = requests.get(url, headers=headers) return r.json()
def get_user_information(self)
Gets the current user information, including sensor ID Args: None Returns: dictionary object containing information about the current user
4.23579
4.054923
1.044604
API_VERSION = '2.1.0' wsgihelpers.track(req.url.decode('utf-8')) params = dict(req.GET) data = dict() try: extensions_header = req.headers.get('X-Openfisca-Extensions') tax_benefit_system = model.get_cached_composed_reform( reform_keys = extensions_header.split(','...
def api2_formula(req)
A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person. Combination ----------- You can compute several formulas at once by combining the paths and joining them with `+`. Example: ``` /salaire_super_brut+salaire_net_a_payer?salaire_de_base=1440 ``` This will com...
5.083207
4.862698
1.045347
''' Calculates the arithmetic mean of every 4 consecutive input numbers Input handshake & data rx_rdy - (o) Ready rx_vld - (i) Valid rx_dat - (i) Data Output handshake & data tx_rdy - (i) Ready tx_vld - (o) Valid tx_dat - (o) D...
def arithmetic_mean4(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat)
Calculates the arithmetic mean of every 4 consecutive input numbers Input handshake & data rx_rdy - (o) Ready rx_vld - (i) Valid rx_dat - (i) Data Output handshake & data tx_rdy - (i) Ready tx_vld - (o) Valid tx_dat - (o) Data ...
3.09013
2.132124
1.44932
''' Instantiates the arithmetic_mean4 pipeline, feeds it with data and drains its output ''' clk = sim.Clock(val=0, period=10, units="ns") rst = sim.ResetSync(clk=clk, val=0, active=1) rx_rdy, rx_vld, tx_rdy, tx_vld = [Signal(bool(0)) for _ in range(4)] rx_dat = Signal(intbv(0)[8:]) tx_dat = S...
def pipeline_control_stop_tx()
Instantiates the arithmetic_mean4 pipeline, feeds it with data and drains its output
3.00904
2.722294
1.105333
value = super(MongoEmbedded, self).clean(value) return self.document_class(**value)
def clean(self, value)
Clean the provided dict of values and then return an EmbeddedDocument instantiated with them.
8.105819
5.88796
1.376677
try: return self.object_class.objects.get(pk=doc_id) except self.object_class.DoesNotExist: raise ReferenceNotFoundError
def fetch_object(self, doc_id)
Fetch the document by its PK.
3.267081
2.833905
1.152855
desc = 'Generate a sample sheet based on a GEO series matrix.' parser = cli.get_argument_parser(desc=desc) g = parser.add_argument_group('Input and output files') g.add_argument( '-s', '--series-matrix-file', type=cli.str_type, required=True, metavar=cli.file_mv, help='The GEO ser...
def get_argument_parser()
Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser.
2.859823
2.947269
0.97033
assert isinstance(path, str) accessions = None titles = None celfile_urls = None with misc.smart_open_read(path, mode='rb', try_gzip=True) as fh: reader = csv.reader(fh, dialect='excel-tab', encoding=encoding) for l in reader: if not l: continue ...
def read_series_matrix(path, encoding)
Read the series matrix.
4.223708
4.265826
0.990127
with open(path, 'wb') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) # write header writer.writerow(['Accession', 'Name', 'CEL file', 'CEL file URL']) n = len(names)...
def write_sample_sheet(path, accessions, names, celfile_urls, sel=None)
Write the sample sheet.
2.136801
2.172989
0.983346
if args is None: parser = get_argument_parser() args = parser.parse_args() #series_matrix_file = newstr(args.series_matrix_file, 'utf-8') #output_file = newstr(args.output_file, 'utf-8') #encoding = newstr(args.encoding, 'utf-8') series_matrix_file = args.series_matrix_file ...
def main(args=None)
Script entry point.
2.990478
2.960095
1.010264
blueprint = Blueprint( 'invenio_jsonschemas', __name__, ) @blueprint.route('/<path:schema_path>') def get_schema(schema_path): try: schema_dir = state.get_schema_dir(schema_path) except JSONSchemaNotFound: abort(404) resolve...
def create_blueprint(state)
Create blueprint serving JSON schemas. :param state: :class:`invenio_jsonschemas.ext.InvenioJSONSchemasState` instance used to retrieve the schemas.
2.354575
2.332188
1.009599
assert isinstance(manifest, pd.DataFrame) assert isinstance(download_dir, str) assert isinstance(chunk_size, int) if auth_token is not None: assert isinstance(auth_token, str) def get_file_md5hash(path): with open(path, 'rb') as fh: h...
def download_files(manifest, download_dir, auth_token=None, chunk_size=1048576, avoid_redownload=True)
Individually download files from GDC. Params ------ manifest : `pandas.DataFrame` GDC manifest that contains a list of files. The data frame should have five columns: id, filename, md5, size, and state. download_dir : str The path of the download directory. auth_token : ...
2.477425
2.477204
1.000089
for key in sorted(record.__dict__.keys()): if key not in ['alignments', 'descriptions', 'reference']: print('%s: %r' % (key, record.__dict__[key])) print('alignments: (%d in total):' % len(record.alignments)) for i, alignment in enumerate(record.alignments): print(' descrip...
def printBlastRecord(record)
Print a BLAST record. @param record: A BioPython C{Bio.Blast.Record.Blast} instance.
2.539769
2.557389
0.99311
#if path == '-': # path = sys.stdin assert isinstance(gene_ontology, GeneOntology) if db is not None: assert isinstance(db, (str, _oldstr)) if (ev_codes is not None) and ev_codes: assert isinstance(ev_codes, (str, _oldstr)) or \ isinstance(ev_codes, Iterable)...
def parse_gaf(path_or_buffer, gene_ontology, valid_genes=None, db=None, ev_codes=None)
Parse a GAF 2.1 file containing GO annotations. Parameters ---------- path_or_buffer : str or buffer The GAF file. gene_ontology : `GeneOntology` The Gene Ontology. valid_genes : Iterable of str, optional A list of valid gene names. [None] db : str, optional ...
2.149111
2.092503
1.027053
go_term_genes = OrderedDict() term_ids = {} for ann in go_annotations: term_ids[ann.go_term.id] = ann.go_term try: go_term_genes[ann.go_term.id].append(ann.db_symbol) except KeyError: go_term_genes[ann.go_term.id] = [ann.db_symbol] go_term_genes ...
def get_goa_gene_sets(go_annotations)
Generate a list of gene sets from a collection of GO annotations. Each gene set corresponds to all genes annotated with a certain GO term.
2.359196
2.422922
0.973699
NUM_STAGES = len(stage_enable) if (stop_rx == None): stop_rx = Signal(intbv(0)[NUM_STAGES:]) if (stop_tx == None): stop_tx = Signal(intbv(0)[NUM_STAGES:]) assert (len(stop_rx)==NUM_STAGES), "pipeline_control: expects len(stop_rx)=len(stage_enable), but len(stop_rx)={} len(stage_...
def pipeline_control(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None)
Synchronizes data flow in a processing pipeline. rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline) tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline) stage_enable - (o) vector of enable signals, one signa...
1.82078
1.813756
1.003872
NUM_STAGES = len(stage_enable) if (stop_rx == None): stop_rx = Signal(intbv(0)[NUM_STAGES:]) if (stop_tx == None): stop_tx = Signal(intbv(0)[NUM_STAGES:]) assert (len(stop_rx)==NUM_STAGES), "pipeline_control: expects len(stop_rx)=len(stage_enable), but len(stop_rx)={} len(stage_...
def pipeline_control_new(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None)
Pipeline control unit rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline) tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline) stage_enable - (o) vector of enable signals, one signal per stage, that controls t...
1.802835
1.775426
1.015438
''' Single stage control BC - enable bubble compression ''' if stop_rx==None: stop_rx = False if stop_tx==None: stop_tx = False state = Signal(bool(0)) a = Signal(bool(0)) b = Signal(bool(0)) bc_link = state if BC else True @always_comb def _comb1()...
def _stage_ctrl(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_en, stop_rx=None, stop_tx=None, BC=False)
Single stage control BC - enable bubble compression
3.105623
2.750026
1.129307
print('normalizeHSP error:', file=sys.stderr) print(' queryLen: %d' % queryLen, file=sys.stderr) print(' Original HSP:', file=sys.stderr) for attr in ['bits', 'btop', 'expect', 'frame', 'query_end', 'query_start', 'sbjct', 'query', 'sbjct_end', 'sbjct_start']: print(' ...
def _debugPrint(hsp, queryLen, localDict, msg='')
Print debugging information showing the local variables used during a call to normalizeHSP and the hsp and then raise an C{AssertionError}. @param hsp: The HSP C{dict} passed to normalizeHSP. @param queryLen: the length of the query sequence. @param localDict: A C{dict} of local variables (as produced ...
2.698586
2.519835
1.070937
# Subject indices must always be ascending. if subjectStart >= subjectEnd: _debugPrint(hsp, queryLen, localDict, 'subjectStart >= subjectEnd') subjectMatchLength = subjectEnd - subjectStart queryMatchLength = queryEnd - queryStart # Sanity check that the length of the matches in the s...
def _sanityCheck(subjectStart, subjectEnd, queryStart, queryEnd, queryStartInSubject, queryEndInSubject, hsp, queryLen, subjectGaps, queryGaps, localDict)
Perform some sanity checks on an HSP. Call _debugPrint on any error. @param subjectStart: The 0-based C{int} start offset of the match in the subject. @param subjectEnd: The 0-based C{int} end offset of the match in the subject. @param queryStart: The 0-based C{int} start offset of the matc...
2.200714
2.199482
1.00056
if read_only: scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] else: scopes = ['https://www.googleapis.com/auth/devstorage.read_write'] credentials = service_account.Credentials.from_service_account_info(key) scoped_credentials = credentials.with_scopes(scopes...
def get_storage_credentials(key, read_only=False)
Authenticates a service account for reading and/or writing on a bucket. This uses the `google.oauth2.service_account` module to obtain "scoped credentials". These can be used with the `google.storage` module. TODO: docstring
1.898418
1.791705
1.059559
scopes = ['https://www.googleapis.com/auth/compute'] credentials = ServiceAccountCredentials.from_json_keyfile_dict( key, scopes=scopes) return credentials
def get_compute_credentials(key)
Authenticates a service account for the compute engine. This uses the `oauth2client.service_account` module. Since the `google` Python package does not support the compute engine (yet?), we need to make direct HTTP requests. For that we need authentication tokens. Obtaining these based on the credentia...
2.51109
3.179959
0.789661
h = hash_pandas_object(self, index=True) return hashlib.md5(h.values.tobytes()).hexdigest()
def hash(self)
Generate a hash value.
5.92204
5.270305
1.123662
return [ExpGene.from_series(g) for i, g in self.reset_index().iterrows()]
def genes(self)
Return a list of all genes.
15.159461
13.909637
1.089853
df = pd.read_csv(file_or_buffer, sep='\t', index_col=0) df = df.where(pd.notnull(df), None) # Note: df.where(..., None) changes all column types to `object`. return cls(df)
def read_tsv(cls, file_or_buffer: str)
Read genes from tab-delimited text file.
4.250889
3.764297
1.129265
data = [g.to_dict() for g in genes] index = [d.pop('ensembl_id') for d in data] table = cls(data, index=index) return table
def from_genes(cls, genes: List[ExpGene])
Initialize instance using a list of `ExpGene` objects.
4.815845
4.038498
1.192484
genes = [ExpGene(id_) for id_ in gene_ids] return cls.from_genes(genes)
def from_gene_ids(cls, gene_ids: List[str])
Initialize instance from gene IDs.
6.509225
4.59526
1.416508
genes = [ExpGene(id_, name=name) for id_, name in gene_names.items()] return cls.from_genes(genes)
def from_gene_ids_and_names(cls, gene_names: Dict[str, str])
Initialize instance from gene IDs and names.
5.226416
4.052248
1.289757
result = [ExpGene.from_series(s) for i, s in self.loc[self['name'] == name].iterrows()] return result
def find_gene(self, name: str)
Find gene(s) by name.
11.315955
8.122688
1.393129
''' copy items with optional fields transformation ''' source = open(src[0], src[1]) target = open(trg[0], trg[1], autocommit=1000) for item in source.get(): item = dict(item) if '_id' in item: del item['_id'] if transform: item = transform(item) ...
def copy(src, trg, transform=None)
copy items with optional fields transformation
4.518924
3.851362
1.173331
''' REGEXP function for Sqlite ''' reg = re.compile(expr) return reg.search(item) is not None
def _regexp(expr, item)
REGEXP function for Sqlite
7.115897
5.21962
1.363298
''' factory for sqlite3 to return results as dict ''' d = {} for idx, col in enumerate(cursor.description): if col[0] == 'rowid': d['_id'] = row[idx] else: d[col[0]] = row[idx] return d
def _dict_factory(cursor, row)
factory for sqlite3 to return results as dict
3.172994
2.638427
1.202608
''' parse URI ''' if not uri or uri.find('://') <= 0: raise RuntimeError('Incorrect URI definition: {}'.format(uri)) backend, rest_uri = uri.split('://') if backend not in SUPPORTED_BACKENDS: raise RuntimeError('Unknown backend: {}'.format(backend)) ...
def parse_uri(uri)
parse URI
4.647652
4.716667
0.985368
''' return fieldnames ''' if not self._fields: if self._item_class is not None: for m in inspect.getmembers(self._item_class): if m[0] == 'fields' and isinstance(m[1], dict): self._fields = m[1] if not self._...
def fieldnames(self)
return fieldnames
2.991255
2.935591
1.018962
''' create sqlite's table for storing simple dictionaries ''' if self.fieldnames: sql_fields = [] for field in self._fields: if field != '_id': if 'dblite' in self._fields[field]: sql_fields.append(' '.join([fiel...
def _create_table(self, table_name)
create sqlite's table for storing simple dictionaries
3.327927
2.795279
1.190553
''' make Item class ''' for field in self._item_class.fields: if (field in item) and ('dblite_serializer' in self._item_class.fields[field]): serializer = self._item_class.fields[field]['dblite_serializer'] item[field] = serializer.loads(item[field]) ...
def _make_item(self, item)
make Item class
4.260081
3.921498
1.08634
''' returns items selected by criteria If the criteria is not defined, get() returns all items. ''' if criteria is None and limit is None: return self._get_all() elif limit is not None and limit == 1: return self.get_one(criteria) else: ...
def get(self, criteria=None, offset=None, limit=None)
returns items selected by criteria If the criteria is not defined, get() returns all items.
3.577801
2.613405
1.369019
''' return all items ''' rowid = 0 while True: SQL_SELECT_MANY = 'SELECT rowid, * FROM %s WHERE rowid > ? LIMIT ?;' % self._table self._cursor.execute(SQL_SELECT_MANY, (rowid, ITEMS_PER_REQUEST)) items = self._cursor.fetchall() if len(items...
def _get_all(self)
return all items
3.570072
3.366736
1.060396
''' returns items selected by criteria ''' SQL = SQLBuilder(self._table, criteria).select(offset=offset, limit=limit) self._cursor.execute(SQL) for item in self._cursor.fetchall(): yield self._make_item(item)
def _get_with_criteria(self, criteria, offset=None, limit=None)
returns items selected by criteria
5.514862
4.754603
1.159899