content
stringlengths
42
6.51k
def tupleCombine(a, b): """Part of partial ordered matching. See http://stackoverflow.com/a/4559604 """ return tuple([i is None and j or i for i, j in zip(a, b)])
def create_url_with_query(api_root: str, query: str): """ Combines the root url with the query string :param api_root: the root url of the twitter api :param query: the query string :return: the url to which the request will be made """ tweet_fields = "tweet.fields=id,author_id,text,created_...
def _path(source, target, parent, path): """ This function finds the path from source to the target according to the parent dictionary. It must be used for shortest_path_faster function. :param source: Float Id of the start node :param target: Float ...
def clean_intent_labels(labels): """Get rid of `None` intents. sklearn metrics do not support them.""" return [l if l is not None else "" for l in labels]
def human_readable(word, does_exist): """Produce a human-readable string to answer the word existence question Parameters ---------- word : str Word to verify does_exist : bool If true, the word exists, otherwise it does not exist Returns ------- str Human-reada...
def _minimize(obj): """Remove lists with only one entry""" if isinstance(obj, list): if len(obj) == 1: return _minimize(obj[0]) else: result = [] for x in obj: y = _minimize(x) if y: result.append(y...
def FixPath(path): """ * Fix too many backslash issue that occurs when reading file paths in json files. Inputs: * path: string to fix. """ if isinstance(path, str): path = path.replace('\\\\', '\\') return path
def _get_command_name(command_raw): """Return command name by splitting up DExTer command contained in command_raw on the first opening paranthesis and further stripping any potential leading or trailing whitespace. """ command_name = command_raw.split('(', 1)[0].rstrip() return command_na...
def find_framework(model_module): """ Find the deep learning framework used from a module - based on items on the module Parameters ----------- model_module - module Module that contains the core model logic Returns ------------ str - with the framework name """ tensor...
def check_split_ratio(split_ratio): """ Checks that the split ratio argument is not malformed and if not transforms it to a tuple of (train_size, valid_size, test_size) and normalizes it if necessary so that all elements sum to 1. (See Dataset.split docs for more info). Parameters --------...
def extractTrustLevelFromResult(result): """Returns True or Folse depending on the result of the JSON parameters in the switchVerifier output The result is trusted if both Firmware and OS are correct and up to data, and both configuration and SDN Rules match in the switch """ if re...
def least_significant_bit_set(mask: int) -> int: """Return the least significant bit set The index is 0-indexed. Returns -1 is no bit is set >>> least_significant_bit_set(0b0000_0001) 0 >>> least_significant_bit_set(0b0001_0000) 4 >>> least_significant_bit_set(0b0000_0000) -1 "...
def str_to_ints(str_arg): """Helper function to convert a list of comma separated strings into integers. Args: str_arg: String containing list of comma-separated ints. For convenience reasons, we allow the user to also pass single integers that a put into a list of length 1 ...
def nint(x): """Round a value to an integer. :param float x: original value :return: rounded integer :rtype: int """ return int(x + 0.5)
def table_name(table, column): """Compute the table name table (string) : the originate table's name column : the column name return : string """ return "{0}__{1}_agg".format(table, column)
def trim_response(response): """ Returns ------- None. """ #trim response response = response[0:response.find("Researcher:")] # stop the response if the model started to create another question response = response[:response.find("\n")] # stop the response after a singl...
def construct_url(url, dataset_path, end_point): """ :return: a url that directs back to the page on LBWIN Data Hub instead of the source page. :param url: host url :param dataset_path: parent path of all datasets :param end_point: name of datasets """ return "/".join([url, dataset_path, en...
def c2st_rfi(acc_prop, acc_base, M_prop, M_base, g): """ Args: acc_prop (float): Proposed model accuracy. acc_base (float): Baseline model accuracy. M_prop (int): Number of parameters for proposed model. M_base (int): Number...
def get_top_matches(matches, top): """Order list of tuples by second value and returns top values. :param list[tuple[str,float]] matches: list of tuples :param int top: top values to return """ sorted_names = sorted(matches, key=lambda x: x[1], reverse=True) return sorted_names[0:top]
def get_positive_axis(axis, ndims, axis_name="axis", ndims_name="ndims"): """Validate an `axis` parameter, and normalize it to be positive. If `ndims` is known (i.e., not `None`), then check that `axis` is in the range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or `axis + ndims` (other...
def is_fp_multiplier(multiplier, modulus): """ Checks if multiplier is a FP multiplier w.r.t. modulus. :param multiplier: an integer in (0, modulus). :param modulus: a prime number. :return: True if multiplier is a FP multiplier w.r.t. modulus. """ period = 1 x = multiplier while x !...
def _public_release_ht_path(data_type: str, version: str) -> str: """ Get public release table path. :param data_type: One of "exomes" or "genomes" :param version: One of the release versions of gnomAD on GRCh38 :return: Path to release Table """ version_prefix = "r" if version.startswith("...
def calcular_comodidad(inicio, fin, rutas, ciudades): """Devuelve el puntaje heuristico de las ciudad pasada por parametro""" try: embotellamientos = (ciudades[inicio].habitantes + ciudades[fin].habitantes) / (rutas[min(inicio,fin)][max(inicio,fin)][0].distancia) felicidad = (0.0 + rutas[min(in...
def factorial_recursion(number: int) -> int: """ >>> factorial_recursion(5) 120 >>> factorial_recursion(0) 1 >>> import random >>> import math >>> numbers = list(range(0, 50)) >>> for num in numbers: ... assert factorial_recursion(num) == math.factorial(num) >>> factorial...
def _quotify(mystr): """ quotifies an html tag attribute value. Assumes then, that any ocurrence of ' or " in the string is escaped if original string was quoted with it. So this function does not altere the original string except for quotation at both ends, and is limited just to guess ...
def asTermVect(doc): """ A simple string to a term vector""" tv = {} terms = doc.lower().split() for term in terms: try: tv[term] += 1 except KeyError: tv[term] = 1 return tv
def new_categories(categories, index): """ Flop around index for '.index' """ if index in categories: categories = categories.copy() categories['.index'] = categories.pop(index) return categories
def has_left_cocomponent_fragment(root, cocomp_index): """ Check whether cocomponent at ``cocomp_index`` has a cocomponent to its left with same ``comp_num``. INPUT: - ``root`` -- the forest to which cocomponent belongs - ``cocomp_index`` -- index at which cocomponent is present in root ...
def normalized_beta_from_beta(beta, N, M): """ input: beta N: total number of values in each input image (pixels times channels) M: number of latent dimensions computes beta_normalized = beta * latent_code_size / image_size given the relationship...
def _jinja2_filter_storage_unit_value(num, suffix='B'): """ Formats storage units into human readable text from http://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) ...
def mov_avg(rates, window=14): """ Returns the moving average with the given window size. rates (iterable): each element is a tick. window (int): each moving average tick is computed as the last <window> ticks including the current tick. """ if len(rates) < windo...
def get_fn_pos_by_rules(pos, token): """ Rules for mapping NLTK part of speech tags into FrameNet tags, based on co-occurrence statistics, since there is not a one-to-one mapping. """ if pos[0] == "v" or pos in ["rp", "ex", "md"]: # Verbs rule_pos = "v" elif pos[0] == "n" or pos in ["$"...
def declaration_path( decl, with_defaults=True ): """ returns a list of parent declarations names @param decl: declaration for which declaration path should be calculated @type decl: L{declaration_t} @return: [names], where first item contains top parent name and last item contains de...
def _create_rest_url(host, version, sid, category, resource, subcategory=None, query_id=None, second_query_id=None, options=None): """Creates the URL for querying the REST service""" # Creating the basic URL url = ('/'.join([host, 'webservices/rest', ...
def is_digit_in_string(input_string): """ check whether digit in string """ return any(ch.isdigit() for ch in input_string)
def _get_precision_type(network_el): """Given a network element from a VRP-REP instance, returns its precision type: floor, ceil, or decimals. If no such precision type is present, returns None. """ if 'decimals' in network_el: return 'decimals' if 'floor' in network_el: return 'flo...
def breed_mlco(outputMLC): """Breeds, i.e., performs selection, crossover (exploitation) and mutation (exploration) on individuals of the MLC output population. It takes an old generation of MLC ouptputs as input and return an evovled generation. """ # return outputMLC return print("breedML...
def setup_ssl_context(config): """ Setup ssl context for connexion/flask app """ if 'httpsEnabled' not in config or not config['httpsEnabled']: context = None elif ('certFile' not in config or config['certFile'] is None or 'keyFile' not in config or config['keyFile'] is None): ...
def print_tree(tree, branch='', print_files=True): """ Utility function to pretty-print a collection of files. """ num_files = 0 tot_file_sz = 0 unk_files = 0 for f,v in tree.items(): if type(v) == dict: n, s, u = print_tree(v, '/'.join([branch, f]), print_files) ...
def _size_pad(width, height): """Performs a padded resize.""" return ("-vf", r"scale=min({height}*(iw/ih)\,{width}):min({width}/(iw/ih)\,{height}),pad={width}:{height}:({width}-iw)/2:({height}-ih)/2".format(width=width, height=height),)
def evensOnly(listOfInts): """ return a new list that has only the even ints from listOfInts """ result = [] for x in listOfInts: if type(x)==int and x % 2 == 0: # check something about x result.append(x) # result = result + [x] return result
def _all_pairs(i, contextsize, arrlen): """ i: index in the array contextsize: size of the context around i arrlen: length of the array Returns iterator for index-tuples near i in a list of size s with context size @contextsize. Context of k around i-th index means all substrings/subarrays...
def merge_sort(A): """ A function that sorts elements of an list """ def merge(L, R, arr): """ This merges the left (L) and right (R) parts of list (arr) in order """ l = r = i = 0 print(len(L), len(R), len(arr)) while l < len(L) and r < len(R): ...
def log_mapping(conf:str): """ Split str of log format into a dict Example : date:application_date,message:application_message is split in : {'date':'application_date','message':'application_message'} """ mapping = dict() for i in conf.split(','): mapping[i.split(':')[0]] = i.split(...
def text_to_int(text): # type (str) -> int """Extracts each digit from a string in sequence, defaults to 0""" try: return int("".join(x for x in text if x.isdigit())) except ValueError: return 0
def check_branch(payload, branch): """ Check if a push was on configured branch. :param payload: Payload from web hook. :param branch: Name of branch to trigger action on. :return: True if push was on configured branch, False otherwise. """ if "ref" in payload: if payload["ref"] == b...
def get_speaker_label(speaker_segments, time_stamp): """ Performs a linear search for the associated speaker for a given time_stamp Helper function for ``chunk_up_transcript()`` :param speaker_segments: List of speaker segments :param time_stamp: The time to search for in the list of speaker segmen...
def get_cd(r_n_metric, os): """ Reference page number: 5 Parameters ------------------------------ r_n_metric: (``float``) Solar radiation in W/m^2 os: (``bool``) Boolean which indicates whether to calculate G for short reference or tall reference Returns ----------------...
def format_data(account): """Takes the account data and returns in a printable format.""" account_name = account["name"] account_desc = account["description"] account_country = account["country"] return f"{account_name}, a {account_desc}, from {account_country}"
def y(r1, x1): """ :param r1: growth rate r :param x1: percentage of the maximum (expressed in decimals) x :return: xn+1 """ return r1*x1*(1-x1)
def list_of_dicts(specialty_dict_iter): """ Some library methods yield an OrderedDict or defaultdict, and it's easier to confirm their contents using a regular dict. This function turns an iterable of specialty dicts into a list of normal dicts. Args: specialty_dict_iter: Returns: ...
def is_valid_field_content(s: str) -> bool: """ Returns True if string s can be stored in a SubStation field. Fields are written in CSV-like manner, thus commas and/or newlines are not acceptable in the string. """ return "\n" not in s and "," not in s
def split_header(diff): """Splits a diff in two: the header and the chunks.""" header = [] chunks = diff.splitlines(True) while chunks: if chunks[0].startswith('--- '): break header.append(chunks.pop(0)) else: # Some diff may not have a ---/+++ set like a git rename with no change or # a...
def is_title(s): """Return True if a single token string s is title cased. is_title(s) treats strings containing hyphens and/or slashes differently than s.istitle() does: is_title("Hyphened-word") returns True; "Hyphened-word".istitle() returns False is_title("Hyphened-Word") returns False; "Hy...
def tenure_flag_str(name,faculty_list): """ Generate flag for newly-assigned committee member. Arguments: name (str): Faculty name faculty_list (list of str): T&TT faculty list entry Returns: (str): flag string """ return "@" if (name in faculty_list) else ""
def pie_perc(n): """precondition: n > 0 Assuming n people want to eat a pie, return the percentage each person gets to eat.""" return int(100 / n)
def parse(puzzle_input): """Parse input""" return [int(line) for line in puzzle_input.split(',')]
def key_check(iterable): """Check and return single list result.""" if len(iterable) != 1: raise ValueError("Multiple description keys found!") else: return iterable[0]
def getRow(rowIndex): """ :type rowIndex: int :rtype: List[int] """ row = [1] for _ in range(rowIndex): row = [x + y for x, y in zip([0]+row, row+[0])] return row
def fibonacci_tabulation(n): """DP implementation of fibonacci. O(n) runtime, O(n) space""" d = [0] * (n + 1) d[1] = 1 d[2] = 1 for i in range(3, n + 1): d[i] = d[i - 1] + d[i - 2] return d[n]
def _convert_to_str_dtype(column_types, known_string_cols): """Sometimes the deteremined dtype is incorrect based off the first 100 rows, update the incorrect dtypes. """ for str_col in known_string_cols: if column_types.get(str_col): column_types[str_col] = 'object' return colum...
def square_me(number): """ Takes numerical input and returns its square """ square = number**2 return square
def compute_padding(w, n_align=64): """compute required padding for given dimension to naturally align""" if w % n_align > 0: new_w = ((w // n_align) + 1) * n_align else: new_w = w pad = new_w - w pad_l = pad // 2 pad_r = pad - pad_l return new_w, pad_l, pad_r
def count_entries(l): """Count number of last non blank/zero entries in list l""" count = len(l) c = count if type(l[0])==int: # integers for j in range(c-1,0,-1): if (l[j]==0): count -= 1 else: break count = max(4,count) # At ...
def maximum_element_size_for_length(length): """ Returns the maximum element size representable in a given number of bytes. :arg length: the limit on the length of the encoded representation in bytes :type length: int :returns: the maximum element size representable :rtype: int """ return (2**(7*length)...
def extract_array(line): """ Return the array on the RHS of the line >>> extract_array("toto = ['one', 'two']\n") ['one', 'two'] >>> extract_array('toto = ["one", 0.2]\n') ['one', 0.2] """ # Recover RHS of the equal sign, and remove surrounding spaces rhs = line.split('=')[-1].stri...
def subsequent_roll_result(sum_dice, point_value): """ rotate again and again to compare the total number of dice If the sum is equal to the first value Return to the point If the sum is equal to 7 Return loss Otherwise, Return to neither Returns: The boolean value (bool...
def fib_n(n): """Efficient way to compute Fibonacci's numbers. Complexity = O(n)""" fibs = [0, 1] # we don't need to store all along the way, but the memory is still as good as in the naive alg for i in range(2, n + 1): fibs.append(fibs[-2] + fibs[-1]) print(fibs[-1]) return fibs[-1]
def step_abs(window, *args, **kwargs): """ Sum of all absolute changes within window :param window: :param args: :param kwargs: :return: """ values = [x[1] for x in window] return sum(abs(x1 - x0) for x0, x1 in zip(values, values[1:]))
def _convert_motion_units(data_pxts, kmperpixel=1.0, timestep=1.0): """Convert atmospheric motion vectors from pixel/timestep units to m/s. Input: data_pxts -- motion vectors in "pixels per timestep" units kmperpixel -- kilometers in pixel timestep -- timestep lenght in minutes Out...
def define_treatment_wells(exclude_outer=1, plate_dims=[16, 24]): """Defines set of inner wells to be used for treatments Parameters ---------- exclude_outer : int defines outer well columns and rows to to exclude plate_dims : list of int Returns ------- tr_wells, list(set(e...
def list_numbers(line): """ Takes a list of integers and removes all zero elements. """ numbers = [] for item in line: if item > 0: numbers.append(item) return numbers
def extract_full_names(people): """Return list of names, extracting from first+last keys in people dicts. - people: list of dictionaries, each with 'first' and 'last' keys for first and last names Returns list of space-separated first and last names. >>> names = [ ... {'...
def findFunc(point1, point2): """find the linear function that fits two points""" m = ((point2[1] - point1[1]) / (point2[0] - point1[0])) b = (((point2[0] * point1[1]) - (point1[0] * point2[1])) / (point2[0] - point1 [0])) return m, b
def find_pos(pos, lst): """Binary search to find insertion point for pos in lst.""" h = 0 t = len(lst) - 1 mid = int((h + t) / 2) ans = -1 while not h > t: if pos >= lst[mid]: ans = mid h = mid + 1 else: t = mid - 1 mid = int((h + t) / 2) return ans
def siqs_choose_nf_m(d): """Choose parameters nf (sieve of factor base) and m (for sieving in [-m,m]. """ # Using similar parameters as msieve-1.52 if d <= 34: return 200, 272 if d <= 36: return 300, 546 if d <= 38: return 400, 1094 if d <= 40: return 500,...
def is_legal(arg: str): """ check if string has illegal word >>> is_legal('ab12123') """ illegal_signal = '~|' for ch in arg: if ch in illegal_signal: return False return True
def fib(num): """ Recursively finds the nth number in the Fibonnacci sequence 1, 1, 2, 3, 5, 8 @param {number} num @return {number} """ if num <= 2: return 1 return fib(num - 1) + fib(num - 2)
def struct_size(elems): """ Computes the total size of a given struct assuming base-2 alignment. elems -- Ordered list of struct member sizes. Returns Total size of struct. """ print("---------") # Assume 8 is size of 'most-aligned' data type (e. g. double). align_values = {2, 4, 8} member_...
def token_parse(obj: str) -> str: """Pass.""" url_check = "token=" if url_check in obj: idx = obj.index(url_check) + len(url_check) obj = obj[idx:] return obj
def validObject(object_): """Check if the data passed in POST is of valid format or not.""" if "@type" in object_: return True return False
def getDctSymbols(dct, symbols=None, excludes=None): """ Lists the free symbols present in each expression in the dictionary. Parameters ---------- dct: dict key: Symbol value: Expression excludes: list-symbol symbols: list-Symbol ...
def _get_gmx_energy_torsion(gmx_energies): """Canonicalize torsion energies from a set of GROMACS energies.""" gmx_torsion = 0.0 for key in ["Torsion", "Ryckaert-Bell.", "Proper Dih."]: try: gmx_torsion += gmx_energies[key] except KeyError: pass return gmx_torsio...
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ windowStart = 0 unique_chars = {} longest_len = 0 for windowEnd in range(len(s)): rightMostChar = s[windowEnd] if rightMostChar not in unique_chars: unique_chars[rightMostChar] = 0 uni...
def split_strings(s): """ Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). :param s: a string input. :return: the string ...
def has_repeating_letter(text): """Check if a string has a repeating letter with one letter in between""" # Check every combination of three letters # and see if the first and third are the same. # If there is any such combination, return True, False otherwise. for i in range(len(text) - 2): ...
def rosenbrock(X, params): """ The Rosenbrock function. The function computed is:: f(x,y) = (a - x)^2 + b(y - x^2)^2 """ _x, _y = X return (params[0] - _x) ** 2 + params[1] * (_y - _x ** 2) ** 2
def _earlygetopt(aliases, args): """Return list of values for an option (or aliases). The values are listed in the order they appear in args. The options and values are removed from args. """ try: argcount = args.index("--") except ValueError: argcount = len(args) shortopts ...
def convert_title_to_snake_case(key): """Converts title-cased key to snake-cased key.""" return '_'.join(w.lower() for w in key.split(' '))
def _GetDisplayRange(old_end, rows): """Get the revision range using a_display_rev, if applicable. Args: old_end: the x_value from the change_point rows: List of Row entities in asscending order by revision. Returns: A end_rev, start_rev tuple with the correct revision. """ start_rev = end_rev =...
def remove_multiple_spaces_from_string(string): """ In the provided ``string`` replaced all instances of multiple spaces with only a single space. Additionally strips the string before removing the spaces. :param string: String to remove spaces from :type string: str :return: String in whi...
def rubygems_api_url(name, version=None, repo='https://rubygems.org/api'): """ Return a package API data URL given a name, an optional version and a base repo API URL. For instance: https://rubygems.org/api/v2/rubygems/action_tracker/versions/1.0.2.json If no version, we return: https://ru...
def delete_none(_dict): """ Deletes dict keys if their value is None. """ for key, value in list(_dict.items()): if isinstance(value, dict): delete_none(value) elif value is None: del _dict[key] elif isinstance(value, list): for v_i in value: ...
def sort_stack(stack): """ Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty """ # O(n^2) time, O(n) space sta...
def range_minmax(ranges): """ Returns the span of a collection of ranges where start is the smallest of all starts, and end is the largest of all ends. >>> ranges = [(30, 45), (40, 50), (10, 100)] >>> range_minmax(ranges) (10, 100) """ rmin = min(ranges)[0] rmax = max(ranges, key=la...
def validateFilename(value): """ Validate filename with list of points. """ if 0 == len(value): raise ValueError("Filename for list of points not specified.") return value
def contiguous(zone, pair): """ Tries to merge `zone` and `pair` if the vehicles in them lie on conitguous indices """ zv1, zv2 = zone["self"], zone["other"] pv1, pv2 = pair["self"][0], pair["other"][0] if (pv1 < zv1[0]) or (zv1[-1] < pv1): if pv1 == (zv1[0] - 1): zv1 = [pv1] + zv1 elif pv1...
def connected_components(leaf_to_root): """Returns the number of roots in onotology Params: leaf_to_root, Dict[str, str] leaf_string -> root_string Outputs: num_roots, int """ num_roots = 0 for l, r in leaf_to_root.items(): if r is None: num_roots += 1 ret...
def obj_box_coord_upleft_butright_to_centroid(coord): """Convert one coordinate [x1, y1, x2, y2] to [x_center, y_center, w, h]. It is the reverse process of ``obj_box_coord_centroid_to_upleft_butright``. Parameters ------------ coord : list of 4 int/float One coordinate. Returns --...
def make_readable(seconds: int) -> str: """ Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS) HH = hours, padded to 2 digits, range: 00 - 99 MM = minutes, padded to 2 digits, range: 00 - 59 SS = seconds, padded to 2 digits...