content
stringlengths
42
6.51k
def totalTreeLengthFinder(nt): """totalTreeLengthFinder() takes a newickTree and finds the total length of the entire tree. """ treeLength = 0 if nt is None: return treeLength treeLength = nt.distance return treeLength + totalTreeLengthFinder(nt.right) + totalTreeLengthFinder(nt.left...
def ridiculously_recursive(n): """Requires maxsize=None when called on large numbers.""" if n <= 0: return 1 result = 0 for i in range(1, 200): result += ridiculously_recursive(n - i) return result
def sum_chars(char, other): """Sum the value of two string characters. Args: char (char): string of the integer. other (char): string of the integer. Returns: (int): sum of the integer value of `x` and integer value of `y`. """ return int(char) + int(other)
def find(value_to_find, attribute, search_space): """Find a video with matching id in a dict or list""" for video in search_space: if video[attribute] == value_to_find: return video raise KeyError('Metadata for {} does not exist'.format(value_to_find))
def hsva_to_rgba(h, s, v, a): """ Converts a HSVA color to a RGBA color. :param h: Hue :type h: int, float :param s: Saturation :type s: int, float :param v: Value :type v: int, float :param a: Alpha :type a: int, float :return: RGBA equivalent as list [r,g,b,a] :rtype: ...
def _calc_tm_sim_int_r0( A_int, B_int): """ Calculate tanimoto distance of A_int and B_int where X_int isinteger fingerprint vlaue of material A. """ C_int = A_int & B_int A_str = bin(A_int)[2:] B_str = bin(B_int)[2:] C_str = bin(C_int)[2:] lmax = max( [len( A_str), len( B_str), len( C_str)]) """ this show...
def manhattan_distance(point_a, point_b): """ Calcula a distancia manhattan entre dois pontos """ dist = 0 for i in range(len(point_a)): dist += abs(point_a[i] - point_b[i]) return dist
def _maybe_name(obj): """Returns object name if it has one, or a message otherwise. This is useful for names that apper in error messages. Args: obj: Object to get the name of. Returns: name, "None", or a "no name" message. """ if obj is None: return "None" elif hasattr(obj, "name"): retur...
def join(words, sep=' '): """join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space. (joinfields and join are synonymous) """ return sep.join(words)
def IF(logical_statement, expression_true, expression_false): """Evaluates the logical statement. If it is true, reuturns the true expression. If not, returns false expression. Parameters ---------- logical_statement : condition that evaluates to True or False condition that will return True or...
def get_prime_numbers_for_range(num_range): """ Get Prime numbers series Function to take num_range as integer and return prime numbers till number Parameters ---------- num_range : int Range of number Returns ------- list Author ------ Prabodh M Date ...
def extend(a, b): """Merge two dicts and return a new dict. Much like subclassing works.""" res = a.copy() res.update(b) return res
def make_dict_uppercase(dictionary): """Make dictionary uppercase""" uppercase_dict = { k.upper(): set(l.upper() for l in v) for k, v in dictionary.items() } return uppercase_dict
def hex_to_str(input: str) -> str: """ Convert a hex string into a human-readable string. XRPL uses hex strings as inputs in fields like `domain` in the `AccountSet` transaction. Args: input: hex-encoded string to convert Returns: Input encoded as a human-readable string. "...
def bar_grad(a=None, b=None, c=None, d=None): """Used in multiple tests to simplify formatting of expected result""" ret = [("width", "10em")] if all(x is None for x in [a, b, c, d]): return ret return ret + [ ( "background", f"linear-gradient(90deg,{','.join(x fo...
def _combine_baseline_window_stats(baseline_stat_list, prev_stats): """ Combine per baseline window stats into a greater window stat object """ result = prev_stats.copy() for stats in baseline_stat_list: result.update(stats) return result
def on_line(p1, p2, current): #returns 1 if current lies on line passing p1 and p2 """returns true if 'current' point lies on the line passing through 'p1' and 'p2' this is used to come out of wall following mode, according to bug2 algorithm""" #giving range, as there might be some error in computations ...
def get_line_number2(value, matrix): """ Function used to get the line number of a value in a array. Parameters ------------- value : 'float' Value of interest. matrix : 'numpy.ndarray' Vector with the value of interest. Returns ------------ Index """ fo...
def convertCityJsonData(cityData): """ function is processing and returning important data about place where will be searching for MPoints :param cityData: MAP_API json data :return: dictionary of city data """ cityDict = dict() for elements in cityData['results']: for key, value in...
def has(name, o): """Returns whether or not an object has an own property with the specified name""" if hasattr(o, str(name)): return True try: o[name] return True except (TypeError, KeyError): return False
def get_time(date): """takes in date from javascript/flask, and sets the variables hour and minute to their appropriate values >>> get_time("Tue Apr 23 2019 23:19:57 GMT-0400 (Eastern Daylight Time)") ('23', '19') >>> get_time("Wed Apr 24 2019 06:59:38 GMT+0300 (Asia Qatar Standard Time)") ('0...
def format_number(n: int) -> str: """ Formats large numbers using K M B T Q """ if n < 1000: return str(n) if n < 10000: s = str(f"{n/1000:.1f}") if s[-1] == '0': return s[:-2] + "K" return s + "K" if n < 1000000: return str(f"{n/1000:.0f}K")...
def check_demand(route, demand, max_load): """ Check if the load of the ant doesn't exceed max_load or isn't below zero """ sum = 0 for node in route: sum += demand[node.id] if sum > max_load or sum < 0: return False return True
def lr_schedule(epoch): """Learning Rate Schedule Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every epoch as part of callbacks during training. # Arguments epoch (int): The number of epochs # Returns lr (float32): learning rate ""...
def csv_to_list(s: str): """Parse comma-separated list (and make lowercase)""" return [x.lower().strip() for x in s.split(',')]
def parse_species(target): """ Based on Makefile target name, parse which species is involved """ genome = 'hg38' # hg gets normalized to hg38 toks = target.split('_') # Parsing reference species info if toks[2] in ['mm', 'zm', 'hg19']: genome = toks[2] return genome
def to_pt(value, units, dpi=96): """ convert length from given units to pt Arguments --------- value : float length in measurement units units : str unit type (e.g. "pt", "px", "in", "cm", "mm") dpi : float / int dots per inch (conversion between inches and px) ...
def calc_percentage_nees_within_ci(nees, ci): """ Calculates the percentage of NEES within the confidence interval """ within_ci = [ind_nees < ci[1] and ind_nees > ci[0] for ind_nees in nees] return sum(within_ci) / len(nees)
def get_file_contents(filename): """ Read file contents from file `filename` """ data = None try: with open(filename) as pf: data = pf.read() except IOError: # File not found, return None pass return data
def str2html(text): """Escape UTF8 string with HTML syntax.""" if isinstance(text, str): out = '' for char in text: # &, < and > if ord(char) in [38, 60, 62] or ord(char) > 127: out += '&#%d;' % (ord(char)) elif ord(char) == 10: ...
def wei_to_ether(wei): """Convert wei to ether. :param wei: :return: """ return 1.0 * wei / 10 ** 18
def _compute_propmotion_lin(tvals, mu_alpha, mu_delta, t_ref): """ Function to compute the term corresponding to the proper motion of the system assuming a simple linear model. INPUT: tvals: times, either single value or array [years] mu_alpha: linear proper motion in the rigth asce...
def _shiftedWord(value, index, width=1): """ Slices a width-word from an integer Parameters ---------- value: int input word index : int start bit index in the output word width: int number of bits of the output word Returns ------- An integer with the sliced ...
def to_class_name(name: str) -> str: """Convert to pascal class name.""" if name.find('-') != -1: parts = name.split('-') for i, part in enumerate(parts): parts[i] = part.capitalize() name = ''.join(parts) return name chars = list(name) chars[0] = chars[0]....
def flatten_json_object(hier_json): """ Flatten the JSON ojbect @param hier_json: Input JSON ojbect (with hierarchy) @type hier_json: JSON @return: Tag/values mapping @rtype: Dict """ flat_dict = {} def flatten(x, name=''): if isinstance(x, dict): for a in x: ...
def vector_function_column(table, function, index): """ This function carries out a given function on a given table column It is necessary to refer to the column index and the function as a function pointer """ for j in range(len(table)): try: table[j][index] = function(table[j][...
def intervals_to_list(data): """Transform list of pybedtools.Intervals to list of lists.""" return [interval.fields for interval in data]
def bit_get(val, idx): """ Gets the bit value. @Arg val: Input value, int or numpy int array. @Arg idx: Which bit of the input val. @Returns: The "idx"-th bit of input val. """ return (val >> idx) & 1
def _gen_kubectl_cmd(cmd, pod_name, pod_namespace=None): """easy wrapper to generate cmds for kubectl""" if isinstance(cmd, (list, tuple)): cmd_string = " ".join(cmd) elif isinstance(cmd, str): cmd_string = cmd else: raise TypeError("Can only take command as string / list tuple")...
def rectangle_to_square(rectangle, width, height): """ Converts a rectangle in the image, to a valid square. Keeps the original rectangle centered whenever possible, but when that requires going outside the original picture, it moves the square so it stays inside. Assumes the square is able to fit ...
def backends_mapping(backend_bin, backend_echo): """ Create 2 separate backends: - path to Backend echo: "/test/bin" - path to Backend httpbin: "/bin" """ return {"/test/bin": backend_echo, "/bin": backend_bin}
def fibonacci(n): """ compute the nth Fibonacci number """ a, b = 0, 1 if n == 0: return a for _ in range(n - 1): a, b = b, a + b return b
def transform3d_from_umpm(humans): """ transforms from umpm dataset ot kth :param humans: :return: """ human_t = [] for human in humans: new_human = [None] * 14 new_human[13] = human[0] new_human[12] = human[1] new_human[9] = human[2] new_human[10]...
def personal_top_three(scores): """Return the three highest scores.""" scores = sorted(scores, reverse=True) return scores[:3]
def make_table_path(keys, value, version=None): """ Generate a path to find a given lookup table. """ if isinstance(keys, (list, tuple)): keys = '/'.join(keys) path = '%s/%s' % (keys, value) if version: path += '.%s' % version path += '.csv' return path
def check_length(data, length): """Checks length""" if len(data) <= length: return True else: return False
def common(list1, list2): """ This function is passed two lists and returns a new list containing those elements that appear in both of the lists passed in. """ common_list = [] temp_list = list1.copy() temp_list.extend(list2) temp_list = list(set(temp_list)) temp_list.sort() for...
def emptyp(thing): """ EMPTYP thing EMPTY? thing outputs TRUE if the input is the empty word or the empty list, FALSE otherwise. """ return thing == '' or thing == [] or thing == () or thing == {}
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ # Handle non-list input if not isinstance(ints, list): return None, None # Define variables for min and max value and...
def class_name(value): """ Function to get class names. Parameters ---------- value : object Value to check type. Returns ------- str The name of the value type. """ return str(type(value))[8:-2]
def fetch_parameter(kwargs, param): """Fetch a parameter from a keyword-argument dict Specifically for use in enforcing "stricter" typing for functions or methods that use **kwargs to allow for different sets of arguments. """ try: return kwargs.pop(param) except KeyError: raise...
def get_ordered_idx(id_type, id_list, meta_df): """ Gets index values corresponding to ids to subset and orders them. Input: - id_type (str): either "id", "idx" or None - id_list (list): either a list of indexes or id names Output: - a sorted list of indexes to subset a dimension...
def normalize_dict(in_dict): """ normalize the dict in order to easy the usage. 1. all the key is changed to lower case 2. all the value will be prime type, the list will use the first value :param in_dict: raw dict :return: dict converted on 2 rules """ if not in_dict: return ...
def mycipher(mystring:str)->str: """ This function performs an alphabatical cipher # Input: mystring: str, String over which cipher has to be done # Returns: str: Encrypted String # Funcationality: We need to shift each character by 5, if it is on the bottleneck, i...
def getColor(x): """Selects an html color based on 0 <= x <= 100 Parameters ---------- x : float percent of injection to color visually. Higher the percent the darker the color Returns ---------- html color name useful for classifying """ if x >= 75: ret...
def multi_dimensional_fitness(individual): """A simple two-dimensional fitness function.""" return pow(individual[0], 2) + pow(individual[1], 3)
def sanity_check(hdf): """ Minimalistic sanity check for Fast5 files.""" required_paths = ['Analyses', 'UniqueGlobalKey', 'Analyses/EventDetection_000'] try: for p in required_paths: if p not in hdf: return False return True except: return False
def convert_dict_values_to_list(d, separator = ' '): """Given a filepath, load the contents in the format value,key into a dictionary in the format (key:value) Keyword arguments: filepath -- path to text file delimiter - type of delimiter to be used, default value is ',' """ ...
def _float2str(val): """ Return full-precision string rep for `val`. """ # In Python2.7 this is obsoleted by just '%r'. return '%.16g' % val
def easy_unpack(e: tuple) -> tuple: """ returns a tuple with 3 elements - first, third and second to the last """ # your code here return (e[0], e[2], e[-2])
def rotate_right(input, count): """ write a single line of code using what you have learnt in this lesson - slicing and concat assume 0 <= count <= len(input) """ #rotated_content = input[-count:] + input[:len(input)-count] return input[-count:] + input[:-count]
def skip_add(n): """ Takes a number x and returns x + x-2 + x-4 + x-6 + ... + 0. >>> skip_add(5) # 5 + 3 + 1 + 0 9 >>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0 30 """ "*** YOUR CODE HERE ***" if n <= 0: return 0 else: return n + skip_add(n - 2)
def get_parent_dir(directory): """ Gets the parent directory. Param: directory (string) like "GitHub/myProject" """ import os return os.path.dirname(directory)
def generate_func_call(name, args=None, kwargs=None): """ Generates code to call a function. Args: name (str): The function name. args (list[str]): Each positional argument. kwargs (list[tuple]): Each tuple is (arg: str, value: str). If value is None, then the keyword ar...
def DEFAULT_REPORT_SCRUBBER(raw): """Remove breakdown and properties.""" return {k: v for k, v in raw.items() if k not in ("breakdown", "properties")}
def isfloat(value): """ Computes whether `value` can be cast to a float. Args: value (str): Value to check. Returns: bool: Whether `value` can be cast to a float. """ try: float(value) return True except ValueError: return False
def _habits_to_markdown(habits): """Create markdown list of habits""" # FIXME: This is inefficient but not sure of a good way to use join since # we want to add a chacter to the beginning and end of each string in list. markdown = '' for habit, dt_obj in habits: markdown += '- [%02d:%02d] ...
def ensure_array_like(x): """ Ensures that x is an array-like object, or wraps it in a list. :param x: Object that should be a list. :return: x wrapped in a list. """ if hasattr(x, '__iter__') and not isinstance(x, str): return x else: return [x]
def jsdate(d): """formats a python date into a js Date() constructor. """ try: return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day) except AttributeError: return 'undefined'
def get_hex(input_list): """ Convert a list of bytes into hex string """ if input_list is None: return "" o = "" for i in input_list: o += (hex(i)) + " " return o[:-1]
def calculate_chocolates_alt(n, c, m): """ :type n: int :type c: int :type m: int :rtype: int """ result = envelops = n // c while envelops >= m: envelops += 1 - m # Every time i give m chocolates to get a new one result += 1 # Add the new one chocolate return res...
def list_to_tran(list): """ Transform the list of predicted tags to a printable way :param list: list of tags :return: string of transliteration """ transcription = "" for tran in list: if tran[-3:] == "(0)": transcription += tran[:-3] elif tran[-4:] == "(0)-" or ...
def extract_properties(geojson: dict, properties: list) -> dict: """ Extracts specific properties from a complete GeoJSON :param geojson: GeoJSON object :type geojson: dict :param properties: A list of properties to extract :type properties: list :return: The extracted fields as a dict ...
def reverse(s): """ reverse a string and return a new string """ new_s = [] for i in range(len(s)): new_s.append(i) for offset, val in enumerate(s): new_s[len(s)-offset-1] = val new_s = str(new_s) new_s = new_s.replace(", ", "") new_s = new_s.strip("[]") new_s = new_s.re...
def _get_token_char_range(utt_tok): """Get starting and end character positions of each token in utt_tok.""" char_pos = 0 # List of (start_char_pos, end_char_pos) for each token in utt_tok. utt_char_range = [] for tok in utt_tok: start = char_pos end = start + len(tok) - 1 utt_char_range.append((s...
def esOperador(o): """"retorna true si 'o' es un operador""" return o == "+" or o == "-" or o == "/" or o == "*"
def fibonacci(nth_fib): """ (int) -> int where <nth_fib> is a positive integer, Returns the <nth_fib> Fibonacci number """ if isinstance(nth_fib, int): if nth_fib < 0: return 0 elif nth_fib == 1: return 1 else: return fibonacci...
def is_tflite_model(model_path): """Check if a model is of TFLite type Parameters: ---------- model_path: str Path to model Returns ---------- bool: True if given path is a valid TFLite model """ try: with open(model_path, "rb") as f: hdr_bytes ...
def get_reference_value_from_spec(openapi_spec: dict, reference_path: str) -> dict: """Follows the reference path passed in and returns the object at the end of the path Args: openapi_spec (dict): The openapi.json specification object reference_path (str): a path formatted as "#/foo/bar/baz" ...
def wheel(pos): """Generate rainbow colors across 0-255 positions.""" if pos < 85: return list(map(lambda x: x & 255, (pos * 3, 255 - pos * 3, 0))) elif pos < 170: pos -= 85 return list(map(lambda x: x & 255, (255 - pos * 3, 0, pos * 3))) else: pos -= 170 return l...
def findSurefireCommand(output): """ Find where the maven surefire plugin (which is the test plugin) begins its command Parameters ---------- output : list of str The lines of the build output Returns ------- str The line that contains the java command to run the ma...
def keep_header_subject(text, keep_subject=False): """ Given text in "news" format, strip the headers, by removing everything before the first blank line. """ _before, _blankline, after = text.partition('\n\n') sub = [l for l in _before.split("\n") if "Subject:" in l] if keep_subject: ...
def universal_worker(input_pair): """This is a wrapper function expecting a tiplet of function, single argument, dict of keyword arguments. The provided function is called with the appropriate arguments.""" function, arg, kwargs = input_pair return function(arg, **kwargs)
def multi_level_get(the_dict, key, default=None): """ Given the level of nested data contained in some of the results, this function performs an iterative get. :param the_dict: The multi-level dict to get the key from. :param key: The key to look for, with each level separated by '.' :param def...
def index_to_packed(px): """Convert 0x88 index to 0-63 index""" return ((px & ~7) // 2) + (px & 7)
def get_cve_id_from_vuln(vuln): """ Returns CVE ID from vulnerability document When there is no CVE, returns "No-CVE" string """ return vuln.get('cve_id', "No-CVE")
def asymptotic_decay(learning_rate, t, max_iter): """Decay function of the learning process. Parameters ---------- learning_rate : float current learning rate. t : int current iteration. max_iter : int maximum number of iterations for the training. """ return ...
def parseSingleLink(line): """Parse a single link having the format: src dst [weight] line - non-empty line of the input text that starts from a non-space symbol return [src_str, dst_str, weight_str | None], """ line = line.split(None, 3) # Ending comments are not allowed, but required unweighted link might c...
def restrict(var, min, max): """restricts a variable with provide min and max""" if var < min: return min if var > max: return max return var
def QueryEncode(q: dict): """ :param q: :return: """ return "?" + "&".join(["=".join(entry) for entry in q.items()])
def orderPlayers(players=[], startingPlayerPosition=None): """Needs a better name Returns the list of players with Player at startingPlayerPosition on index 0 """ if not isinstance(startingPlayerPosition, int): raise IndexError('startingPlayerPosition must be an integer') ordered = play...
def nro_examiner_name(examiner_name): # -> (str) """returns an examiner name, formated and tuncated to fit in NRO :examiner_name (str): an examiner name, as found in NameX :returns (str): an examiner name that is 7 or less chars in length """ # namex examiner_names are {domain}{/}{username} sta...
def is_pairwise_disjoint(sets): """ This function will determine if a collection of sets is pairwise disjoint. Args: sets (List[set]): A collection of sets """ all_objects = set() for collection in sets: for x in collection: if x in all_objects: retur...
def extract_window_size(config, default=10): """ Extract window size from "window" dictionary value in query configuration. :param config: config :type config: dict :param default: default value if "window" is not found :type default: int :return: window size :rtype: int :raises...
def vapor_flux(air_density, k, q_dif, z_dif): """water vapor flux (kg/(m^2 sec)) between two layers Args: air_density (float or array): air density (kg/m^3) k (float or array): diffusion coef. (m^2/sec) q_dif (float or array): specific hum. diff between layers (kg/kg) z_dif (flo...
def to_nom_val_and_std_dev(interval): """ For a given interval [mu - sigma, mu + sigma] returns (mu, sigma) (Here mu is nominal value and sigma is standard deviation) Parameters ---------- interval: ~list [lwr_bnd, upr_bnd] Returns: ~tuple """ lwr_bnd, upr_bnd = interval sigma...
def page(title, description, element_list=None, tab_list=None): """ Returns a dictionary representing a new page to display elements. This can be thought of as a simple container for displaying multiple types of information. The ``section`` method can be used to create separate tabs. Args: ...
def _preprocess_padding(padding): """Convert keras' padding to theano's padding. # Arguments padding: string, `"same"` or `"valid"`. # Returns a string, `"SAME"` or `"VALID"`. # Raises ValueError: if `padding` is invalid. """ if padding == 'same': th_padding = ...
def get_grams(sentence, n): """ Returns phrases i.e. windowed sub strings with range (1-N) window Keyword arguments: sentence -- utterance (str) n -- max_ngram (int) """ all_grams = [] for l in range(1, n + 1): grams = [" ".join(sentence[i:i + l]) for i in range(len(sentence...
def sanitize(name, replace_with=''): """ Removes some of the reserved characters from the name so it can be saved :param name: Name to be cleaned up :return string containing the cleaned name """ clean_up_list = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|", "\0"] for x in clean_up_list: ...