content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _aggregate_player_attributes(player_df, columns): """Compute the mean for all the players for the given columns Parameters ---------- player_df: pd.DataFrame The DataFrame containing the statistics of all the players columns: list The columns on which to calculate the mean ...
298ca9c12d38bfffe7bdd32ab0e25108a5e95f27
623,848
def calculate_accuracy(fx, y): """ Calculate top-1 accuracy fx = [batch size, output dim] y = [batch size] """ pred_idxs = fx.max(1, keepdim=True)[1] correct = pred_idxs.eq(y.view_as(pred_idxs)).sum() acc = correct.float()/pred_idxs.shape[0] return acc
d011511680faf0fae97982b4b920f7df11b8780f
623,849
def recall_interval(recall): """Return the interval of recall classified to 11 equal intervals of 10 (the field range is 0-100)""" return ((recall*10)//1)*10
9b027edea939e9fa83a07467f77b5759ec85dfc3
623,850
import random def identify_random_elements(max, num_random_elements): """ Picks a specified number of random elements from 0 - max. Used to select poisoned workers Unmodified from Tolpegin et al. :param max: Max number to pick from :type max: int :param num_random_elements: Number of rand...
e3c71cf09ea5d2352764a8d4a5f5ded07b61d3f4
623,851
from typing import Tuple from typing import Dict from typing import Union from typing import List def parse_stan_vars( names: Tuple[str, ...] ) -> Tuple[Dict[str, Tuple[int, ...]], Dict[str, Tuple[int, ...]]]: """ Parses out Stan variable names (i.e., names not ending in `__`) from list of CSV file co...
ba334eb66990d58640d9d978786e89e5555b5d71
623,853
import fileinput def read_description(path): """Reads a text description from a file. """ return ''.join(fileinput.input([path]))
71d30d05e45f5b192a95b3d0fd3a449b682379f8
623,857
def load_sentence_data(row): """Loads sentence-delimited data. Returns task_name, program, [array of sentences] """ if row['phrase_kind'] != 'output': return None, None, None else: task_name = row[""] program = row["program"] sentences = row['natural_language'].split(...
fd0e7fe4bd410639102e4014d61c0199d8940b0c
623,867
def vep_csq(csq, alt, alts): """ >>> csq = 'intron_variant|||ENSG00000047056|WDR37|ENST00000263150||||-/494|protein_coding|1,downstream_gene_variant|||ENSG00000047056|WDR37|ENST00000436154||||-/209|protein_coding|1,intron_variant|||ENSG00000047056|WDR37|ENST00000358220||||-/494|protein_coding|1,stop_lost|Tga/Cg...
8f97341e4f40f92aa8fe10b52439baf59a076c78
623,871
def powell(ind): """Powell function defined as: $$ f(x) = \sum_{i=1}^{n/4} ( (x_{4i-3}+10x_{4i-2})^2. + 5(x_{4i-1}-x_{4i})^2 + (x_{4i-2}-2x_{4i-1})^4 + 10(x_{4i-3}-x{4i})^4 )$$ with a search domain of $-4 < x_i < 5, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(0, ..., 0) = 0. """...
5e0cdf03e5f05e81e2b6301ab462bbd20a2657bb
623,874
def gardner(vp, alpha=310, beta=0.25): """ Compute bulk density (in kg/m^3) from vp (in m/s). """ return alpha * vp ** beta
12c4ca35171b7091dac466a782b438e341fc3d71
623,875
def normalize_image(img): """ Scale image Parameters ---------- img : numpy array image img to be scaled Returns ------- numpy array image scaled """ return img / 255
8911055d81c1fe62f43ae4531c9db3180520f240
623,881
import json def read_proxy_config(file_name): """convert proxy file from json file to python data structure Parameters -------------- file_name : str location of proxies json list file Returns ------------- object datastructure representation of json file """ with...
15ef78c1b5a67424d5cf1b3179fad1d884b80178
623,883
import re def mark_code_blocks(txt, keyword='>>>', split='\n', tag="```", lang='python'): """ Enclose code blocks in formatting tags. Default settings are consistent with markdown-styled code blocks for Python code. Args: txt: String to search for code blocks. keyword(optional, strin...
6e249db9f2d2622fd2491ac01c1f6f10a36caddc
623,885
def fasta_processor(filename): """ Given a fasta generates a unique string with it to be processed by the next functions """ lines = [line.rstrip('\n') for line in open(filename)] # remove > line del lines[0] # Join sequence sequence = "".join(lines) return sequence
dea942108f05da97bd35c5b1616fa9b186656ca5
623,888
def seq_adjacent_terms_sum(sequence: list, sum_level: int): """ A function to extract the sums of adjacent terms sequence: A list of integers that contains the sequence sum_level: The level indicates the number of times the operation will be applied on the sequence return: A list of list of integers...
7f68f8dc448a8fd9406858d3d7774b82f12cb910
623,892
def string_tag(name, value): """Create a DMAP tag with string data.""" return name.encode('utf-8') + \ len(value).to_bytes(4, byteorder='big') + \ value.encode('utf-8')
21e041195fb986cbdcb7d9eabcc57018eb111c05
623,894
def get_in(d, *keys, default=None): """Get a nested value from a dict.""" for k in keys: if not isinstance(d, dict) or k not in d: return default d = d[k] return d
49cd735d8aedc87d5fc8fb494b6469b665219e77
623,899
def count_flowables_by_class(flowlist): """ Counts flowables by class :param flowlist: A FlowList in standard format :return: pandas df with 'Class' and counts of unique flowables """ flowables_by_class = flowlist[['Class', 'Flowable']] flowables_by_class = flowables_by_class.drop_duplicates...
f8d427691b0cf939a297f91a54189c79889d04b8
623,902
def or_default(value, default): """ Helps to avoid using a temporary variable in cases similiar to the following:: if slow_function() is not None: return slow_function() else: return default """ return value if value is not None else default
1bcf0867b2bd18668f75c48707a1b07df52780f8
623,903
import random import math def gamma(alpha=1): """ Returns value greater than 0 from the gamma distribution (https://en.wikipedia.org/wiki/Gamma_distribution). Parameter alpha controls the distribution's shape and should be a positive integer (if a non-integer is provided, the value is rounded.) W...
6fb259a69ee0efa1e094a05b3c6f74262cd36659
623,907
import re def get_project_names(r): """ Extracts a list of project names from a wiki page HTML. """ # projects short names are in h2 elements without any attributes # there is one more h2 element, but it has `class` attribute # re_proj_names = re.compile(r'<h2><a[^>]>(.+)</a></h2>') re_pro...
2469b9683220bce356b6230ca4cd100fbb0f9e43
623,909
def chromosome(record): """ Get the chromosome this record is from. If it is part of a scaffold then it will be returned. """ basic = record.id if basic.startswith("chromosome:") or basic.startswith("scaffold:"): parts = basic.split(":") return parts[2] return basic.split("....
220695950ef7de4e2819ae84c69b77d7f95ac8cf
623,913
def file_type_by_extension( extension): """ Tries to guess the file type by looking up the filename extension from a table of known file types. Will return the type as string ("audio", "video" or "torrent") or None if the file type cannot be determined. """ types={ 'audio': [ ...
398be4b45b26eb7562f70f58acbd88a8af87c064
623,915
def CStructName(t): """Obtain the name of the CType struct from Python.""" # Clang2py translates C structs to python classes with # prefixes like 'struct_c__SA_Foo' and then assign # types like 'Foo = struct_c__SA_Foo'. This function # gets the real C struct name by removing those prefixes. struct_name = t....
3cda606ba4ffcb62666846eb001f20c8428ca30f
623,917
def __get_num_parent_instantiations__(parents, num_values): """ Gets the number of parent instantiations. :param parents: List of parent indices. :param num_values: List of the number of values per node. :return: Number of parent instantiations. """ num_pa_instantiations = 1 for pa in p...
b4ea6686b3a529bd966253b0c31a04d6f77a3a9e
623,922
import csv def read_source_file(filename, tsv=False): """ Read a source file into a list of video dictionaries :param filename: A file opened for reading :param tsv: The type of file: false for UTF-8 CSV, true for UTF-16 TSV :return: A list of video dictionaries """ with open(filename, 'r', newline='', ...
b57d544bf3f7f0b469d689fc86a865fbcabc92c2
623,928
def replace_files(d,file_list): """ Replace files for mzmine task Inputs: d: an xml derived dictionary of batch commands file_list: a list of full paths to mzML files Outputs: d: an xml derived dict with new files in it """ for i,step in enumerate(d['batch']['batchstep']): ...
504655f890779c36e85b03615de9f3c5c1db00f8
623,930
def _validate_dataset(dataset): """ Confirm a valid ICESat-2 dataset was specified """ if isinstance(dataset, str): dataset = str.upper(dataset) assert dataset in [ "ATL01", "ATL02", "ATL03", "ATL04", "ATL06", "ATL07...
2051b8a8b12b6f2bcd9b05b828b24f9e7ee3aeaf
623,933
def vgr_callback(prepend_msg='', logger=None, msg_update_callback=None): """Create a callback function to use for vsphere-guest-run functions. :param str prepend_msg: string to prepend to all messages received from vsphere-guest-run function. :param logging.Logger logger: logger to use in case of e...
86e5e5833dc07700abcf8ef71e7fd43b3586dd6a
623,938
def get_padded_string(string: str, in_string: str, from_char_index: int) -> str: """ Return a string that is appropriately padded/indented, given a starting position. For example, if a starting index of 4 is given for a string " content\ngoes here", th...
54de197df73b7c3481669ecd0ded142a5bf2d08e
623,939
def ret_group_delay(taps): """ Helper function computes group delay of FIR filter. """ grp_delay = (len(taps)-1)//2 return grp_delay
8132ec7423bb9ab0139f72b67aa3b9c86b06beec
623,942
def _role_valid(roles, role_list): """ Return ``True`` if there is an intersection between the users roles and any roles in the constraint. """ if [role for role in roles if role in role_list]: return True return False
d6606586ab299f418c84658b8d82ff1dccd7a2b0
623,945
import collections import itertools import logging def categorize(metapath): """ Returns the classification of a given metapath as one of a set of metapath types which we approach differently. Parameters ---------- metapath : hetio.hetnet.MetaPath Returns ------- classification :...
7ee1d4230a799f1cf0b66e7f79a667ad133a4e0f
623,946
def is_quote(code, idx=0): """Position in string is an unescaped quotation mark.""" return (0 <= idx < len(code) and code[idx] == '"' and (idx == 0 or code[idx-1] != '\\'))
054354ea0372df436d4c2c8a0c52ec98c2b16986
623,947
def deep_merge(left, right): """Deep merge dictionaries, replacing values from right""" if isinstance(left, dict) and isinstance(right, dict): result = left.copy() for key in right: if key in left: result[key] = deep_merge(left[key], right[key]) else: ...
f15939421e7ea046806ba5c33efa2bec02949eea
623,949
import csv def write_proc_periods(start_times, end_times, fname): """ writes an output file containing start and stop times of periods to process Parameters ---------- start_times, end_times : datetime object The starting and ending times of the periods fname : str The nam...
bb557cda3b5cbce2debfcb647422d4c14e567091
623,953
def rename_col_index(df, label): """rename level 0 of column indes to "label" Parameters ---------- df : dataframe labour force and population timeseries data label : string name of level 0 of multiindex Returns ------- df dataframe with column multiinde...
60410ce369f27aa5d06fdcb2482059ad64d31365
623,959
def calc_checksum(content: bytes) -> bytes: """ Calculate checksum using 8-bit Fletcher's algorithm. :param bytes content: message content, excluding header and checksum bytes :return: checksum :rtype: bytes """ check_a = 0 check_b = 0 for char in content: check_a += char...
7a6dfa6d94754eaa9aff94ddc4122bc272279eab
623,961
def fix_object(value): """Fixes python objects so that they can be properly inserted into SQL queries""" if isinstance(value, str): return value.encode('utf-8') else: return value
507f1f73c80b67964cb10048956d83a6099bec38
623,962
def ranking_list(input_list): """ Returns the rank of each element of the list :param input_list: a list of elements :return: output_list: the corresponding ranks """ indices = list(range(len(input_list))) indices.sort(key=lambda x: input_list[x]) output_list = [0] * len(indices) fo...
8a585d183485f831860b141c96579cb1a7046dd7
623,965
from typing import Any from typing import List from typing import Tuple import csv def get_phone_times(phn_file: Any) -> List[Tuple[int, int, str]]: """Gets endpoint times for each phone in a recording. Reads phone endpoint times from .phn file. The .phn file has a simple text format as used in TIMIT. Each row...
3d7bf0a2ce03e7885214ae90849793cbe55ff857
623,970
import asyncio def _run(awaitable): """A shim for :func:`asyncio.run` from 3.7+.""" loop = asyncio.get_event_loop() return loop.run_until_complete(awaitable)
7656797000fe4bc080474d4d817f41d4f5dbb73b
623,973
import math def clog(x,b=2): """returns the ceil of log base b x, and never returns negative.""" if x < b: return 1 else: return math.ceil(math.log(x,b))
eeed101248809a86e26de177f49acc7b92bad0a9
623,974
import logging def validate_config(config): """ Validate the user's config. Any errors get logged. If there are 1 or more errors, False is returned. :param config: The configuration dictionary to validate :return: Whether or not the number of errors in the config was 0 """ expected_value...
4f5f134b048df7dc698568a027f82d33c9fe57bf
623,975
def not_valid(peer_id, doc_id): """ There are some summaries full of dashes '-' which are not easy to be handled :param peer_id: The peer id of the author :param doc_id: The id of corresponding document :return: Bool True or False whether or not the summary is valid """ return True if (peer...
ad57010ac68cd6e69719044fa16a50a4312b2b20
623,977
def samplevar_dataset_to_varcope(samplevar_dataset, sample_size): """Convert "sample variance of the dataset" (variance of the individual observations in a single sample) to "sampling variance" (variance of sampling distribution for the parameter). Parameters ---------- samplevar_dataset : arra...
ce68189e189231ca5f42637912620b40abe38664
623,978
def get_pfcwd_config_attr(host_ans, config_scope, attr): """ Get PFC watchdog configuration attribute Args: host_ans: Ansible host instance of the device config_scope (str): 'GLOBAL' or interface name attr (str): config attribute name, e.g., 'detection_time' Returns: co...
6b99b9534dd19b9e3bde3648ff0ebc285e6f2d9f
623,979
def __rename_column(df, old_name, new_name): """ Renames a column in a pandas dataframe :param df: pandas dataframe :param old_name: :param new_name: :return: data frame with renamed column """ return df.rename(index=str, columns={old_name: new_name})
0612f4955fa69f7df3cc41b1be4a53496b08cc10
623,986
import json def translate_xiaomi_aqara_contact(topic, data, srv=None): """Translate the Xiaomi Aqara's contact sensor JSON data to a human-readable description of whether it's open or closed.""" payload = json.loads(data["payload"]) if "contact" in payload: if payload["contact"]: r...
94a745339cc7893cc5df16d69b01edfc66ab057a
623,989
def __repr__(self): """A custom repr for targetdb models. By default it always prints pk, name, and label, if found. Models can define they own ``__print_fields__`` as a list of field to be output in the repr. """ fields = ['pk={0!r}'.format(self.pk)] for ff in self.__print_fields__: ...
98c7ab169dd0e8cb7074f65099432fccf4a18c31
623,990
def range_of_lst(lst): """ calculates the range of a given list :param lst: list of numbers :return: max-min """ return max(lst) - min(lst)
6647cbd4fb46412f39d356c9f0e717a129f1f957
623,991
def _seedOffsetForAlgo(tree, algo): """Internal function for returning a pair of indices for the beginning of seeds of a given 'algo', and the one-beyond-last index of the seeds.""" for ioffset, offset in enumerate(tree.see_offset): if tree.see_algo[offset] == algo: next_offset = tree.see_of...
55940def7245b58cd3b8d09cb77e7841d513ec60
623,992
from typing import Dict def market_is_active(market: Dict) -> bool: """ Return True if the market is active. """ # "It's active, if the active flag isn't explicitly set to false. If it's missing or # true then it's true. If it's undefined, then it's most likely true, but not 100% )" # See http...
f8c113e2e3cf08906aa38cddbf89cb555096012e
623,993
from typing import List from typing import Tuple def navigate_part_one(commands: List[Tuple[str, int]]) -> Tuple[int, int]: """Navigate and return the horizontal position and depth.""" horizontal: int = 0 depth: int = 0 for command, units in commands: if command == 'forward': horiz...
bff0d08cfe739beb20a92f75c2caf04aff89b66f
623,995
def is_child_uri(parent_uri: str, child_uri: str) -> bool: """Return True, if child_uri is a child of parent_uri. This function accounts for the fact that '/a/b/c' and 'a/b/c/' are children of '/a/b' (and also of '/a/b/'). Note that '/a/b/cd' is NOT a child of 'a/b/c'. """ return ( bool...
c757df4a982df22c86211fb5dce5395fe8463573
623,997
def is_scalar(x): """ >>> is_scalar(1) True >>> is_scalar(1.1) True >>> is_scalar([1, 2, 3]) False >>> is_scalar((1, 2, 3)) False >>> is_scalar({'a': 1}) False >>> is_scalar({1, 2, 3}) False >>> is_scalar('spam') True """ try: len(x) except...
b8ee1536df04dda1e071a6e84dce66e4c576e42e
623,998
def format_generic_string(event_value, attribute): """ Creates a filter format string for a generic attribute. :param str event_value: String that is used to generate the filter string. :param str attribute: The attribute that is used in the filter. :return: A string that can be used in a LQL filte...
71ed4a04a49c1f7a29211a9c12d48ac360f5f79c
624,000
def _invert_dict(orig_dict): """ Inverting Python dictionary keys and values: Many to one --> One to many Args: - orig_dict: Dictionary desired to invert. + type: dict Return: - Inverted dictionary + type: dict """ return_dict = {} for v, k in orig_dic...
75dc0cdf99e646ddd81ed75eac94ed895dbf185f
624,001
import time def _expired(ts, lifetime=84600000): """ return True if a timestamp is considered expired lifetime is default 23.5 hours """ return (int(time.time()) * 1000) - ts >= lifetime
b67f72dd6b3be298969ee6e0586513cd8ec789fe
624,003
from typing import Iterator from pathlib import Path from typing import Optional import re def _filter_by_include_exclude( notebooks: Iterator[Path], include: Optional[str], exclude: Optional[str], ) -> Iterator[str]: """ Include files which match include, exclude those matching exclude. note...
6760e8be3203cc48610f70530c2786d5f8b66a2e
624,004
def undo_rescale_voxel_tensor(rescaled_voxel_tensor): """Takes a voxel tensor with values in [-1, 1] and rescales them to [0, 1]. Args: rescaled_voxel_tensor: A single voxel tensor after rescaling (values in [-1, 1]). Returns: voxel_tensor: A single voxel tensor with values in [0, 1]. ...
3f64427e8d4144f22db6712a716033d1cbe4dbb3
624,008
def url_has_param(url, param): """Checks whether a URL contains specified parameter.""" url = str(url) return any(x in url for x in [f'?{param}=', f'&{param}='])
62a23cdebd68a07ebd3463b567f92f59b60c1c8c
624,010
import hashlib def ComputeMD5Hex(byte_str): """Compute MD5 hash of "byte_str" and return it encoded as hex string.""" hasher = hashlib.md5() hasher.update(byte_str) return hasher.hexdigest()
f1f423bb67de2b5028aa7488d481e83ed65f8eb4
624,015
def initialized_coroutine(function): """Function decorator to automatically initialize a coroutine.""" def _wrapper(*args, **kw): coroutine = function(*args, **kw) coroutine.send(None) return coroutine return _wrapper
a5ef01ee311bb116922a17b5b23b133e52f441cd
624,016
def cdf_UPL(x, a, beta): """ Cumulative function for untruncated power law. pdf(x) = (beta-1)/a * (a/x)^beta for x >= a """ F = 1-(a/x)**(beta-1) return F
90b3fc1cb0d09c7772acc81e21c6398dc4e0c09a
624,021
import torch import math def get_log_marginal_joint(generative_model, guide, discrete_latent, obs, num_particles): """Estimate log p(z_d, x) using importance sampling Args: generative_model guide discrete_latent [*discrete_shape, *shape, *dims] OR ...
7ee00eee53530d04d328ea18ce76114dad6b3153
624,023
import re def _is_a_glob(a_string): """ Return True or False depending on whether a_string appears to be a glob """ pattern = re.compile(r'[\*\[\]\{\}\?]') return bool(pattern.search(a_string))
849bdf0e49ae95e0b425b5072afd2b800aa93848
624,025
import hashlib def generate_hash_str(linking_identifier: str, salt_str: str) -> str: """ Given a string made of concatenated patient information, generate a hash for this string to serve as a "unique" identifier for the patient. """ hash_obj = hashlib.sha256() to_encode = (linking_identifi...
9e823f3b572e2a82bcfd8faab780a5d35491c063
624,026
from typing import List def needed_columns_are_in_df(to_check: List, to_interrogate: List) -> bool: """ True if all of to_check values are in to_interrogate, else False """ if all(x in to_interrogate for x in to_check): return True else: return False
dbf4f5078ce1683cdea4ae9c9e32ba513e9110bc
624,028
def take(items, indices): """ Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: items (list): an indexable object to select items from indices (Sequence): sequence of indexing objects Returns: iter or scalar: subset o...
bb162acd777624b0ad86fd35ae2a9ac67a46c906
624,033
def _getShapeSize(df, shape_name_str): """ Get the arbitrary shape size with its shape name. Args: df: tuple-(df_CompartmentData, df_NodeData, df_ReactionData, df_ArbitraryTextData, df_ArbitraryShapeData). shape_name_str: str-the shape name. Returns: shape_size_list: list...
76bb20e423b26472c841bfd345fc8f42ce0888bd
624,034
def issubset(left, right): """A subset relation for dictionaries""" return set(left.keys()) <= set(right.keys())
0e03bfb2983f673e658aedf74111081ea2f07c57
624,037
def full_house(dice): """ Score the dice based on rules for FULL_HOUSE. """ points = 0 dice.sort() first = dice[0] last = dice[-1] num_first = dice.count(first) num_last = dice.count(last) if num_first >= 2 and num_last >= 2 and num_first + num_last == len(dice): points =...
57c5343726b45ae4b6985cd399191ce2f3cca887
624,040
def add_input_args(parser): """Add parser arguments for input options.""" parser.add_argument('--image', metavar='<image>', type=str, required=False, default='./doc/valid_test.png', help='Path of input image.') parser.add_argument('--video', metavar='<video>', type=str, required=False, default='./doc/valid_...
e6ebb4e956922c924092bf5649c2ae153570d0f4
624,041
def uniq(dup_list): """Remove duplicated elements in a list and return a unique list Example: [1,1,2,2,3,3] #=> [1,2,3] """ return list(set(dup_list))
a02a015a304b624ba4a55894f714e297672efd83
624,042
import struct def unpack_int(st): """unpack 2 bytes little endian to int""" return int(struct.unpack('<h', st[0:2])[0])
473dceb06177ca72c609a4ba2ac30d681bbff6d9
624,043
import uuid import re def html_id_safe(text: str) -> str: """ Makes a string that can be made into an HTML id and referenced easily """ if not text: return str(uuid.uuid4()) text = re.sub("[^0-9A-Za-z]", "-", text) text = re.sub("_{2,}", "-", text) if not text[0].isalpha(): ...
7628e3bbfb437af2c1c8d8ed4058028c225a5927
624,045
def getDim(scale,supercell): """ Helper function for to determine periodicity of a crystal, used in various functions inputs -------- scale (float): The ratio of final and initial network size supercell (int): The supercell size used to generate the new ...
9b476ac7a7b16791c6bca496bd4d87f76226b956
624,046
import struct def _read_matrix_shape(file_path: str): """ Reads and returns the shape (rows, columns) from the matrix stored in the given file. """ with open(file_path, 'rb') as f: rows = struct.unpack('<i', f.read(4))[0] cols = struct.unpack('<i', f.read(4))[0] return rows...
84c82d820958bfa795d69161661fe4128748e2f8
624,047
def get_token_auth_header(request): """Obtains the Access Token from the Authorization Header """ auth = request.META.get("HTTP_AUTHORIZATION", None) parts = auth.split() token = parts[1] return token
5fef9c797d2c87ad71331918e306af4c911b3b73
624,048
def max_norm(p): """ Computes the max norm (infinity norm) of a polynomial. :param p: the polynomial :return: a tuple containing the monomial degrees of the largest coefficient and the coefficient """ max_degs = None max_coeff = 0 for degs, coeff in p.dict().items(): if abs(coeff...
ba2398fa265944298ca8e8d35c73a951c1ac8002
624,050
from typing import Any def build_param_error(name: str, value: Any, description: str) -> dict: """Return a dictionary describing a parameter error. Can be used in build_error as detail. Schema: { 'parameter': { 'name': name of a parameter 'value': value of the paramete...
6aded8834bff201e9d34a2a56df911150c16030f
624,051
def create_cluster_logical_device_ids(core_id, switch_id): """ Creates a logical device id and an OpenFlow datapath id that is unique across the Voltha cluster. The returned logical device id represents a 64 bits integer where the lower 48 bits is the switch id and the upper 16 bits is the core id...
9a8b5e88ab1bbef048d1ea85d423a3e3822bf79e
624,058
def find_prime_factors(n): """Return prime factors of n""" p_factors = [] current = n test = 2 while test <= current: if not current%test: p_factors.append(test) current = current // test test = 2 else: test += 1 return p_factors
d51d10f18780441f84f53bb31b383210d19ca71f
624,059
def parse_args(parser): """ Parse commandline arguments. """ parser.add_argument('-i', '--input-file', type=str, default="text.txt", help='full path to the input text (phareses separated by new line)') parser.add_argument('-o', '--output', type=str, default="outputs", help='output folder to save aud...
799083d33068b5ed3b350a773ae957fb5b9ab4f9
624,060
def fasta(sequences): """Builds a FASTA record of extracted sequences. This function expects either a list of Synthase objects (mode='synthase') or a dictionary of extracted domains, keyed on synthase header (mode='domains'). """ # Entire Synthase objects were extracted if isinstance(sequences,...
76ea3b13c8ea8214d73985d56a0d4cf50de4c517
624,062
def describe_humidity(humidity): """Convert relative humidity into wet/good/dry description.""" if 30 < humidity <= 75: description = "good" elif humidity > 75: description = "wet" else: description = "dry" return description
aadfa10b532cedd1574ad80a97c1e2762269d58e
624,063
def autoSize(image, resolution=1920): """Determines the size of an image by setting the largest side to the size of the resolution""" if image.width >= image.height: size = (resolution, round((resolution / image.width) * image.height)) else: size = (round((resolution / image.height) * image....
c0559f8454946ec5b23020f656d2a70de046e415
624,070
def build_cgi_env(req): """ Utility function that returns a dictionary of CGI environment variables as described in http://hoohoo.ncsa.uiuc.edu/cgi/env.html """ req.add_cgi_vars() env = req.subprocess_env.copy() if req.path_info and len(req.path_info) > 0: env["SCRIPT_NAME"] = ...
275e9b4400b002bafd57fbbdc00723445f209441
624,071
import json def open_json(fname: str) -> dict: """open json story book and return as dict.""" with open(f"./data/json/{fname}.json", "r") as fh: return json.load(fh)
9690dcfe9f8b9bb9a68a14eec5e1aa41f219d61e
624,072
from typing import List from typing import Union def fizzbuzz_list() -> List[Union[int, str]]: """Create a list 1-100 --- - Multiples of 3 and 5: FizzBuzz - Multiples of 3: Fizz - Multiples of 5: Buzz - Else: integer """ out: List[Union[int, str]] = [] for i in range(100): ...
d34d0c3d202e643273eb20479810f14303e0924c
624,073
def get_strand_bias(sample, variants): """Based on method 1 (SB) of Guo et al., 2012 If there a denominator would be 0, there is no valid result and this will return None. This occurs when there are no reads on one of the strands, or when there are no minor allele reads.""" # using same variable names as in p...
ae570ce6ae26f5675bc98d5fd61cb7b14b7a4372
624,082
from typing import List def string_contains_any_of_args(string: str, args: List[str]) -> bool: """ Return whether array contains any of a group of args. :param string: String being checked. :param args: Args being analyzed. :return: True if any args are found in the string. """ return any...
15415acbd5e5d3e81870e6256042a7b151df17a0
624,083
def additional_file(remote, local): """ Create step additional file :param remote: the remote file of the additional file :type remote: string :param local: the local file of the additional file :type local: string :return: :rtype map """ return { 'remote': remote, ...
3b43abb1ded1eac3d1adb8e38da3e351ee3febc0
624,085
from typing import List def check_sequential( reference: List[str], update: List[str] ) -> bool: """Helper to check if update continues sequence. Helps to check if updated dates are all in sequence. Args: reference (List[str]): Reference list of dates to be updated. updat...
fc3661a682e9f84540c6bee8bd6f40f8dcfb233b
624,090
def iou_bbox(box1, box2): """ Input format is [xtl, ytl, xbr, ybr] per bounding box, where tl and br indicate top-left and bottom-right corners of the bbox respectively """ # determine the (x, y)-coordinates of the intersection rectangle xA = max(box1[0], box2[0]) yA = max(box1[1], box2[1]) ...
16bf67c3e14bdc5dd202140fbb48548c6d7bbeba
624,094
def test_equal_i(x0, x1): """ Test for exact equality. """ return x0 == x1
01b8a277a22519a607d2d6663aadac0d605e0189
624,095
def get_odds_desc(count): """ This method returns a list of the first 'count' odd numbers in descending order. e.g count = 3 should return [5,3,1] """ return list(reversed(range(1,count*2,2)))
b9cc53054550c148c58738582701dd0ed3ef5763
624,098
def group_by(seq, f): """ A proper groupby that doesn't require sorted input. Output is a dict, rather than an interator >>> group_by([1,2,3,4,5], mod_two) {0: [2, 4], 1: [1, 3, 4]} """ ret = {} [ret.setdefault(f(i), []).append(i) for i in seq] return ret
6d3b1711c9587c3e6b427e18a991b015218dc97c
624,103
from typing import List from typing import Any def config_item_list(value: str, convert=str) -> List[Any]: """ Convert a comma separated string into a list """ return [convert(x) for x in value.split(',')]
718f9d56ae7c09c6b323a839830c86491330ea49
624,105