content
stringlengths
42
6.51k
def update_ema(biased_ema, value, decay): """ calculate biased stat and unbiased stat in each step using exponential moving average method Parameters ---------- biased_ema : float previous stat value value : float current stat value decay : float the weight of previo...
def get_delta(k, c=1.0874, s=1.0187): """ Estimate the approximate expected transit depth as a function of radius ratio. There might be a typo here. In the paper it uses c + s*k but in the public code, it is c - s*k: https://github.com/christopherburke/KeplerPORTs :param k: the dimensionless ra...
def untag(tagged_sentence): """ Given a tagged sentence, return an untagged version of that sentence. I.e., return a list containing the first element of each tuple in C{tagged_sentence}. >>> untag([('John', 'NNP'), ('saw', 'VBD'), ('Mary', 'NNP')] ['John', 'saw', 'mary'] """ return [w...
def largest_factor(n): """Return the largest factor of n*n-1 that is smaller than n. >>> largest_factor(4) # n*n-1 is 15; factors are 1, 3, 5, 15 3 >>> largest_factor(9) # n*n-1 is 80; factors are 1, 2, 4, 5, 8, 10, ... 8 """ factor = n - 1 while factor > 0: if (n*n-1) % factor ...
def _process_blacklist(resource, blacklist): """ Process a blacklist of keys """ new_resource = {} for key, value in resource.items(): if key not in blacklist: new_resource[key] = value return new_resource
def count_word_occurrence_in_string(text, word): """ Counts how often word appears in text. Example: if text is "one two one two three four" and word is "one", then this function returns 2 """ words = text.split() return words.count(word)
def encode(number, base): """Encode given number in base 10 to digits in given base. number: int -- integer representation of number (in base 10) base: int -- base to convert to return: str -- string representation of number (in given base)""" # Handle up to base 36 [0-9a-z] assert 2 <= base <= ...
def flip_dict(original_dict): """ Flip keys and values of the dictionary :param original_dict: DESCRIPTION :type original_dict: TYPE :return: DESCRIPTION :rtype: TYPE """ flipped_dict = {} for k, v in original_dict.items(): if v in [None, "special"]: continue ...
def _IsRemoteBetter(new_name, old_name): """Indicates if a new remote is better than an old one, based on remote name. Names are ranked as follows: If either name is "origin", it is considered best, otherwise the name that comes last alphabetically is considered best. The alphabetical ordering is arbitrary, b...
def pi_sub_list_to_str(pi_list, index): """ Parameters ---------- pi_list list of pi number expressions index indexes of chosen pi numbers Returns A string with only the chosen pi numbers ------- """ out_set = "" if len(pi_list) > 0: for i in range(len(pi_l...
def sequence_equals(sequence1, sequence2): """ Inspired by django's self.assertSequenceEquals Useful for comparing lists with querysets and similar situations where simple == fails because of different type. """ assert len(sequence1) == len(sequence2), (len(sequence1), len(sequence2)) for i...
def getFasta(opened_file, sequence_name): """ Retrieves a sequence from an opened multifasta file :param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+') :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:1...
def get_max(a: int, b: int) -> int: """ if a < b then -(a < b) = -1 elif a > b then -(a < b) = 0 (a^b) & -1 = a^b (a^b) & 0 = 0 """ return a ^ ((a ^ b) & -(a < b))
def overl(l1, l2): """ calculate overlap of two lists """ return len(set(l1).intersection(l2)) / max([len(l1), len(l2)])
def second_bubble_sort(numbers): """Second implementation of bubble sort. Contains the first optimization: excluding the last sorted item at each iteration. The iteration counter will be present to show the difference between each implementation. Args: numbers (list): list of integers to be sor...
def parseUnits(value, units): """ Parses a value with a unit and returns it in the base unit. :param value: str The value to parse :param units: list of tuples of unit names and multipliers :return: int """ n = len(value) for i, c in enumerate(value): if c.isalpha(): n = i break numberStr = value[:n]...
def uris_from_lookup_response(response): """Return list of URIs from response from /lookup_datasets/<uuid>.""" return [item["uri"] for item in response]
def clean_text(text): """Cleans raw text so that it can be written into a csv file without causing any errors.""" temp = text temp = temp.replace("\n", " ") temp = temp.replace("\r", " ") temp = temp.replace(",", " ") temp.strip() return temp
def strip_args(line): """Takes com.some.thing.Class.method(this.that.SomeThing) and removes arguments and parentheses.""" method, _ = line.split("(") return method
def check(index, x, y, diff_x, diff_y, block_width): """ image: 0 y y y y y y y y x x x x x index range: 0 - 31 block_width range: 8 - 1000 revert: diff_image_index = (num_1 >> 22) & 0x1f x = (num_1 >> 11) & 0x7ff y...
def _prefixed_flag_vals(prefixes, flag_vals): """Returns a dict of prefixed flag values. Prefixes are stripped from matching flag names. The value for the first matching prefix from prefixes is used. """ prefixed = {} for prefix in prefixes: for full_name in flag_vals: if f...
def get_by_name(yaml, ifname): """Return the loopback by name, if it exists. Return None otherwise.""" try: if ifname in yaml["loopbacks"]: return ifname, yaml["loopbacks"][ifname] except KeyError: pass return None, None
def text_from_buffer(b, l1, l2): """ Return the text from the given buffer between the given lines This starts at a line before the given index to get all the text From the array of lines, joined by a newline """ if l1 > 0: l1 -= 1 return {"content": "\n".join(b[l1:l2])}
def validate_project_name(project_name): """Must be ascii alnum and start with letter""" if not project_name or not isinstance(project_name, str): return False if not project_name[0].isalpha(): return False if not project_name.isalnum(): return False return True
def compute_mae(y_pred, y, center_to_border_dict=None): """ Returns the absolute distance of predicted value to ground truth. Args center_to_border_dict is for compatibility issues in quanfification error analysis. """ return abs(y_pred - y)
def str_to_bool(s: str) -> bool: """Convert 'True' or 'False' provided as string to corresponding bool value.""" if s == "True": return True elif s == "False": return False else: raise ValueError
def get_aggregation_func(path, aggregation_functions): """Lookup aggregation function for path, if any. Defaults to 'mean'. :param path: Path to lookup :type path: str :param aggregation_functions: Aggregation function configuration :type aggregation_functions: dict(<pattern>: <compiled regex>)...
def volts_to_watts(V): """ Volts to watts for a 50 ohm load @param V : volts @type V : float @return: watts """ return V**2/50.
def permutation_from_disjoint_cycles_to_cauchy(cyclic_perm): """ from [[1, 3, 5], [2, 4]] to [[1, 2, 3, 4, 5], [3, 4, 5, 2, 1]] """ pairs = sorted([(a, b) for cycle in cyclic_perm for a, b in zip(cycle, cycle[1:] + cycle[:1])]) return [list(i) for i in zip(*pairs)]
def is_collection(value) -> bool: """ Check if value is a collection """ return any([isinstance(value, list), isinstance(value, set), isinstance(value, tuple)])
def scope2string(scope): """ Auxiliary function that converts the scope (list of ints) into a string for printing. """ if len(scope) <= 5: return scope res = '' first = scope[0] last = None for i in range(1, len(scope)-1): if scope[i-1] != scope[i]-1: ...
def json_elements_to_atom_fractions(elements): """Calculate element atomic number fractions from the Elements data.""" results = [] for element in elements: line = f"{element['Element']} {element['AtomFraction_whole']:.6f}" results.append(line) return results
def transform_cmds(argv): """ Allows usage with anaconda-project by remapping the argv list provided into arguments accepted by Bokeh 0.12.7 or later. """ replacements = { '--anaconda-project-host':'--allow-websocket-origin', '--anaconda-project-port': '--port', '--anaconda-p...
def _intensity_to_eeg(intensity): """Intensity is uniform random between [0, 1], eeg is [-1, 1].""" return (intensity - 0.5)*2.0
def tblfmt(v, strpad=0): """Table-like formatting of the value strpad: int - string padding """ if isinstance(v, float): return '{:.3f}'.format(v) elif isinstance(v, int): return str(strpad).join(('{:', '}')).format(v) if v is None: v = '-' elif not isinstance(v, str): v = str(v) return v.rjust(strpad...
def sum_of_proper_divisors(n): """ Returns the sum of proper divisors of the given number excluding itself.""" ## Your code starts here sum = 1 for div in range(2, n): if n%div == 0: sum += div return sum ## Your code ends here
def stats_variable_names(res): """Return the variable names for a stats object""" def varname(s): pos = s.find(':') return s if pos==-1 else s[0:pos] return set( [ varname(key) for key in res.keys()] )
def getattr_unwrapped(env, attr): """Get attribute attr from env, or one of the nested environments. Args: - env(gym.Wrapper or gym.Env): a (possibly wrapped) environment. - attr: name of the attribute Returns: env.attr, if present, otherwise env.unwrapped.attr and so on recursively....
def set_checksum_args(arguments): """ Argparse parses checksums as {'checksum_sha256': '<sha256_hash>'} Return a list of these arguments in a format the Identifiers Service understands: "checksums": [ { "function": "md5", "value": "fobarbas" }, { "function...
def add_fixed_mods(seqs:list, mods_fixed:list, **kwargs)->list: """ Adds fixed modifications to sequences. Args: seqs (list of str): sequences to add fixed modifications mods_fixed (list of str): the string list of fixed modifications. Each modification string must be in lower case, except f...
def to_text(diffs): """Diff type of non -1 will be appended to generate a text which contains transfered annotations. Args: diffs (list): list diff tuples containing diff type and diff value Returns: str: annotation transferd text """ result = "" for diff in diffs: if d...
def calc_relative_error(reference, array): """Calculates relative error (%).""" return ((array - reference) / reference) * 100
def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm
def partition(my_list: list, part: int) -> list: """ Function which performs Partition """ begin = 0 end = len(my_list) - 1 while begin < end: check_lower = my_list[begin] < part check_higher = my_list[end] >= part if not check_lower and not check_higher: # Swap ...
def get_length_of_list_of_iterables(list_of_tuples): """Get the total length of a list of tuples.""" length = 0 for tuple_item in list_of_tuples: length += len(tuple_item) return length
def matrix_looks_valid(matrix): """\ Returns if the matrix contains just ``0x0`` and ``0x1`` values. Does not check if the the matrix represents a valid (Micro) QR Code. :param matrix: tuple of bytearrays :return: """ invalid_values = [] for i, row in enumerate(matrix): for j, b...
def create_branch_node_promise_var(node_id: str, var: str) -> str: """ Generates a globally (wf-level) unique id for a variable. When building bindings for the branch node, the inputs to the conditions (e.g. (x==5)) need to have variable names (e.g. x). Because it's currently infeasible to get the name...
def get_class_name(class_or_instance) -> str: """Return the fully qualified name of a class.""" try: return class_or_instance.__qualname__ except AttributeError: # We're dealing with a dataclass instance return type(class_or_instance).__qualname__
def cam_name(cam_index): """ Returns the name of the depth map for index: 0-48 """ if cam_index < 10: return '0000000{}_cam.txt'.format(cam_index) else: return '000000{}_cam.txt'.format(cam_index)
def embed_youtube(videolink): """Embed a youtube video. I hope.""" url = videolink url = url.replace("https://youtu.be/", "https://www.youtube.com/embed/") url = url.replace("watch?v=", "embed/") return '<iframe width="560" height="315" src="{url}" frameborder="0" allow="autoplay; encrypted-media" a...
def block_quoter(foo): """ Indents input with '> '. Used for quoting text in posts. :param foo: :return: """ foo = foo.strip() split_string = foo.split("\n") new_string = "" if len(split_string) > 0: for i in split_string: temp_string = "> " + i new_s...
def checksum_tle_line(_line): """ Performs TLE-defined checksum on TLE line""" check = 0 for char in _line[:-1]: if char.isdigit(): check += int(char) if char == "-": check += 1 _check_val = check % 10 return(_check_val)
def choice_line (matrix): """a- Choix de la ligne qui contient le moins de zero libre""" line = 0 liste_nb_zero = list() liste_sans_zero = list() for line in matrix: liste_nb_zero.append(line.count(0)) for elt in liste_nb_zero: if elt != 0: liste_sans_zero.append(elt)...
def str2bool(value): """ Map "true"/"false" => True/False """ if value.lower() in ["true", "t", "1", "yes", "y"]: return True elif value.lower() in ["false", "f", "no", "n", "0"]: return False else: raise ValueError
def default_send_tx_request_parameters(rpc_client_id, serialized_address): """Default required request parameters for a POST request to /transactions.""" parameters = {"client_id": rpc_client_id, "to": "the_address", "value": 123, "startgas": 2} return parameters
def _convert_labels_dict_to_list(parent): """Covert "labels" from dictionary into list of "name", "value" pairs. This makes the resulting BigQuery schema more consistent when the json object has arbitrary user supplied fields. Args: parent: dict object. Returns: The modified dict o...
def chop_end_of_string(str_input, str_remove): """Function that strips the supplied str_remove from the end of the input string Parameters ---------- str_input: `str` A string to be chopped str_remove: `str` The string to be removed from the end of the input ...
def get(vals, key, default_val=None): """ Returns a dictionary value """ val = vals for part in key.split('.'): if isinstance(val, dict): val = val.get(part, None) if val is None: return default_val else: return default_val retu...
def get_bool_arg(arg): """Parse boolean argument.""" return arg in ["true", "True", "TRUE", "on", "On", "ON", "1"]
def check_reference_positions(reference_sequence: str, positions: list) -> bool: """ Takes the aligned reference sequence and the list of parsed positions and checks to see if there are any dashes at the beginning of the sequence. If there are, they are removed and the positions are corrected. Para...
def is_operator(node): """This function checks whether a validation node is an operator or not. Args: node(str): The node key you want to check. Returns: : bool. """ return node.startswith('$')
def _attrs2dict(attrs): """Take an (attribute, value) list and make a dict""" dict = {} for (a,v) in attrs: dict[a] = v return dict
def get_sts_endpoint(region): """Get regionalized STS endpoint.""" return "https://sts.{0}.{1}".format(region, "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com")
def to_weighted(graph, weight=1): """ Add a default weight to edges of graph if it doesn't have any :param graph: :param weight: :return: """ new_graph = {} for node, neighbors in graph.items(): if node not in new_graph: new_graph[node] = {} for...
def recurse_access_key(current_val, keys): """ Given a list of keys and a dictionary, recursively access the dicionary using the keys until we find the key its looking for If a key is an integer, it will convert it and use it as a list index Example: >>> recurse_access_key({'a': 'b'}, ['a']) ...
def is_compatible_dict(base, delta): """ returns False if any key common to base/delta has a different type, except for None values, dicts are evaluated recursively """ common_keys = [k for k in base if k in delta] for k in common_keys: if base[k] is None or delta[k] is None: ...
def string_contrains_substring(str1, str2): """Function to return True if str1 contains str2 otherwise return False.""" if str1.find(str2) >= 0: return True else: return False
def cell(point, size): """ returns the grid cell coordinates containing the given point. size is the side length of a grid cell beware: in other languages negative coordinates need special care in C++ for example int(-1.5) == -1 and not -2 as we need hence we need floor(x / pas) in C++ using #inclu...
def area_parallelogram(base: float, height: float) -> float: """ Calculate the area of a parallelogram. >>> area_parallelogram(10, 20) 200 >>> area_parallelogram(-1, -2) Traceback (most recent call last): ... ValueError: area_parallelogram() only accepts non-negative values...
def fn_Calc_SearchVolume(az,el): """ az,el in deg eqn 1.61 in Mahafza book """ return az*el/(57.296**2)
def bitscatter(bits, mask): """ Scatters the contents of bitvector `bits` onto the raised bits in `mask`. """ value = 0 mask_walker = enumerate(reversed(bin(mask)[2:])) for bit_index, mask_index in enumerate([x for x, y in mask_walker if y == '1']): value |= (bits & (1 << bit_index)) << ...
def _check_ip(ip: str) -> bool: """ Check IP in range. """ # address = ipaddress.IPv4Address(ip) # return address in allowed_ips # todo add fb ip return True
def exponential(x, halflife): """ Returns a decay factor based on the exponential function .. math:: f(x) = 2^(-x/halflife). :param x: The function argument. :param halflife: The half-life of the decay process. """ return 2 ** (-x / halflife)
def mandelbrot_iterate(c, max_iterations, julia_seed=None): """ Returns the number of iterations before escaping the Mandelbrot fractal. :param c: Coordinates as a complex number :type c: complex :param max_iterations: Limit of how many tries are attempted. :return: Tuple containing the last co...
def fall(func, iterable): """ fall(func: function, iter: iterable) return true if all element x make func(x) == True args: func = x > 0, iter = [-1,0,1] return: False """ for x in iterable: if not func(x): return False return True
def _hydrate_active_votes(vote_csv): """Convert minimal CSV representation into dpayd-style object.""" if not vote_csv: return [] cols = 'voter,rshares,percent,reputation'.split(',') votes = vote_csv.split("\n") return [dict(zip(cols, line.split(','))) for line in votes]
def get_exponent(number, base): """If number = base**k, returns k. Else returns None """ if number <= 1: return 0 k = 0 if base > 1: while number % base == 0: number /= base k += 1 return k if number == 1 else None
def validate_bbox_wgs84(bbox): """ Function purpose: Validate if bbox is correct for WGS84 bbox: bounding box (list) Output: True if bbox is correct for WGS84 """ valid = True lon_values = bbox[0:3:2] lat_values = bbox[1:4:2] if sum(list(map(lambda x: x < -90 or x > 90, lat_values))...
def filter_item(item): """Only return specified keys""" keys = ["display_name", "installed_version", "installed_size", "version_to_install", "installed", "note"] out = {} for key in keys: try: out[key] = item[key] # pylint: disable=pointless-except except...
def nextDay(year, month, day): """Simple version: assume every month has 30 days""" if day < 30: return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1
def reconcile_countries_by_name(plot_countries, gdp_countries): """ Inputs: plot_countries - Dictionary whose keys are plot library country codes and values are the corresponding country name gdp_countries - Dictionary whose keys are country names used in GDP data Output...
def make_file_list(files): """Make a list of subject files. Parameters ---------- files : dict Collection of files per subject. Returns ------- file_lst : list of str List of all subject files. """ file_list = [] for subj, sessions in files.items(): for...
def get_molecule_subset(molecule_set, init_idx, n_molecules, subset_size): """ "Slices" the input set of molecules (`molecules_set`) into a subset of size `subset_size` (`int`), starting from `init_idx` (`int`). `n_molecules` (`int`) is the number of molecules in the full `molecule_set` (`list`). ""...
def anotherFunction(x,y,z): """this is my docString""" m=x**2+y**2+z**2 return m
def divisible_cheksum(string): """Take rows of numbers and return the sum of their divisible pairs.""" total = 0 # Split string so each row is its own embedded list row_list = [] rows_split = string.split('\n') for i in rows_split: row_string = str(i) row = row_string.split() ...
def prime_factorization(n): """Returns a divtionary with the prime facotrs of n and it's prime factorization """ if n == 1: return {1:1} i = 2 k = n**0.5 prime_factors = {} while i <= k: if n%i == 0: n //= i k = n**0.5 prime_factors[i] = prime_factors[i] + 1 if i in prime_factors else 1 i -= 1...
def ifEmpty(str, defStr): """ if a string is empty, return the defStr in its place """ if str is None or str == "": str = defStr return str
def split(text): """ Splits text into a list of paragraphs, each of which is a list of sentences. """ paragraphs = text.split("\n\n") paragraphs = [paragraph.split("\n") for paragraph in paragraphs] return paragraphs
def is_number(s: str) -> bool: """Returns True if given string is a number""" try: int(s) return True except ValueError: return False
def dotClose(input,footer): #OLDNAME dot_close """ Close the graphiz config file Return final output to be written """ input.extend(footer) input.append("}") output = ''.join(input) return output
def active_class(var, prop, active): """Tag to return an active class if the var and prop test matches.""" try: return active if var == prop else '' except Exception: return ''
def li_worker(func, time, storage, *args, **kwargs): """limits the time taken for exection of given function Args: func (`function`): function to execute limit (`int`): maximum allowed time in seconds storage (`list`): multiprocessing.Manager().List() to store the peak memory ar...
def str_to_bool(val: str) -> bool: """Takes string and tries to turn it into bool as human would do. If val is in case insensitive ("y", "yes", "yep", "yup", "t","true", "on", "enable", "enabled", "1") returns True. If val is in case insensitive ("n", "no", "f", "false", "off", "disable", "disabl...
def tobin(i): """ Maps a ray index "i" into a bin index. """ #return int(log(3*y+1)/log(2))>>1 return int((3*i+1).bit_length()-1)>>1
def dash(n): """ The function turns the answer into dashes and shows the length of the answer. :param n: int, the length of the answer. :return: str, a string consists of dashes. """ dash = '' for i in range(n): dash += '-' return dash
def translatePrefixes(xpath, namespaces): """Translate prefix:tag elements in an XPath into qualified names.""" elts = [] for elt in xpath.split('/'): if elt.find(':') > 0: prefix, tag = elt.split(':') if prefix in namespaces: elts.append(namespaces[prefix] + ...
def int_to_base36(i: int): """Convert an integer to a base36 string.""" char_set = "0123456789abcdefghijklmnopqrstuvwxyz" if i < 0: raise ValueError("Negative base36 conversion input.") if i < 36: return char_set[i] b36 = "" while i != 0: i, n = divmod(i, 36) b36 ...
def getRelativePositionTupleToAncestor(win, ancestor): """ Calculates relative pixel position of win to ancestor where ancestor is either parent, grandparent, grandgrandparent ... or None for absolute position. Returns a tuple with the position. """ resultx = 0 resulty = 0 w...
def until(p, f, a): """``until :: (a -> Bool) -> (a -> a) -> a -> a`` Yields the result of applying `f` until ``p(a)`` holds. """ while not p(a): a = f(a) return a
def frame_from_timecode(timecode, fps=24.0): """ Return the frame corresponding to the given timecode, for the given fps. :param timecode: String, timecode. :param fps: Float representing frames-per-second. :returns: Int representing a number of frames. """ # Return a frame of 0 if we don'...