content
stringlengths
42
6.51k
def relEqual(x, y, tol = 2**-26): """ Simple test for relative equality of floating point within tolerance Default tolerance is sqrt double epsilon i.e. about 7.5 significant figures """ if y == 0: return x == 0 return abs(float(x) / float(y) - 1.) < tol
def check_doc_id(txt): """ Quickly checks if a document_id is likely to be valid. Return True / False depending on result """ if len(txt) == 45 and txt[12] == '-' and all(letter in ['a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9','-'] for letter in txt): return True else: ret...
def printed(o, **kwargs): """Print an object and return it""" return print(o, **kwargs) or o
def _iter_len(iterator): """Return length of an iterator""" return sum(1 for _ in iterator)
def shunt(infix): # Doc string - string inside class/ function """Shunt function -> returnes the infix regular expression to postfix """ infix = list(infix)[::-1] # Operator stack opers = [] # Postfix regular expression postfix = [] # Operator precidence * - . - | pr...
def normalizeDanceName(str): """ Normalizes dance name """ if ("v. waltz" in str.lower() or "viennese waltz" in str.lower()): return "V. Waltz" if ("paso doble" in str.lower()): return "Paso Doble" if ("cha cha" in str.lower()): return "Cha Cha" tokens = s...
def word_to_col(w): """Splits a hexadecimal string to a bytes column. Parameters ---------- w : str Hexadecimal 32-bit word. Returns ------- list 4 bytes column containing integers representing the input string. """ x = int(w, 16) return [x >> 24, (x >> 16) & 0...
def find_best_row(m): """ This function finds the list | row that has more 0 in the matrix to make less calculus in the adjuct method. @params: m => a matrix to find best row @return: res[0] => the number of the best row Alejandro AS """ res ...
def right_replace(string, old, new, occurrence): """ Take <string> and replace <old> substring with <new> substring <occurrence>-times, starting from the most right one match. :param string: string which we are changing :param old: substring which will be replaced :param new: substring which wil...
def unpack_string_from(data, offset=0): """Unpacks a zero terminated string from the given offset in the data""" result = "" while data[offset] != 0: result += chr(data[offset]) offset += 1 return result
def is_ethiopia_dataset(name): """Names with 'TR' at start or Ethiopia""" return name.upper().startswith('TR') or \ name.lower().find('ethiopia') > -1
def COND(_if, _then, _else): """ Evaluates a boolean expression to return one of the two specified return expressions. See https://docs.mongodb.com/manual/reference/operator/aggregation/cond/ for more details :param _if: expression that will be evaluated :param _then: if _if expression evaluates...
def cmaps(band): """ Color maps: 'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn' """ colors = {"B01": "Greys", "B02": "Blues", "B03": "Greens", ...
def u2(vector): """ This function calculates the utility for agent 2. :param vector: The reward vector. :return: The utility for agent 2. """ utility = vector[0] * vector[1] return utility
def seconds_to_days(seconds): """Takes a time in integer seconds and converts it into fractional days. Parameters ---------- seconds: int The number of seconds. Returns ------- float The number of days as a float. """ return(seconds / 86400.0)
def is_valid_writable(value): """ Check that writable flag is 'yes' or 'no' """ return value == 'yes' or value == 'no'
def accuracy(true_positives, true_negatives, false_positives, false_negatives, description=None): """Returns the accuracy, calculated as: (true_positives+true_negatives)/(true_positives+false_positives+true_negatives+false_negatives) """ true_positives = float(true_positives) true_...
def _get_einsum_operands(args): """Parse & retrieve einsum operands, assuming ``args`` is in either "subscript" or "interleaved" format. """ if len(args) == 0: raise ValueError( 'must specify the einstein sum subscripts string and at least one ' 'operand, or at least one...
def sum_pow(p, n_begin, n_end): """ Power summation, N inclusive. \sum_{n=N_begin}^{N_end} p^n """ return (p**(n_end+1) - p**n_begin) / (p - 1.0)
def pluck(dictionary, fields): """Extract fields from dict and return a dict""" return {key: dictionary.get(key, '') for key in fields}
def list_difference(li1, li2): """ Difference between two lists args: -li1 - 1st list -li2 - 2nd list returns: resulting list after subtraction """ return [i for i in li1 + li2 if i in li1 and i not in li2]
def wrap_it_in_a_link(html, url): """ Wrap a link around some arbitrary html Parameters: html - the html around which to wrap the link url - the URL to link to Returns: The same html but with a link around it """ return "<a href='" + url + "'>" + html + "</a>"
def homepath(): """Tries to find correct path for home folder. Returns ------- str Path to home directory. """ from os.path import expanduser home = expanduser("~") if not home: return '.' return home
def trim_slice(slice_nd, shape): """ Makes intersection of an array (defined by arg shape) with a slice (arg slice_nd). This method is useful for operations between two non-overlaping arrays. This can happen when the two arrays have different shapes, or when one is moved to a specific positio...
def sort_by_name(dicts): """ Sorting of a list of dicts. The sorting is based on the name field. Args: list: The list of dicts to sort. Returns: Sorted list. """ return sorted(dicts, key=lambda k: k.get("name", "").lower())
def _dict2list(irm_matrix): """Return pos, rho, and N as matching lists from the dict""" pos, rho, N = [], [], [] for key in irm_matrix: pos.append(irm_matrix[key]['position']) rho.append(irm_matrix[key]['rho']) N.append(irm_matrix[key]['N']) return pos, rho, N
def circle_bbox(radius, center): """ Computes the bounding box (upper-left, bottom-right) of a circle :param radius: radius of the circle :param center: (x,y) 2-tuple :return: list of 2 points representing the bounding box """ x, y = center return [[x-radius, y-radius], [x+ra...
def str_is_int(value): """Test if a string can be parsed into an integer. :returns: True or False """ try: _ = int(value) return True except ValueError: return False
def occupied(m: list, x, y) -> int: """Return 1 if the position (x, y) is occupied, or 0 if it is either outside of the map, or unoccupied.""" if x == -1 or y == -1 or y == len(m): return 0 if x == len(m[y]): return 0 if m[y][x] == '#': return 1 return 0
def get(array, index_tuple): """Get value from multi-dimensional array "array" at indices specified by tuple "index_tuple" """ to_return = array for index in index_tuple: to_return = to_return[index] return to_return
def calc_checksum(s): """NMEA checksum calculation""" checksum = 0 for char in s: checksum ^= ord(char) return "{:02x}".format(checksum).upper()
def get_seconds(data: dict) -> float: """Find out how many seconds the user has played for.""" return data.get('seconds', 0)
def render_header(level_and_content): """ - level_and_content: None OR string OR list of [postive-int, string] OR tuple of (positive-int, string), the header level and content RETURN: string, the header """ if level_and_content is None: return "" if isinstance(level_and_content, st...
def bool2str(value: bool) -> str: """Return bool as str.""" if value: return '1' return '0'
def update_shape(obs_shape, act_shape, rew_shape, wrapper_names): """ Overview: Get new shape of observation, acton, and reward given the wrapper. Arguments: obs_shape (:obj:`Any`), act_shape (:obj:`Any`), rew_shape (:obj:`Any`), wrapper_names (:obj:`Any`) Returns: obs_shape (:ob...
def check_wordlist_sets(wordlist, book_words): """Return only those words in book_words not in wordlist, in a set wordlist, book_words: dictionaries """ return set(book_words)-set(wordlist)
def str_to_hex(value: str) -> str: """Convert a string to a variable-length ASCII hex string.""" return "".join([f"{ord(x):02X}" for x in value])
def parse_values(values): """Create a new dictionary version from the sheet values passed in. Arguments: values -- (list) a 2d list of values from the google sheet Returns: new_sheet -- (dictionary) a dictionary representation of 'values' """ new_sheet = {} header = values[0] ...
def find_when_entered_basement(text): """Find position in text when santa enters basement first time.""" cur_floor = 0 for position, floor_change in enumerate(text, start=1): cur_floor += 1 if floor_change == '(' else -1 if cur_floor < 0: return position return -1
def handle_extends(tail, line_index): """Handles an extends line in a snippet.""" if tail: return 'extends', ([p.strip() for p in tail.split(',')],) else: return 'error', ("'extends' without file types", line_index)
def get_base_url(url): """Returns the base part of a URL, i.e., excluding any characters after the last /. @param url - URL to process @return base URL """ parts = url.rpartition('/') return parts[0] + (parts[1] if len(parts) >= 2 else '')
def choose_int(g1, g2): """Function used by merge_similar_guesses to choose between 2 possible properties when they are integers.""" v1, c1 = g1 # value, confidence v2, c2 = g2 if v1 == v2: return v1, 1 - (1 - c1) * (1 - c2) else: if c1 >= c2: return v1, c1 - c2 / 2 ...
def convert_section_to_keys(section): """Splits section into its keys to be searched in order Required Args: section (str) - Period delimited str Returns: (list) keys """ return section.split('.')
def _get_match_fields(flow_dict): """Generate match fields.""" match_fields = {} if "match" in flow_dict: for key, value in flow_dict["match"].items(): match_fields[key] = value return match_fields
def divide(a: float, b: float) -> float: """Return the quotient of two numbers. Args: a (float): dividend b (float): divisor Raises: ZeroDivisionError: gets raised when the divisor is `0` Returns: float: the quotient """ if b == 0: raise ZeroDivisionEr...
def cstring(s, width=70): """Return C string representation of a Python string. width specifies the maximum width of any line of the C string. """ L = [] for l in s.split("\n"): if len(l) < width: L.append(r'"%s\n"' % l) return "\n".join(L)
def url_join(*pieces: str) -> str: """ Join url parts, avoid slash duplicates or lacks :param pieces: any number of url parts :return: url """ return '/'.join(s.strip('/') for s in pieces)
def get_bit_value(val, place): """ Return the truthness of the bit in place place from 8 or 16 bit val """ place_val = 2**place return val & place_val != 0
def get_exb_group_best_con(exb_group_ids_list, id2exb_pair_dic): """ Given a list of site IDs connected at exon borders with intron-spanning reads. Only one of them should have a connection in both directions, while the other have different connections. >>> exb_group_ids_list = ['id1', 'id2', 'id3'...
def ns2sec(ns): """Convert ns to seconds.""" return ns / (10**9)
def finalize_version(v): """ Remove `-rc#` from a version string. A more realistic implementation would convert `v` to a SchemaVersion instance and use schema_version.semver.finalize_version(). """ assert isinstance(v, str) try: i = v.index("-rc") return v[0:i] except Val...
def canonical_order(match): """ When searching for atoms with matching bond patterns GraphMatcher often returns redundant results. We must define a "canonical_order" function which sorts the atoms and bonds in a way which is consistent with the type of N-body interaction being considered. The a...
def last_known_commit_id(all_commit_ids, new_commit_ids): """ Return the newest "known" (cached in mongo) commit id. Params: all_commit_ids: Every commit id from the repo on disk, sorted oldest to newest. new_commit_ids: Commit ids that are not yet cached in mongo, s...
def mapdictv(f, d): """ Maps a function over the *values* of a dictionary. Examples -------- Let us define a simple dictionary: >>> d = {'a': 0} Now, we can map over its values: >>> mapdictv(lambda x: x + 1, d) {'a': 1} """ return dict(map(lambda key: (key, f(d[key])), d.keys()))
def transpose(matrix): """ function to transpose a matrix """ return [[row[i] for row in matrix] for i in range(len(matrix[0]))]
def role(value, arg): """Returns html div with the given user's group's role Keyword arguments value -- list of dictionaries, containing users, groups and roles arg -- a user """ html = '' for group in value.get(arg): role = value.get(arg).get(group) if role: h...
def sort_by_name(dict): """ Sort a dictionary on the values """ return sorted(dict, key=dict.get)
def get_obj_elem_from_keys(obj, keys): """ Returns values stored in `obj` by using a list of keys for indexing. Parameters ---------- obj : object Python object offering indexing, e.g., a dictionary. keys : list of str List of keys for indexing. Returns ------- obje...
def bsort(A): """bucket sort O(N)""" count = [0]*1000 for x in A: count[x-1] += 1 ans = [] for i, x in enumerate(count, 1): if x: ans.extend([i]*x) return ans
def square_root_1param(t, a): """t^1/2 fit w/ 1 param: slope a.""" return a*t**(0.5)
def to_snake(camel): """TimeSkill -> time_skill""" if not camel: return camel return ''.join('_' + x if 'A' <= x <= 'Z' else x for x in camel).lower()[camel[0].isupper():]
def _find_quadratic_peak(y): """Given an array of 3 numbers in which the first and last numbers are less than the central number, determine the array index at which a quadratic curve through the 3 points reaches its peak value. Parameters ---------- y : float,float,float The values of th...
def found_solution(sudoku_possible_values, k): """ Checks if the search found a solution. Input: - sudoku_possible_values: all the possible values from the current step of the game. - k: the size of the grid. Output: - A boolean variable which takes True if a solution is found or...
def replaceMacrosWithValues(s, macroDict): """ Given a string, s, which might contain one or more macros of the form "$(P)", and given a dictionary of macro name/value pairs (e.g., macroDict["P"]=="xxx:") return s with macros replaced by their corresponding values. Also return a string indicating whether any macr...
def find_next_group(group_str, style='()'): """ Return the next group of data contained in a specified style pair from a string. Example: find_next_group('(a=1)(b=2)') returns 'a=1' :param group_str: Any string to search for a group. :param style: Start and end characters of a group. Default='(...
def parse_hex(hex_string): """ Helper function for RA and Dec parsing, takes hex string, returns list of floats. Not normally called directly by user. TESTS OK 2020-10-24. :param hex_string: string in either full hex ("12:34:56.7777" or "12 34 56.7777"), or degrees ("234.55") :return:...
def num2ord(place): """Return ordinal for the given place.""" omap = { u'1' : u'st', u'2' : u'nd', u'3' : u'rd', u'11' : u'th', u'12' : u'th', u'13' : u'th' } if place in omap: return place + omap[place] elif place.isdigit(): ...
def _simplify_method_name(method): """Simplifies a gRPC method name. When gRPC invokes the channel to create a callable, it gives a full method name like "/google.pubsub.v1.Publisher/CreateTopic". This returns just the name of the method, in this case "CreateTopic". Args: method (str): The...
def complement(base): """ Return the complementary DNA base """ complements = {"A": "T", "T": "A", "G": "C", "C": "G"} try: return complements[base] except KeyError: raise ValueError("Invalid DNA base. Must be uppercase ATGC")
def isaxis(data): """ Detects if there is an axis in the data. :type data: list[float] :param data: Data containing spectras an possible axis. :returns: True if there is axis. :rtype: bool """ features = list(data) is_axis = True # there is axis by default axis = features[0] ...
def autocomplete_configuration_path(actions, objects): """ Returns current configuration_path for object. Used as a callback for `default_value`. Args: actions: Transition action list objects: Django models objects Returns: configuration_path id """ configuration_pa...
def bubble_sort(items): """ the bubble sort algorithm takes in an unsorted list of numbers. returns a list in ascending order. Parameters ---------- items : list list of unordered numbers Returns ------- list list of elements in items in ascending order Exampl...
def pytest_saltfactories_master_configuration_overrides( request, factories_manager, config_defaults, master_id ): """ Hook which should return a dictionary tailored for the provided master_id. This dictionary will override the config_defaults dictionary. Stops at the first non None result """ ...
def positive_integer(val, default): """Attempt to coerce ``val`` to a positive integer, with fallback.""" try: val = int(val) except (AttributeError, TypeError, ValueError): val = default if val < 1: val = 1 return val
def get_distance_with_cam(blob_size): """ Calculate distance based on blob size """ if blob_size > 0: distance = (135142.26678986842/blob_size) -114.93114618701983 print('Distance to wall is -----------> ', distance) else: distance = -1 r...
def FindNumberOfLeadingSpaces(line): """Calculate number of leading whitespace characters in the string.""" n = 0 while n < len(line) and line[n].isspace(): n += 1 return n
def idndecode(domain, encoding='utf-8', errors='strict'): """Decode International domain string.""" if not isinstance(domain, bytes): return domain.encode('idna').decode('idna', errors) else: return domain.decode(encoding, errors).encode('idna').decode('idna', errors).encode(encoding, errors...
def get_version_from_arguments(arguments): """Checks the arguments passed to `nox -s release`. If there is only 1 argument that looks like a version, returns the argument. Otherwise, returns None. """ if len(arguments) != 1: return None version = arguments[0] parts = version.split...
def collapse_record(record, separator = '.', root=None): """Collapses the `record` dictionary. If a value is a dictionary, then its keys are merged with the higher level dictionary. Example:: { "date": { "year": 2013, "month" 10, "day": 1...
def dynamic_palindrome(s: str) -> str: """ Assume N = len(s). We make an NxN table T that we fill in bottom-up, where: 1. table[i][j] = the substring is a palindrome :param s: the longest palindrome :return: the first longest palindrome >>> dynamic_palindrome('a') 'a' >>> dynamic_pa...
def getSamlNames(members, user_map, remote_users): """ Method that replaces old remote usernames with new SAML usernames. Parameters: members (dict): The members of a user group user_map (list): User metadata remote_users (list): A list of remote user names ...
def _find_path(graph, start_addr, end_addr): """Determines if there is a path from start_addr to end_addr (note that edges in the graph are unidirectional). Args: graph, dict, a dict that maps a string (the sending address) to a set that contains every address that has received BTC from...
def snake(s): """ Converts an input string in PascalCase to snake_case. """ snek = [] prev_up = False prev_alnum = False for idx, c in enumerate(s): alnum = c.isalnum() up = c.isupper() next_up = s[idx+1].isupper() if idx+1 < len(s) else False if (up and not p...
def read_file(file_location): """ Reads the file stored at :param file_location :param file_location: absolute path for the file to be read (string) :return: contents of file (string) """ try: with open(file_location, "r") as file: return file.read() except FileNotFound...
def interpret_options(start_prefix, traj_prefix, info_name, language): """Reformat command line inputs. Args: start_prefix str Prefix of start files. traj_prefix str Prefix of trajectory files. info_prefix str Prefix of info file. languag...
def _get_fuzzy_name(names, fuzzy_name): """Return the full project name that matches the fuzzy_name. Note: There may be multiple matches for fuzzy_name. Currently this implementation will simply match the first occurance. That is probably a bug, but until this is used more I'm not sure what it should do. ...
def resdev_vout(Vin, R1, R2): """ Calculate Vout with given R1, R2 and Vin """ return Vin * R2 / (R1 + R2)
def is_js_true(value: str): """ booleans get converted into strings in json. This fixes that. """ if not value or value in ('false', 'False', False, 'No', 'no', 'F', 'null', 'off', 0, ''): return False else: ## while also return True if its a number or string. return True
def power(a,b): """ This function will return the power of a number """ if b == 0: return 1 elif b < 0: return 0 else: return a * power(a,b-1)
def _pack_bytes_signed(byte_list): """Packs a list of bytes to be a single signed int. The MSB is the leftmost byte (index 0). The LSB is the rightmost byte (index -1 or len(byte_list) - 1). Big Endian order. Each value in byte_list is assumed to be a byte (range [0, 255]). This assumption is n...
def merge_index_sections(new_section, old_section): """Helper function for merge_indexes which loops through each section and combines them. Args: new_section: section which is being added to if line from old_section is absent old_section: section which is pulled from Returns: ...
def get_list_detail_case_property_row(module_row, sheet_name): """ Returns case list/detail case property name """ case_property, list_or_detail, name = module_row return [ sheet_name, case_property, list_or_detail, '', # label name, '', # image ...
def _bytes(packet): """ Returns a human-friendly representation of the bytes in a bytestring. >>> _bytes('\x12\x34\x56') '123456' """ return ''.join('%02x' % ord(c) for c in packet)
def convert_str_key_to_int(data): """in a dictionary, convert to int the keys (assumed to be an int) that can be parsed to int AND order the dict in increasing key value the keys that cant be parsed are kept intact, but sorting still happens Args: data: anything. If it is not a...
def convert_letter_to_number(letter: str) -> int: """ This function receives a string representing a letter of the alphabet, and convert it to its respective number in ascending order, for example: A - 1 B - 2 C - 3 D - 4 :param str letter: The letter to be converted. :rtype: int ...
def _remove_duplicate_folders(folder_list): """Removes duplicate folders from a list of folders and maintains the original order of the list Args: folder_list(list of str): List of folders Returns: list of str: List of folders with duplicates removed """ new_folders_set = set() new_folders_list ...
def PercentBias(SimulatedStreamFlow, ObservedStreamFlow): """(SimulatedStreamFlow, ObservedStreamFlow) Define definition for Percent Bias model efficiency coefficient---used up in the class""" x = SimulatedStreamFlow y = ObservedStreamFlow A = 0.0 # dominator B = 0.0 # deminator for i in r...
def invert(instruction, mirror): """Returns the opposite (if exists) of an instruction.""" if instruction in mirror: return mirror[instruction] return instruction
def cleanString(s,spaces_for_underscores=False): """cleans a string from special chars and spaces""" if spaces_for_underscores: s= s.strip().replace(' ','_') return "".join(x for x in s if x.isalnum() or x == '_')
def liveobj_changed(obj, other): """ Check whether obj and other are not equal, properly handling lost weakrefs. Use this whenever you cache a Live API object in some variable, and want to check whether you need to update the cached object. """ return obj != other or type(obj) != type(other)