content
stringlengths
42
6.51k
def extract_name_and_id(user_input): """Determines if the string user_input is a name or an id. :param user_input: (str): input string from user :return: (name, id) pair """ name = id = None if user_input.lower().startswith('id:'): id = user_input[3:] else: name = user_input...
def find_median(quantiles): """Find median from the quantile boundaries. Args: quantiles: A numpy array containing the quantile boundaries. Returns: The median. """ num_quantiles = len(quantiles) # We assume that we have at least one quantile boundary. assert num_quantiles > 0 median_index = ...
def parse_http_list(s): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Neither commas nor quot...
def percentage(n, total): """If `total`=100 and `n`=50 => 50%""" if n is None: return 0 else: return (n*100)/total
def verbose_formatter(verbose: int) -> str: """formatter factory""" if verbose is True: return 'verbose' return 'simple'
def _naics_level(code: str) -> int: """_naics_level is a helper that allows us to determine what level the employment sector is talking about Parameters ---------- code : str NAICS Sector as a string in the format xx-xxxxxx Returns ------- int: The number corresponding to the level...
def ordinal_suffix(i): """Get 'st', 'nd', 'rd' or 'th' as appropriate for an integer.""" if i < 0: raise Exception("Can't handle negative numbers.") if i % 100 in [11, 12, 13]: return 'th' elif i % 10 is 1: return 'st' elif i % 10 is 2: return 'nd' elif i % 10 is...
def get_activation_function(function_name): """ Transform keras activation function name into full activation function name :param function_name: Keras activation function name :return: Full activation function name """ translation_dict = { 'relu': 'Rectified Linear Unit', 'line...
def int2baseTwo(x): """x is a positive integer. Convert it to base two as a list of integers in reverse order as a list.""" assert x >= 0 bitInverse = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
def remove_bools(kwargs): """ Remove booleans from arguments. If ``True``, replace it with an empty string. If ``False``, completely remove the entry from the argument list. Parameters ---------- kwargs : dict Dictionary with the keyword arguments. Returns ------- new_...
def make_auth_header(auth_token): """Make the authorization headers to communicate with endpoints which implement Auth0 authentication API. Args: auth_token (dict): a dict obtained from the Auth0 domain oauth endpoint, containing the signed JWT (JSON Web Token), its expiry, the scopes grant...
def sort_names_numerically(filename_list): """Named after the checkbox in ImageJ's "Import --> Image Sequence" dialog box Sorts the given filename list the same way ImageJ does if that checkbox is checked (and if the file is either not DICOM or the (0020, 0018) Instance Number tag is blank): hierarchically,...
def find_substring(string, substring): """Funkce hleda podretezec (substring) v retezci (string). Pokud se podretezec v retezci nachazi, vrati index prvniho vyskytu. Jinak vraci -1. """ if len(substring) > len(string): return -1 j = 1 i = 1 while i < len(string): if stri...
def to_median_redshift(wavelength, median_z): """Converts wavelength array to the median redshift of the sample Parameters: wavelength (array): wavelength values to convert median_z (int): redshift to change the wavelength by Returns: wavelength_red (array): redshifted wavelength """ ...
def bisect_left(a, x, lo=0, hi=None): """bisection search (left)""" if hi is None: hi = len(a) while lo < hi: mid = (lo + hi)//2 if a[mid] < x: lo = mid + 1 else: hi = mid return lo
def rowdict(columns, row): """Convert given row list into dict with column keys""" robj = {} for k,v in zip(columns, row): robj.setdefault(k,v) return robj
def meanreturn(rates): """ Calculates the average rate of return given a list of returns. [ r1, r2, r3, r4, r5 ... rn ] r = [(1+r1)*(1+r2)*(1+r2) .... * (1+rn)]^(1/n) - 1 :param rates: List of interest rate :return: Geometric mean return Example: Suppose you have invested your sa...
def vect_mult(_V, _a): """ Multiplies vector _V (in place) by number _a """ for i in range(len(_V)): _V[i] *= _a return _V
def paramsDictPhysical2Normalized(params, params_range): """Converts a dictionary of physical parameters into a dictionary of normalized parameters.""" # create copy of dictionary params = dict(params) for key, val in params.items(): params[key] = (val - params_range[key][0]) / (params...
def zero_column(d, j, i): """Return True if ``d[k,j] = 0`` for ``0 <= k < i`` Here ``d`` is a bit matrix implemented as an array of integers. """ s = 0 for k in range(i): s |= d[k] return (s & (1 << j)) == 0
def find_common_directory(directory_x, directory_y): """Given two strings containing paths to directories, find the lowest level parent directory that they share and return it's path. If none are found, return False""" x_path = directory_x.split("\\") y_path = directory_y.split("\\") resul...
def tokenization(sequence_list): """ input : sequence_list -> [[s1],[s2],[s3],[s4] ....,[sn]] where sn is prediction vector output: tokenized sequence_list -> [1,2,3,2,3,....,678] and a look_up table -> {[s1]:0,[s2]:1,[s3]:2,[s4]:3 ....,[sn]:n-1} """ lookup_table={} tokenized_sequence_list=[] ...
def _transform_kwargs(kwargs): """ Replace underscores in the given dictionary's keys with dashes. Used to convert keyword argument names (which cannot contain dashes) to HTML attribute names, e.g. data-*. """ return {key.replace('_', '-'): kwargs[key] for key in kwargs.keys()}
def formatTitle(title): """ It formats titles extracted from the scraped HTML code. """ if(len(title) > 40): return title[:40] + "..." return title
def minimumBribes_iterative(q): """ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1, 2, 3, """ length = len(q) moves = [0 for i in range(length)] moves_made = 0 arr = q.copy() last_pos = length-1 def get_pos_indices(arr): nonlocal last_pos while last_pos >= 0 and arr[...
def index_words(text): """ index_words :param text: :return: """ result = [] if text: result.append(0) for index, letter in enumerate(text): if letter == ' ': result.append(index + 1) return result
def has(i): """Returns the form of the verb 'avoir' based on the number i.""" # Note: this function is used only for the third person if i == 1: return 'a' else: return 'ont'
def f2p_worlds(worlds: list): """ Filters a list of worlds to a list only containing f2p worlds """ return [world for world in worlds if world['f2p'] and not world['vip']]
def returnRainfall(dd): """Returns rainfall data in units kg/m2/s""" rho_fresh = 1000 # freshwater density rain = [] if 'LIQUID_PRECIPITATION_VOLUME' in dd: period = dd['LIQUID_PRECIPITATION_DURATION'] # hours volume = dd['LIQUID_PRECIPITATION_VOLUME'] # mm rain = volume/...
def replace_in_str(rstring, repres): """Replace keys by values of repres in rstring.""" for k in sorted(repres.keys(), key=len, reverse=True): rstring = rstring.replace(k, repres[k]) return rstring
def print_tree(ifaces): """ Prints a list of iface trees """ return " ".join(i.get_tree() for i in ifaces)
def _construct_param(arg_name): """Converts argument name into a command line parameter.""" return f'--{arg_name.replace("_", "-")}'
def add_whitespaces(file_contents, symbols): """Adds whitespaces around symbols""" for symbol in symbols: if symbol in file_contents: file_contents = file_contents.replace(symbol, " " + symbol + " ") return file_contents
def pattern_count(text, pattern): """[finds all occurences of a pattern in a text of bases] Args: text ([string]): [input string] pattern ([string]): [pattern to search for in string] Returns: [int]: [running tally of how many occurrences of pattern were found in text] ...
def remove_assc_goids(assoc, broad_goids): """Remove GO IDs from the association, return a reduced association""" actuall_removed_goids = set() actuall_removed_genes = set() assc_rm = {} for geneid, goid_set in assoc.items(): rm_gos = goid_set.intersection(broad_goids) if rm_gos: ...
def link_easy(sid): """ Creates an html link to a dataset page in Easy. :param sid: a dataset id :return: link to the page for that dataset """ prefix = 'https://easy.dans.knaw.nl/ui/datasets/id/' return '<a target="_blank" href="{}{}">{}</a>'.format(prefix, sid, sid)
def is_valid(sequence, number): """ Returns True if the number is a sum of two discrete numbers in the preceding sequence. """ success = False for i,num in enumerate(sequence): if (number - num) in sequence[i:]: success = True break return success
def octet_str_to_int(octet_str: str) -> int: """ Convert octet string to integer. :param octet_str: Octet string to convert. :returns: Converted integer. """ return int(octet_str.replace(" ", ""), 16)
def get_href_attribute(xml_elem): """ Helping function which returns None or the href attribute. Since some xml documents use https for the w3.org reference, it is nicer to encapsulate the logic inside this separate function. Args: xml_elem: The xml element Returns: None | the att...
def modular_range(value, values): """ Provides a validator function that returns the value if it is in the range. Otherwise it returns the value, modulo the max of the range. :param value: a value to test :param values: A set of values that are valid """ return value % max(values)
def convert_float(s): """ Convert the string data field *s* to a float. If the value is 99999 (missing data) or 88888 (not observed), return not a number. """ f = float(s) if int(f) in [99999, 88888]: return float('nan') return f
def parse_sas_token(sas_token): """Parse a SAS token into its components. :param sas_token: The SAS token. :type sas_token: str :rtype: dict[str, str] """ sas_data = {} token = sas_token.partition(' ')[2] fields = token.split('&') for field in fields: key, value = field.spli...
def reindent(s, numSpaces=4, no_empty_lines=False): """ Return string s reindented by `numSpaces` spaces Args: s (string): string to reindent numSpaces (int): number of spaces to shift to the right no_empty_lines (bool): if True remove empty lines Returns: ...
def basic_sequence(piece_dict): """ Create a basic sequence with the given pieces. Keyword arguments: piece_dict -- The pieces dictionary with the quantity of each piece. """ sequence = [] # Iterate over the pieces original dict for piece, number in piece_dict.items(): if nu...
def counting_sort(arr): """ Counting_sort Sorting a array which has no element greater than k Creating a new temp_arr,where temp_arr[i] contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the result_arr return the result_arr Complexity: 0(n...
def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest co...
def get_cursor_ratio(image_size: tuple, screen_size: tuple): """ Used to calculate the ratio of the x and y axis of the image to the screen size. :param image_size: (x, y,) of image size. :param screen_size: (x, y,) of screen size. :return: (x, y,) as the ratio of the image size to the screen size. ...
def ij_tag_50838(nchannels): """ImageJ uses tag 50838 to indicate size of metadata elements (e.g., 768 bytes per ROI) :param nchannels: :return: """ info_block = (20,) # summary of metadata fields display_block = (16 * nchannels,) # display range block luts_block = (256 * 3,) * nchannels ...
def get_link_root(link): """ Gets the root of a url Inputs: link - the url of the page Output: Returns the root of the link if it can fint it. Otherwise, returns -1. """ websites = ["com", "org", "net", "int", "edu", "gov", "mil"] for extension in websites: ind...
def htseq_quant(curr_sample, out_dir, ERCC_gtf, strand): """ Use htseq-count for quantification """ cmd = "" cmd=cmd+"mkdir "+out_dir+"htseq_out/\n" if strand=="nonstrand": # non-strand-specific assay: capture coding transcriptome without strand information cmd=cmd+"samtools view "+cur...
def parse_categorised_lists( data, header_formatter, formatter, list_parser, sorted_keys=None ): """Parses each element in data using a formatter function. Data is a dict, each key is a category and each value is a list of dicts. Adds a header for each category. """ if sorted_keys is None: ...
def three_point_derivative(f,x,h): """#3-point function to calaculate 1st derivative""" h = float(h) return (1/(2*h))*(f(x-2*h) - 4*f(x-h) + 3*f(x))
def marshal_error(error): """Gather/Marshal error details. Args: error (Object): Instance of NetworkLicensingError or OnlineLicensingError or MatlabError Returns: Dict: Containing information about the error. """ if error is None: return None return { "message":...
def convert_pH_temp(pH, original_temperature, desired_temperature): """Convert pH between temperatures. Parameters ---------- pH : float pH as measured. original_temperature : float Measurement temperature, in degrees Fahrenheit. desired_temperature : float Temperatur...
def sharedLangCost(criterion, frRow, exRow): """Returns 1 if the two do not share a language, else 0""" fluentQ = criterion['fluentQ'] learningQ = criterion['learningQ'] frLangs = [set(frRow[fluentQ].split(',')), set(frRow[learningQ].split(','))] exLangs = [set(exRow[fluentQ].split('...
def geojson_to_features_list(json_data: dict) -> list: """ Converts a decoded output GeoJSON to a list of feature objects The purpose of this formatting utility is to obtain a list of individual features for decoded tiles that can be later extended to the output GeoJSON From:: >>> {'type'...
def check_memory_burst(msgs): # type: (str) -> bool """ Check if memory burst is inferred as expected FIXME: Now we only check if Merlin failed to infer burst for any array instead of further checking the burst length """ #tracking = False for msg in msgs: # pylint: disable=n...
def insert_sub_reqs(reqs, levels, req_info): """Recursively build all requirements in correct order.""" all_reqs = [] for _, req in enumerate(reqs): # Coefficients are referenced as 'c.<name>'... areq = req[2:] if req.startswith('c.') else req try: rargs = req_info[areq]...
def _hr_time(seconds): """Convert time in seconds to a human readable string""" minutes = seconds // 60 if not minutes: return '{}s'.format(seconds) hours = minutes // 60 if not hours: seconds -= minutes * 60 return '{}m {}s'.format(minutes, seconds) days = hours // 24 ...
def get_weights(w = 1.7, length = 20): """Returns a list of weights, based on quadratic function""" return [w**i for i in range(length, 0, -1)]
def scale(x, range, drange): """ From real coordinates get rendered coordinates. :param x: source value :param range: (min,max) of x :param drange: (min,max) of sx :return: scaled x (sx) """ (rx1, rx2) = float(range[0]), float(range[1]) (sx1, sx2) = float(drange[0]), float(drange[1]...
def _softint(intstr, base=10): """ Try to convert intstr to an int; if it fails, return None instead of ValueError like int() """ try: return int(intstr, base) except ValueError: return None
def _get_any_bad_args(badargs, dictionary): """Returns the intersection of 'badargs' and the non-Null keys of 'dictionary'.""" return list(illegal for illegal in badargs \ if illegal in dictionary and dictionary[illegal] is not None)
def get_key_presses(songs, data, replay): """This function returns the number of keys pressed during a run, because why not""" if songs < 0: return 0 keys = 0 for i in range(0, songs): keys += int(data[(i+1)*11]) return keys
def ip_bytes_to_int(ip_bytes: list)->int: """ :param ip_bytes: :return: """ return (ip_bytes[0] << 24) | (ip_bytes[1] << 16) | (ip_bytes[2] << 8) | \ ip_bytes[3]
def get_return_types_as_tuple(arg_id_to_dtype): """Returns the types of arguments in a tuple format. :arg arg_id_to_dtype: An instance of :class:`dict` which denotes a mapping from the arguments to their inferred types. """ return_arg_id_to_dtype = {id: dtype for id, dtype ...
def fuzzy_substring(needle, haystack): """Calculates the fuzzy match of needle in haystack, using a modified version of the Levenshtein distance algorithm. The function is modified from the levenshtein function in the bktree module by Adam Hupp. Taken and modified from: http://ginstrom.com/...
def compare(sample_list, first, last): """ This function aims to find tuples with each unique first element.For equal first element tuples, find the one with largest last element. Parameters ---------- sample_list : list, This parameter represents the a list of several tuples. fir...
def bigger_price(limit, data): """ TOP most expensive goods """ res = sorted(data, key=lambda k: k['price'], reverse=True) return res[:limit]
def filter_planes(feature_dict, removeDirection, percentile): """filter planes by the criteria specified by removeDirection and percentile Args: feature_dict (dictionary): planes and respective feature value removeDirection (string): remove above or below percentile percentile (int...
def boolean(value): """ Converts string into boolean Returns: bool: converted boolean value """ if value in ["false", "0"]: return False else: return bool(value)
def arch_sampling_str_to_dict(sampling_str): """ Converts string representations of architecutre sampling methodology to the dictionary format that nas_searchmanager.SearchManager uses. Example: \"1:4,2:4,3:4,4:4\" is converted to {1.0 : 4, 2.0 : 4, 3.0 : 4, 4.0 : 4}. """ # Remove ...
def msgEpoch(inp): """ Taken (with permission) from https://github.com/TheElementalOfCreation/creatorUtils """ return (inp - 116444736000000000) / 10000000.0
def brook(x): """Brook 2014 CLUES inverted subhalo mass function. Keyword arguments: x -- array of peak halo masses """ tr = 38.1*1.e10/(x**(1./0.89)) return tr
def remove_Es(a_string): """Implement the code required to make this function work. Write a function `remove_Es` that receives a string and removes all the characters `'e'` or `'E'`. Example: remove_Es('remoter') # 'rmotr' remove_Es('eEe') # '' remove_Es('abc') # 'abc' """ b...
def gender_aware(line, genders): """ :param line: string line :param genders: map from "name" to "name[gender]" """ for old_name, new_name in genders.items(): line = line.replace(old_name, new_name) return line
def get_change_record(hostname: str, addr: str, rrtype: str): """Return a Route 53 request to UPSERT a resource record. As documented in https://boto3.amazonaws.com/v1/documentation/api/latest/reference/ \ services/route53.html#Route53.Client.change_resource_record_sets """ assert rrtype in...
def get_recall(mx): """Gets sensitivity, recall, hit rate, or true positive rate (TPR) Same as sensitivity """ [tp, fp], [fn, tn] = mx return tp / (tp + fn)
def azure_securityzone(azure_nic={"ipAddress": "", "tags": []}): """ Returns security zone from azure nic ipaddress """ prefix = 'azure_SecurityZone' security_zone = [t for t in azure_nic['tags'] if '_SecurityZone_' in t] if security_zone: if '_High' in security_zone[0]: return f'{prefix}_High' el...
def _time_to_seconds_past_midnight(time_expr): """ Parse a time expression to seconds after midnight. :param time_expr: Time expression string (H:M or H:M:S) :rtype: int """ if time_expr is None: return None if time_expr.count(":") == 1: time_expr += ":00" hour, minute, s...
def complex_multiply(x, y): """ Element wise multiplication for complex numbers represented as pairs """ x_re, x_im = x y_re, y_im = y z_re = (x_re * y_re) - (x_im * y_im) z_im = (x_re * y_im) + (x_im * y_re) return z_re, z_im
def relu_activation(x): """ Returns x if positive, 0 otherwise. """ return x if x > 0.0 else 0.0
def _split_svg_style(style): """Return `dict` from parsing `style`.""" parts = [x.strip() for x in style.split(';')] parts = [x.partition(':') for x in parts if x != ''] st = dict() for p in parts: st[p[0].strip()] = p[2].strip() return st
def getType(string: str): """getType Gives type of a type string (right hand side) :param string: :type string: str """ if '#' in string: string = string.rsplit('#', 1)[1] return string.rsplit('.', 1)[-1]
def longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """ if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) ...
def find_nearest_locus(start, end, loci): """ Finds nearest locus (object with method `distance_to_interval`) to the interval defined by the given `start` and `end` positions. Returns the distance to that locus, along with the locus object itself. """ best_distance = float("inf") best_locus ...
def decode_payload(encoding, payload): """Decode the payload according to the given encoding Supported encodings: base64, quoted-printable. :param encoding: the encoding's name :param payload: the value to decode :return: a string """ encoding = encoding.lower() if encoding == "base64"...
def get_base_layout(figs): """ Generates a layout with the union of all properties of multiple figures' layouts Parameters: ----------- fig : list(Figures) List of Plotly Figures """ layout = {} for fig in figs: if not isinstance(fig, dict): fig =...
def gt_support(A,x): """ Return set of support for probability vector x. Here A and x have the same length. A is the list of candidates. x is a list of their probabilities. Probability is `non-zero' if it is greater than epsilon = 1e-6. """ epsilon = 1e-6 support = [ ] for (xi,...
def to_pecha_id_link(pecha_id): """Return pecha_id_link for `pecha_id`.""" return f"[{pecha_id}](https://github.com/OpenPecha/{pecha_id})"
def quadratic_inverse_distortion_scale(distortion_coefficient, distorted_r_squared, newton_iterations=4): """Calculates the inverse quadratic distortion function given squared radii. The distortion factor is 1.0 + `distortion_coefficient` * `r_squared`. When `distortion_coefficient` is negative (barrel distort...
def flatten(x): """Build a flat list out of any iter-able at infinite depth""" result = [] for el in x: # Iteratively call itself until a non-iterable is found if hasattr(el, "__len__") and not isinstance(el, str): flt = flatten(el) result.extend(flt) else: ...
def sidak_inv(alpha, m): """ Inverse transformation of sidak_alpha function. Used to compute final p-value of M independent tests if while preserving the same significance level for the resulting p-value. """ return 1 - (1 - alpha)**m
def run_and_read_all(run_lambda, command): """Runs command using run_lambda; reads and returns entire output if rc is 0""" rc, out, _ = run_lambda(command) if rc != 0: return None return out
def remove_underscore(text): """ Call this on variable names and api endpoints, so that BERT tokenizes names like 'find_place' as 'find place'. """ return text.replace("_", " ")
def disable_current_user_run(on=0): """Desabilitar Execucao de Comandos Especificados no Registro DESCRIPTION Esta restricao e usada para desabilitar a habilidade de executar programas de inicializacao especificados no registro quando o Windows e carregado. COMPATIBILITY ...
def pad(fingering, width): """Return fingering as a string, each note padded to the given width.""" return ''.join(str(f).ljust(width) for f in str(fingering))
def get_new_keys(values: dict, idx): """ :param values: Werte aus der JSON-Datei :param idx: Index des Arrays, welches gerade betrachtet wird. :return: """ return values["new_keys"][idx] if values.get("new_keys", None) else values["keys"][idx]
def calc_faculty(c_cid, cid_s, bad): """ c_cid : Given a class, map it to it's clump ID cid_s : Given a clump ID, map it to its slot bad: Given a CRN, tell me a set of slots that the CRN shouldn't go in. Returns: Number of courses scheduled into slots that the professor has said will not w...
def bytes_to_human_readable(bytes_in, suffix='B'): """ Convert number of bytes to a "human-readable" format. i.e. 1024 -> 1KB Shamelessly copied from: https://stackoverflow.com/a/1094933/2307994 :param int bytes_in: Number of bytes to convert :param str suffix: Suffix to convert to - i.e. B/KB/MB ...