content
stringlengths
42
6.51k
def CheckLowerLimitWithNormalization(value, lowerLimit, normalization=1, slack=1.e-3): """Lower limit check with slack. Check if value is no less than lowerLimit with slack. Args: value (float): Number to be checked. lowerLimit (float): Lower limit. normalization (float): normalizat...
def untabify(text, width): """Replace tabs with spaces in text.""" def next_stop(p): return width * ((p + width) // width) def pad(p): return ' ' * (next_stop(p) - p) out = list(text) pos = 0 for cur, c in enumerate(out): if c == '\t': out[cur] = pad(pos) ...
def group_consecutives(vals, step=1): """Return list of consecutive lists of numbers from vals (number list).""" run = [] result = [run] expect = None for v in vals: if (v == expect) or (expect is None): run.append(v) else: run = [v] result.append(...
def rain(walls): """ walls is a list of non-negative integers. Return: Integer indicating total amount of rainwater retained. Assume that the ends of the list (before index 0 and after index walls[-1]) are not walls, meaning they will not retain water. If the list is empty return 0. """ ...
def totient(p, q): """Compute totient of p and q.""" return ((p - 1) * (q - 1))
def rep(x, N): """ Returns a range with repeated elements. """ return [item for item in x for _ in range(N)]
def pickmiddlerun(files): """Selects the middle run Defined as the floor of the number of runs divided by two. Parameters ---------- files : list of filenames Returns ------- file : returns the filename corresponding to the middle run """ if isinstance(files, list): re...
def strip_empty_leading_and_trailing_lines(s): """ Removes all empty leading and trailing lines in the multi-line string `s`. """ lines = s.split('\n') while lines and not lines[0].strip(): del lines[0] while lines and not lines[-1].strip(): del lines[-1] return '\n'.join(lines)
def filter_dict_nulls(mapping: dict) -> dict: """Return a new dict instance whose values are not None.""" return {k: v for k, v in mapping.items() if v is not None}
def guess_multichannel(shape): """Guesses if an image is multichannel based on its shape. """ first_dims = shape[:-1] last_dim = shape[-1] average = sum(first_dims) / len(first_dims) if average * .95 - 1 <= last_dim <= average * 1.05 + 1: # roughly all dims are the same return ...
def get_dis_factor(base_price): """Gets discount factor based on price""" if base_price > 1000: return 0.95 return 0.98
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) True >>> che...
def filter_onlyCheapest(itineraries, count=1): """ filter the input itineraries and select the cheapest one :param itineraries: input itineraries :param count: number of itineraries needed to get after filtering :return: cheapest itineraries :rtype: list """ itineraries.sort(key=lambda ...
def patch_uri(uri): """If a custom uri schema is used with python 2.6 (e.g. amqps), it will ignore some of the parsing logic. As a work-around for this we change the amqp/amqps schema internally to use http/https. :param str uri: AMQP Connection string :rtype: str """ index = u...
def is_prime(n: int): """ Primality test from https://stackoverflow.com/questions/15285534/ """ if n == 2 or n == 3: return True if n < 2 or n % 2 == 0: return False if n < 9: return True if n % 3 == 0: return False r = int(n ** 0.5) f = 5 whil...
def _filter(data, start_date=None, end_date=None): """Only return data with dates between start_date and end_date""" temp_data = [] if start_date: for row in data: if "date" in row and row["date"] >= start_date: temp_data.append(row) data = temp_data temp_dat...
def get_check_function(check): """Return check function corresponding to check.""" return { '>': int.__gt__, '<': int.__lt__, '>=': int.__ge__, '==': int.__eq__, '<=': int.__le__, '!=': int.__ne__, }[check]
def deep_update(source, updates): """Deeply updates a dictionary Iterates through a dictionary recursively to update individual values within a possibly nested dictionary of dictionaries Args: source: source dictionary updates: updates to the dictionary Returns: source: up...
def ctd_sbe37im_tempwat(t0): """ Description: OOI Level 1 Water Temperature data product, which is calculated using data from the Sea-Bird Electronics conductivity, temperature and depth (CTD) family of instruments. This data product is derived from SBE 37IM instruments and app...
def shorten_hash(original_hash: int) -> int: """ This function removes final bytes from a hash to get a hash that can be parsed in java as an int :param original_hash: the original hash of an object. This should have 36 bytes. :return: A in int parsed from the first 32 bytes of the original hash """...
def split_email(s, h): """Given a sender email s and a HELO domain h, create a valid tuple (l, d) local-part and domain-part. Examples: >>> split_email('', 'wayforward.net') ('postmaster', 'wayforward.net') >>> split_email('foo.com', 'wayforward.net') ('postmaster', 'foo.com') >>> spl...
def _is_encodable(value: str) -> bool: """ We need to filter out environment variables that can't be unicode-encoded to avoid a "surrogates not allowed" error in jsonnet. """ # Idiomatically you'd like to not check the != b"" # but mypy doesn't like that. return (value == "") or (value.e...
def get_header(value): """ Gets the header for a piece of content by: #. Attempting to split the content on variations of the `<!--more-->` tag. #. Attempting to split the content on the first paragraph similar to the method in :func:`mezzanine.models.MetaData.description_from_content`. #. ...
def is_feat_in_sentence(sentence, features): """ Parameters ---------- sentence: str, One sentence from the info text of a mushroom species features: list of strs List of possible features as in dataset_categories.features_list Return ------ bool, True if sentenc...
def sort_words_case_insensitively(words): """Sort the provided word list ignoring case, and numbers last (1995, 19ab = numbers / Happy, happy4you = strings, hence for numbers you only need to check the first char of the word) """ # sorted_words = sorted(words, key=str.lower) # new_list = ...
def init_lun_parameters(name, parameters): """Initialize basic LUN parameters.""" lunparam = {"TYPE": "11", "NAME": name, "PARENTTYPE": "216", "PARENTID": parameters['pool_id'], "DESCRIPTION": parameters['volume_description'], "ALLO...
def BinarySearch(start, end, test): """Binary search integers using test function to guide the process.""" while start < end: mid = (start + end) // 2 if test(mid): start = mid + 1 else: end = mid return start
def get_in(obj, keys, default=None): """ >>> get_in({'a': {'b': 1}}, 'a.b') 1 """ if isinstance(keys, str): keys = keys.split('.') for key in keys: if not obj or key not in obj: return default obj = obj[key] return obj
def purge_sparse_entry(n): """Return the standard form of the sparse index n. Return zero if the sparse index n is illegel. This is is a slow python function. The fast C functions purge sparse indices internally, whenever this is needed. """ tag = n >> 25 if 1 <= tag <= 3: # Tags A, B, C...
def listeq(L1, L2): """Return True if L1.sort() == L2.sort() Also support iterators. """ return sorted(L1) == sorted(L2)
def fib(n): """ Inputs a number, Returns None if number is negative Otherwise return final fibinachi number in sequence Must use recursion """ #If n is less than or equal to 0, return an error. if n < 0: return None #If n is equal to 0, return 0. if n == 0: re...
def clean_title(title: str) -> str: """ Cleans a str such that it is appropriate to act as a Wikipedia title """ title = title.replace(" ", "%20") title = title.replace("&", "%26") title = title.replace("?", "%3F") return title
def _fn_order(n): """File name order - integers at start of file name, but ignore nonnumerics""" try: return int(n) except (ValueError, TypeError): return 0
def binary_search(arr, item): """ This searches by repeatedly splitting an array in two and searches each side. """ first = 0 last = len(arr) - 1 while first<= last: midpoint = (first + last)//2 if arr[midpoint] == item: return True elif item < arr[midpoin...
def remove( remove_nodes, node_list=None, node_dict=None, edge_list=None, edge_dict=None): """remove specified nodes""" if node_list: return [ node_id for node_id in node_list if node_id not in remove_nodes] elif node_dict: return { node_id: value ...
def timestamp_to_seconds(timestamp): """ seconds since midnight derived from timestamp hh:mm:ss """ h = int(timestamp[0:2]) m = int(timestamp[3:5]) s = int(timestamp[6:8]) seconds = 60 ** 2 * h + 60 * m + s return seconds
def insert_snippet(seq, snippet, idx): """ idx: 0 <= idx <= len(seq)] """ split1 = seq[:idx] split2 = seq[idx:] return split1 + snippet + split2
def first_letter(name): """A simple name compression that returns the first letter of the name. Args: name (str): A forename, surname, or other name. Returns: (str): The upper case of the first letter of the name """ return name[0].upper() if name else ''
def tuple_to_string(input): """ convert tuple to string :param input: :return: """ if input: test_string = "" for i in input: test_string += i + " " return test_string.lower().strip()
def avg_mutation_rate(alignment :list): """ Counts number of POLYMORPHIC sites on an alignment. -> no distinction on whether mutation carried by 1 or several sequences Used to estimate the age of the most recent common ancester. Parameters: alignment (list): !should be a compatible ...
def output_notebook(name: str, input: str) -> str: """Generate name for output notebook. If an output name is given it is returned as it is. Otherwise, the name of the input notebook will have the suffix ``.ipynb`` replaced by ``.out.ipynb``. If the input notebook does not have a suffix ``.ipynb`` the ...
def solution(value): # O(1) """ Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 ...
def text_tostring(t, default=None, emphasis='emphasis', strong='strong', sup='sup', fn_anc='fn_anc', fn_sym='fn_sym'): """Convert Text object to str. Mark all styled text with special characters and return str Example: >>> t = [('Unmarked text. ', None), ('Text marked "emphasis".', ...
def generate_lr_map(params, lr_config, default): """ generate a layerwise learning map. to change the values of the learning rate at different epochs eg: learning rate decay use a tensor.shared object. To set the value of the variable use tensor.shared.set_value() to set the value of the variable ...
def strings_AND_bitwise(string1, string2): """Returns the bitwise AND of two equal length bit strings. Parameters ---------- string1 : str First string string2 : str Second string Returns ------- string_out : str bitwise AND of the two input strings ...
def header_decoder(header_str: str): """This function is used to decode the bearer header token. """ if type(header_str) != str: raise ValueError(f"The header is not str (Got {type(header_str)})") splitted_header = header_str.split(" ") if len(splitted_header) != 2: raise ValueEr...
def build_request_url(method, output_format='tsv'): """Create url to query the string database Allows us to create stubs for querying the string api with various methods Parameters ---------- method: str options - get_string_ids, network, interaction_partners, homology, homology_best, ...
def _must_be_true(values): """Root validator to be added to ExampleModel.""" assert values.get("field_a") return values
def removeN(svgfile): """ Removes the final character from every line, this is always /n, aka newline character. """ for count in range(0, len(svgfile)): svgfile[count] = svgfile[count][0: (len(svgfile[count]))-1] return svgfile
def add_slash(path): """Add slash to the path if it's not there.""" if path.endswith('/'): return path return path + '/'
def decode(proto_str): """Decodes a proto string.""" return proto_str.decode("utf-8")
def _geojson_properties2karta(properties, n): """ Takes a dictionary (derived from a GeoJSON properties object) and divides it into singleton properties and *n*-degree data. """ props = {} data = {} for (key, value) in properties.items(): if isinstance(value, list) or isinstance(value, tuple...
def reformat_to_coco(predictions, ground_truths, ids=None): """Reformat annotation lists to the COCO format. :param predictions: List of predicted captions. :type predictions: list :param ground_truths: List of lists of reference captions. :type ground_truths: list :param ids: List of fi...
def paire_impair(a): """ test parity, return True/False """ if (a % 2): # rest is != 0 return False else: # rest i 0 return True
def sortDictionaryListByKey(dictList, key, reverse=False): """ _sortDictionaryListByKey_ Given a list of dictionaries and a key with a numerical value, sort that dictionary in order of that key's value. NOTE: If the key does not exist, this will not raise an exception This is because this is u...
def is_base(gpu, node_rank): """ Whether the current process is the base process. Args: gpu (int): local rank of the current gpu node_rank (int): rank of the node Returns: bool """ return gpu == 0 and node_rank == 0
def vlv_to_int(vlv: bytes) -> int: """Calculate integer from variable-length time""" output = 0 mask = 127 # 01111111 for count, byte in enumerate(vlv[::-1]): b = mask & byte # remove first bit c = b << (count*7) # move to correct position in 'bit string' output |= c ...
def _ion(v): """if v is not return int(v) else return None""" return int(v) if v is not None and v != '' else None
def get_url (schema): """ Get model url from a schema """ if schema.get("encoder") != None: return schema["encoder"] else: return None
def determine_longest_matched_line(results): """Results is a list of tuples: (match_list1, 'filename1.py', longest_line_in_match)""" if len(results) == 1: return results[0][2] return max(results, key=lambda x: x[2])[2]
def _linear_extrapolate(x0, y0, x1, y1, x_new): """Linearly extrapolate the value at x_new from 2 given points (x0, y0) and (x1, y1).""" return y0 + ((x_new - x0) / (x1 - x0)) * (y1 - y0)
def get_feature_names(num_features): """ Args: num_features: The number of feature names to create Returns: feature_names: A list of feature names """ feature_names = [] for i in range(num_features): feature_names.append('feature' + str(i + 1)) return feature_names
def prepend_q(pass_params): """ Add ? to parameters if needed """ if len(pass_params) > 0: if pass_params.startswith('?'): pass else: pass_params = '?' + pass_params return pass_params
def slice_fraction(sequence, i, n): """ Split a sequence in `n` slices and then return the i-th (1-indexed). The last slice will be longer if the sequence can't be splitted even-sized or n is greater than the sequence's size. """ total = len(sequence) per_slice = total // n if not per_...
def sanitize_strings(txt): """ Removes newlines from a piece of text :param txt: a string. :return: a string without new lines. """ if not txt: return "" if len(txt) > 0: return "".join(txt.splitlines()) else: return ""
def gold_build_config(args): """ Extracts key value pairs from the arguments handed to 'gn gen' and returns them as a dictionary. Since these are used as parameters in Gold we strip common prefixes and disregard some arguments. i.e. 'use_goma' since we don't care about how a binary was built. ...
def seconds_to_game_time(seconds,option): """Intake aggregate seconds and convert to game minute / second""" if option == "string": return '{}\'{}\"'.format(*divmod(seconds, 60)) elif option == "float": return float(seconds)/60 else: raise Exception("%s is not an appropriate conversion option" % (option))
def xml_escape(string): """Replaces all unescaped xml characters""" return string.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&apos;')
def lovelace_to_ada(lovelace_value: float) -> float: """Take a value in lovelace and return it in ADA.""" constant = 1e6 return lovelace_value / constant
def char2hex(a: str) -> int: """Convert a hex character to its integer value. '0' becomes 0, '9' becomes 9 'A' becomes 10, 'F' becomes 15 'a' becomes 10, 'f' becomes 15 Returns -1 on error. """ if "0" <= a <= "9": return ord(a) - 48 elif "A" <= a <= "F": return ord(a) ...
def format_time_delta(s): """ Formats seconds to a better representation of delta time """ hours, remainder = divmod(s, 3600) minutes, seconds = divmod(remainder, 60) ht = '{}h'.format(hours) if hours else '' mt = '{}m'.format(minutes) if minutes else '' st = '{}s'.format(seconds) if seconds el...
def EdgesSetCreate(TrajectoryEdges): """Take the set of all duplicate points in trajectory object.""" listOfEdges = [] for edgesList in TrajectoryEdges: for edge in edgesList: listOfEdges.append(edge) setOfEdges = list(set(listOfEdges)) return setOfEdges, listOfEdges
def title_case(sentence): """ Convert string to title case. Title case means that the first character of every word is capitalized, otherwise lowercase. Parameters -------------- sentence: string Sentence to be converted to title case Returns: -------------- ret: string ...
def _get_heuristic_col_headers(adjusted_table, row_index, col_index): """Heuristic to find column headers.""" adjusted_cell = adjusted_table[row_index][col_index] adjusted_col_start = adjusted_cell["adjusted_col_start"] adjusted_col_end = adjusted_cell["adjusted_col_end"] col_headers = [] for r ...
def deserialize_bool(data_type, data, model_finder): """Deserializes data into a boolean object. :param data_type: class literal for deserialized object, or string of class name :param data: data to be parsed :param model_finder: ModelFinder instance to find class for data_type class literal :retu...
def axis_for_letter(letter): """Returns 0, 1 or 2 for 'K', 'J', or 'I'; as required for axis arguments in FineCoarse methods.""" assert isinstance(letter, str) and len(letter) == 1 u = letter.upper() return 'KJI'.index(u)
def calculate_centroid(coords): """[summary] Args: coords ([type]): [description] Returns: [type]: [description] """ lons = [] lats = [] for c in coords: lons.append(float(c[0])) lats.append(float(c[1])) return [sum(lons)/len(lons), sum(lats)/len(lats)...
def last_element(lst): """Return last item in list (None if list is empty. >>> last_element([1, 2, 3]) 3 >>> last_element([]) is None True """ if len(lst) != 0: return lst[-1] return None
def isDomainAdmin(user, domain): """ User is admin of the domain or higher. Return: {bool} """ try: if domain: hasAccess = user in domain.admins.all() or domain.lead == user or user.hasAdminAccess() else: hasAccess = user.hasAdminAccess() except: hasAccess = False return hasAccess
def rescale(data, total=1): """ Rescales numerical values in lists or dictionary values to sum to specified total. Usage ***** rescale([1, 3]) -> [0.25 0.75] rescale({'a': 1, 'b':'9']) -> {'a': 0.1, 'b': 0.9} """ if isinstance(data, list): input_total = sum(data) as...
def _filter_statements(statements, agents): """Return INDRA Statements which have Agents in the given list. Only statements are returned in which all appearing Agents as in the agents list. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements t...
def decode(value): """Decode utf-8 value to string. Args: value: String to decode Returns: result: decoded value """ # Initialize key variables result = value # Start decode if value is not None: if isinstance(value, bytes) is True: result = value....
def isgreater(angle, X, dx): """isgreater function. Is angle greater than X?""" try: if float(angle) > X: return True else: return False except ValueError: return False
def merge_deps(old, new): """ Merge two dependency lists. The lists are partially ordered, with all dependents coming after the items they depend on, but otherwise order doesn't matter. The merged list preserves the partial ordering. So if old and new both include the item "c", then all items that...
def _process(line, separator): """Processes a text line and handles malformed formats.""" if line.startswith(separator): line = "null" + line s = separator + separator while s in line: line = line.replace(s, separator + "null" + separator) if line.endswith(separator): line ...
def get_ioh(bb1, bb2): """ Calculate the Intersection over motorcyclist bbox (IoH) of given helmet bounding box. Parameters ---------- bb1 : Helmet Bounding Box List List Idx : {0 -'x1', 2 - 'x2', 1 - 'y1', 3- 'y2'} The (x1, y1) position is at the top left corner, t...
def version_lower_than(gaphor_version, version): """Only major and minor versions are checked. >>> version_lower_than("0.3.0", (0, 15, 0)) True """ parts = gaphor_version.split(".") return tuple(map(int, parts[:2])) < version[:2]
def freq(wordlist): """ Function to calculate word frequency from a list of words. It returns the list of words together with frequencies. """ # Create empty 'result list' result = [] # break the string into list of words new_string = [] # loop over words present in...
def get_list_of_multiple_or_one_or_empty_from_dict(input, name, vtype=None): """ Extracts objects by 'name' from the 'input' and returns as a list. Tries both plural and singular names from the input. If vtype is specified, tries to convert each of the elements in the result to this type. :param in...
def transform_package_responses(data, submission_id, long_field_names_map): """ Funtion to format flow results package data to flattened JSON for each submission and return a list of dictionaries. """ transformed_data = {"submission_uuid": submission_id} for i in data: transformed_data[...
def filter_protections(candidates): """Return only non-protected pages""" non_protected_candidates = {} for c in candidates: if 'protection' not in candidates[c]: print("Missing protection info:", candidates[c]) continue if not candidates[c]['protection']: ...
def rootsearch(f, a, b, dx): """ x1,x2 = rootsearch(f,a,b,dx). Searches the interval (a,b) in increments dx for the bounds (x1,x2) of the smallest root of f(x). Returns x1 = x2 = None if no roots were detected. """ x1 = a f1 = f(a) x2 = a + dx f2 = f(x2) # while f1*f2 > 0.0: ...
def correct_mag(m0, X, k): """Correct magnitude for airmass and extinction. Parameters ---------- m0 : float Apparent magnitude. X : float Airmass. k : float Extinction coefficient. Returns ------- m : float The corrected apparent magnitude. """...
def point_line_distance(P, A, B): """ Given points P, A, and B in R^2, find the distance between P and the line through A and B. """ #If the line through A and B is defined by ax + by + c = 0, #then the distance is given by |a*Px + b*Py + c|/sqrt(a^2 + b^2) dy = B[1] - A[1] dx ...
def seconds_to_timestamp(seconds): """ timestamp hh:mm:ss derived from seconds since midnight """ h = int(seconds / 60 ** 2) seconds = seconds - 60 ** 2 * h m = int(seconds / 60) seconds = seconds - 60 * m s = int(seconds) timestamp = "{0:2d}:{1:2d}:{2:2d}".format(h, m, s) timest...
def PC_S_calc(classes): """ Calculate Percent chance agreement for Bennett-et-al.'s-S-score. :param classes: confusion matrix classes :type classes: list :return: percent chance agreement as float """ try: return 1 / (len(classes)) except Exception: return "None"
def convert_qa_input_dict(infer_dict): """ Input dictionaries in QA can either have ["context", "qas"] (internal format) as keys or ["text", "questions"] (api format). This function converts the latter into the former. It also converts the is_impossible field to answer_type so that NQ and SQuAD dicts have t...
def convertArgsToStrings(*args) -> str: """converts list of args to a concatenated string for file naming""" if args: fileName: str = "" for i, arg in enumerate(args): # convert to string arg = str(arg) #arg = str(arg) if i != len(args)-1: ...
def _get_field_names(field: str, aliases: dict): """ Override this method to customize how :param field: :param aliases: :return: """ trimmed = field.lstrip("-") alias = aliases.get(trimmed, trimmed) return alias.split(",")
def _find_and_replace_fields_arcade(text, field_mapping): """Perform a find and replace for field names in an arcade expression. Keyword arguments: text - The arcade expression to search and replace fields names field_mapping - A dictionary containing the pairs of original field names and new field nam...