content
stringlengths
42
6.51k
def time_in_range(start, end, day_start, day_end): """Return true if event time range overlaps day range""" if (start <= day_start and end >= day_end): return True elif (start >= day_start and start <= day_end): return True elif (end >= day_start and end <= day_end): return True ...
def _one_hot(index, size): """returns one-hot vector with given size and value 1 at given index """ vec = [0 for _ in range(size)] vec[int(index)] = 1 return vec
def disambiguate(names, mark='1'): """ Given a list of strings ``names``, return a new list of names where repeated names have been disambiguated by repeatedly appending the given mark. EXAMPLE:: >>> disambiguate(['sing', 'song', 'sing', 'sing']) ['sing', 'song', 'sing1', 'sing11'] ""...
def binary_search(array, k, pos): # O(logN) """ Apply binary search to find either a "start" or "end" of a particular number >>> binary_search([2, 3, 3, 3, 4], 3, 'start') 1 >>> binary_search([2, 3, 3, 3, 4], 3, 'end') 3 >>> binary_search([2, 3, 3, 3, 4], 5...
def stringify_dict(d): """create a pretty version of arguments for printing""" if 'self' in d: del d['self'] s = 'Arguments:\n' for k in d: if not isinstance(d[k], str): d[k] = str(d[k]) s = s + '%s: %s\n' % (k, d[k]) return(s)
def list_all(seq): """Create a list from the sequence then evaluate all the entries using all(). This differs from the built-in all() which will short circuit on the first False. """ return all(list(seq))
def number_of_divisors(n) -> int: """ Returns the number of all non-trivial divisors """ n = abs(n) i = 2 NumberOfDivisors = 0 while i < n: if n % i == 0: NumberOfDivisors += 1 i += 1 return NumberOfDivisors
def _quote_if_str(val): """ Helper to quote a string. """ if isinstance(val, str): return f"'{val}'" return val
def fromDD(s): """Takes a string of 2 digits and returns a number with up to 2 digits""" if len(s) <= 2: return int(s) else: return int(s[0:2])
def avg(stats: list) -> float: """ Find the average of a list. Given a list of numbers, calculate the average of all values in the list. If the list is empty, default to 0.0. Parameters ---------- input_list : list A ``list`` of ``floats`` to find an average of. Returns --...
def tablenamify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower...
def get_metric_names(data: dict) -> dict: """Retrieves metric names from returned data.""" row = {} for index, col in enumerate(data['result']['definition']['metrics']): row[index] = col["name"] return row
def name_test(item): """ used for pytest verbose output """ return f"{item['params']['peer_link']}"
def is_probably_number(value: str) -> bool: """ Determine whether value is probably a numerical element. """ # value is simply a numerical value probably_number = value.isdigit() if not probably_number: s = value.split(' ') if len(s) is 2: # value is made up of 2 component...
def create_description(name, args=None): """Create description from name and args. Parameters ---------- name : str Name of the experiment. args : None or argparse.Namespace Information of the experiment. Returns ------- description : str Entire description of t...
def listToString(my_list): """ A function to convert a list to a string """ # initialize an empty string str1 = "" # traverse in the string for element in my_list: str1 += element # return string return str1
def clear_url(url): """ Remove domain and protocol from url """ if url.startswith('http'): return '/' + url.split('/', 3)[-1] return url
def find_str(s,l): """ Find index of occurence of string s in list l """ idx = 0 while idx < l.__len__() and l[idx] != s: idx = idx + 1 return idx
def reverse_complement(x): """Construct reverse complement of string. """ rc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} x = x.upper() return ''.join(rc[b] for b in x[::-1])
def getitem_helper(obj, elem_getter, length, idx): """Helper function to implement a pythonic getitem function. Parameters ---------- obj: object The original object elem_getter : function A simple function that takes index and return a single element. length : int The...
def configurePostfix(post): """configurePostfix(post) Configure a string that will be appended onto the name of the spectrum and other result attributes.""" return {'Postfix' : post }
def is_vm(obj): """ Checks if object is a vim.VirtualMachine. :param obj: The object to check :return: If the object is a VM :rtype: bool """ return hasattr(obj, "summary")
def set_output(kwargs, job, map): """Set the __no_output__ flag""" if 'return_preds' in kwargs: if kwargs['return_preds']: __no_output__ = False else: __no_output__ = True else: __no_output__ = job == 'fit' kwargs['return_preds'] = job != 'fit' if...
def str_width(unicode_text): """calc string width, support cjk characters.""" from unicodedata import east_asian_width return sum(1+(east_asian_width(c) in "WF") for c in unicode_text)
def fetch_value(data: dict, key: str, default: str=''): """ Function to get a value from a key in a dict. Supports getting values from an array index. Args: data (dict): A dictionary. key (str): Key for which to get the value. Can have an index attached as [index]. default (str,...
def get_text_content(node, xpath=""): """ return the text from a specific node Parameters ---------- node : lxml node xpath : xpath.search Returns ------- str None if that xpath is not found in the node """ if node is None: return None if xpath: no...
def nvdot(nv, nb0, nbs, e_effective, F, alpha, B, pv): """ Calculates the rate of change in minutes for the total phage population, nv. Note that this assumes CRISPR immunity is only present for exactly matching clones. Inputs: nv : total phage population size at time t nb0 : number of bact...
def arch2abi(arch): """Map arch to abi""" # pylint: disable=too-many-return-statements if "rv32e" in arch: if "d" in arch: return "ilp32ed" if "f" in arch: return "ilp32ef" return "ilp32e" if "rv32i" in arch: if "d" in arch: return "ilp...
def license_filter(lic): """Used from the template to produce the license logo""" lic_abbr,lic_name=lic # something like BY-SA, CC BY-SA 4.0 unported if lic_abbr == "GNU": logo_file = "gpl" elif lic_name.startswith("CC0"): logo_file = "cc-zero" elif lic_name.startswith("CC"): ...
def header(text): """Format text as a wikitext markup header""" if '|' not in text: return f"! {text}\n" else: return f"!{text[1:]}"
def is_in_range(a, low, high): """ Return True if 'a' in 'low' <= a >= 'high' """ return (a >= low and a <= high)
def dynamic_param_logic(text): """ validates parameter values for dynamic completion """ is_param = False started_param = False prefix = "" param = "" txtspt = text.split() if txtspt: param = txtspt[-1] if param.startswith("-"): is_param = True elif len(tx...
def escape_xpath(string: str) -> str: """ Xpath string literals don't have escape sequences for ' and " So to escape them, we have to use the xpath concat() function. See https://stackoverflow.com/a/6938681 This function returns the *enclosing quotes*, so it must be used without them. For example: dom.xpath(f"//...
def percentage_to_int(value): """ Scale values from 0-100 to 0-255 """ return round((255.0 / 100.0) * float(value))
def doGroup(indata, group_key_func, group_data_func): """Group the indata based on the keys that satisfy group_key_func (applied to the value) Return a dict of groups summarized by group_data_func Each group returned by group_data_func must be a dictionary, possibly similar to the original value of the ...
def make_filename_by_table_var(table, variable, prefix=''): """Generate a filename (without extention) using table and variable names.""" if prefix != '': prefix += '_' return prefix + variable + '_' + table
def make_suffix_array(s): """ Given T return suffix array SA(T). We use Python's sorted function here for simplicity, but we can do better. """ satups = sorted([(s[i:], i) for i in range(len(s))]) # Extract and return just the offsets return list(map(lambda x: x[1], satups))
def quadraticPointAtT(pt1, pt2, pt3, t): """Finds the point at time `t` on a quadratic curve. Args: pt1, pt2, pt3: Coordinates of the curve as 2D tuples. t: The time along the curve. Returns: A 2D tuple with the coordinates of the point. """ x = (1 - t) * (1 - t) * pt1[0] +...
def pad_input_ids_msmarco(input_ids, max_length, pad_on_left=False, pad_token=0): """An original padding function that is used only for MS MARCO data.""" padding_length = max_length - len(input_ids) padding_id = [pad_token] * padding_length if padding...
def bonferroni_correction(significance, numtests): """ Calculates the standard Bonferroni correction. This is used for reducing the "local" significance for > 1 statistical hypothesis test to guarantee maintaining a "global" significance (i.e., a family-wise error rate) of `significance`. Para...
def get_cvss_score(vuln, vulners_api): """Get CVSS score if available, otherwise get Vulners AI score""" cvss = vuln["cvss"]["score"] if cvss == 0.0: try: return vulners_api.aiScore(vuln["description"])[0] except: return 0.0 else: return cvss
def odd(num): """ Check if a number is odd :type num: number :param num: The number to check. >>> odd(3) True """ return num % 2 != 0
def tree_search(states, goal_reached, get_successors, combine_states): """ Given some initial states, explore a state space until reaching the goal. `states` should be a list of initial states (which can be anything). `goal_reached` should be a predicate, where `goal_reached(state)` returns `True` ...
def normalize(position): """ Accepts `position` of arbitrary precision and returns the block containing that position. Parameters ---------- position : tuple of len 3 Returns ------- block_position : tuple of ints of len 3 """ x, y, z = position x, y, z = (int(round(x)), i...
def as_dicts(results): """Convert execution results to a list of tuples of dicts for better comparison.""" return [result.to_dict(dict_class=dict) for result in results]
def _to_date_in_588(date_str): """ Convert date in the format ala 03.02.2017 to 3.2.2017. Viz #100 for details. """ try: date_tokens = (int(x) for x in date_str.split(".")) except ValueError: return date_str return ".".join(str(x) for x in date_tokens)
def content_priority(experiment, obj): """ Return a priority to assign to ``obj`` for an experiment. Higher priority objects are shown first. """ score = 0 if hasattr(obj, 'photo'): photo = obj.photo score += photo.publishable_score() if photo.synthetic and photo.intrinsic_synt...
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 10) # 4 * 3 * 2 * 1 # Only n times!! 24 """ if (n > k): tota...
def unpackHexStrings(hexRow): """Unpacks a row of binary strings to a list of floats""" return [float.fromhex(ss) for ss in hexRow.split() if ss != ""]
def degree_to_order(degree): """Compute the order given the degree of a B-spline.""" return int(degree) + 1
def merge(a, b, *, replace=None): """ Merges dicts and lists from the configuration structure """ if isinstance(a, dict) and isinstance(b, dict): if not replace: replace = set() res = {} for key in set(a).union(b): if key not in a: res[key] = b[ke...
def split_content_header_data( content ): """ Splits content into its header and data components. :param content: The content to split. :returns: Tuple of ( header, data ). :raises RuntimeError: If the data could not be split. """ split_pattern = '*** The recorded data ***' try...
def isint(x): """Determine if provided object is convertible to an int Args: x: object Returns: bool """ if x is None: return False try: int(float(x)) return True except: return False
def get_action_mapping(n, exclude_self=True): """In a matrix view, this a mapping from 1d-index to 2d-coordinate.""" mapping = [ (i, j) for i in range(n) for j in range(n) if (i != j or not exclude_self) ] return mapping
def test_list(l): """ Return true if object is a list """ return isinstance(l, list)
def convert_move_to_action(move_str: str): """ :param move_str: A1 -> 0, H8 -> 63 :return: """ if move_str[:2].lower() == "pa": return None pos = move_str.lower() x = ord(pos[0]) - ord("a") y = int(pos[1]) - 1 return y * 8 + x
def set_haplotypes(curr_coverage): """Creates a list to manage counting haplotypes for subplots """ hps = sorted(curr_coverage.keys(), reverse=True) #if there are multiple haplotypes, must have 0,1,2 if len(hps) > 1 or (len(hps) == 1 and hps[0] != 0): if 0 not in hps: hps.append(...
def redshifts_to_frequencies(z): """The cosmological redshift (of signal) associated with each frequency""" return 1420e6 / (z + 1)
def utm_from_lon(lon): """ utm_from_lon - UTM zone for a longitude Not right for some polar regions (Norway, Svalbard, Antartica) :param float lon: longitude :return: UTM zone number :rtype: int """ from math import floor return floor((lon + 180) / 6) + 1
def hinted_tuple_hook(obj): """ Decoder for specific object of json files, for preserving the type of the object. It's used with the json.load function. """ if '__tuple__' in obj: return tuple(obj['items']) else: return obj
def linspace(start, stop, num, decimals=18): """ Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value...
def exclude(list, exclusions): """New list >>> exclude(['a', 'b', 'c'], ['b']) ['a', 'c'] """ included = [] for item in list: if not item in exclusions: included.append(item) return included
def flatten(d): """ This flattens a nested dictionary. Args: d (dict|list): The object to flatten. Returns: flat_d (dict): The flattened object. """ def recurse(value, parent_key=""): if isinstance(value, list): for i in range(len(value)): re...
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. From Django's "django/template/defaultfilters.py". """ for c in r'[]/\;,><&*:%=+@!#^\'()$| ?^': value = value.replace(c,'') return value
def is_valid_ecl(eye_color): """Checks for valid Eye Color.""" if eye_color in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']: return True else: return False
def mayan_long_count_date(baktun, katun, tun, uinal, kin): """Return a long count Mayan date data structure.""" return [baktun, katun, tun, uinal, kin]
def bittest(val, n): """ Return the n^th least significant bit of val. """ return (val >> n) & 1
def get_tile_index(rank: int, total_ranks: int) -> int: """ Returns the zero-indexed tile number, given a rank and total number of ranks. """ if total_ranks % 6 != 0: raise ValueError(f"total_ranks {total_ranks} is not evenly divisible by 6") ranks_per_tile = total_ranks // 6 return rank...
def factors_singles(num): """ (int) -> list Builds a list of factors for a positive integer <num>. Returns the list """ return [x for x in range(1, num + 1) if num % x == 0]
def str_to_bool(s: str): """Return a boolean for the given string, follows the same semantics systemd does.""" if s.lower() in ('1', 'yes', 'true', 'on'): return True elif s.lower() in ('0', 'no', 'false', 'off'): return False else: raise NotImplementedError(f"Unknown boolean val...
def zero_fill(value: bytearray) -> bytearray: """ Zeroing byte objects. Args: value: The byte object that you want to reset. Returns: Reset value. """ result = b'' if isinstance(value, (bytes, bytearray)): result = b'/x00' * len(value) result = bytearray(res...
def get_common_gn_args(is_zircon): """Retrieve common GN args shared by several commands in this script. Args: is_zircon: True iff dealing with the Zircon build output directory. Returns: A list of GN command-line arguments (to be used after "gn <command>"). """ if is_zircon: ret...
def _resolve_role(current_user, profile): """What is the role of the given user for the given profile.""" if current_user: if profile.user == current_user: return "OWNER" elif current_user.is_authenticated: return "ADMIN" else: return "ANONYMOUS" e...
def is_number(string): """ Return whether or not a string is a number """ if string.startswith("0x"): return all(s.lower() in "0123456789abcdef" for s in string[2:]) if string.startswith("0b"): return all(s in "01" for s in string[2:]) else: return string.lstrip("-").replace(".",...
def words_frequency(item): """Convert the partitioned data for a word to a tuple containing the word and the number of occurances. """ word, occurances = item return (word, sum(occurances))
def is_misc(_item): """item is report, thesis or document :param _item: Zotero library item :type _item: dict :returns: Bool """ return _item["data"]["itemType"] in ["thesis", "report", "document"]
def text_escape(v: str) -> str: """ Escape str-like data for postgres' TEXT format. This does all basic TEXT escaping. For nested types as of hstore or in arrays, array_escape must be applied on top. """ return (v.replace('\\', '\\\\') .replace('\b', '\\b').replace('\f', '\\f').replace(...
def parse_value(val: bytes): """Parse value from IMAP response :param val: :return: """ if val in (b'NIL', b'nil') or not val: return None if val.isdigit(): return int(val) return val
def level_to_color(tags): """ map django.contrib.messages level to bootstraps color code """ level_map = { 'debug': 'dark', 'info': 'info', 'success': 'success', 'warning': 'warning', 'error': 'danger' } return level_map[tags]
def one(item): """ Return the first element from the iterable, but raise an exception if elements remain in the iterable after the first. >>> one(['val']) 'val' >>> one(['val', 'other']) Traceback (most recent call last): ... ValueError: ...values to unpack... >>> one([]) ...
def ensure_str(obj): """Ensure `obj` is a str object (or None).""" return obj if obj is None else str(obj)
def dist(p1, p2): """Return Manhattan distance between the given points.""" return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def getDistance(posn1, posn2): """Helper for getSeeds that calculates the cartesian distance between two tuple points.""" distX = (posn1[0] - posn2[0]) ** 2 distY = (posn1[1] - posn2[1]) ** 2 return (distX + distY) ** 0.5
def convert_uuid(*args, **kwargs): """ Handle converter type "uuid" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'string', 'format': 'uuid', } return schema
def get_oil_price(hp): """Provide oil cost per km from horsepower Arg: hp (int): horsepower of tugs Return: (float): oil price ($/km) """ hp_price = { 1800: 134.1075498270909, 2400: 185.0696699493183, 3200: 257.887743955886, 3300: 267.3812284262817, ...
def parse_resolution(res: str): """ Parse a resolution string. If the y value is zero, the x value is the number to scale the image with. """ # Check what type of input we're parsing if res.count("x") == 1: # Try parsing the numbers in the resolution x, y = res.split("x") try: ...
def extra_year_bits(year=0x86): """ practice getting some extra bits out of the year byte >>> extra_year_bits( ) [1] >>> extra_year_bits(0x06) [0] >>> extra_year_bits(0x86) [1] >>> extra_year_bits(0x46) [0] >>> extra_year_bits(0x26) [0] >>> extra_year_bits(0x16) [0] """ # year = ye...
def check_edge(t, b, nodes): """ t: tuple representing an edge b: origin node nodes: set of nodes already visited if we can get to a new node from `b` following `t` then return that node, else return None """ if t[0] == b: if t[1] not in nodes: return t[1] elif t...
def modular_multiply(A, B, C): """Finds `(A * B) mod C` This is equivalent to: `(A mod C * B mod C) mod C` https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/modular-multiplication https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a...
def list_latex2str(x): """Dataframe's map function Replaces the latex of the custom dataset to ground truth format. Args: x (list) : latex string to convert Returns: latex of ground truth format(str) """ return ' '.join(x)
def check_contain_chinese(check_str): """Check if the path name and file name user input contain Chinese character. :param check_str: string to be checked. """ for ch in check_str: if u'\u4e00' <= ch <= u'\u9fff': return True return False
def pagify(text: str, delim="\n", *, shorten_by=0, page_length=2000): """ Chunk text into manageable chunks. This does not respect code blocks or special formatting. """ list_of_chunks = [] chunk_length = page_length - shorten_by deliminator_test = text.rfind(delim) if deliminator_test...
def cosine_similarity(str_a, str_b): """ Calculate cosine similarity Returns: cosine score """ set1 = set(str_a.decode('utf8')) set2 = set(str_b.decode('utf8')) norm1 = len(set1) ** (1. / 2) norm2 = len(set2) ** (1. / 2) return len(set1 & set2) / (norm1 * norm2)
def cired_re(b4, b5, b8, a=0.7): """ Red and Red-edge Modified Chlorophyll Index (Xie et al. 2018). .. math:: CIREDRE = (b8 / (a * b4 + (1 - a) * b5)) - 1 :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-edge 1. :type b5: numpy.ndarray or float :param b8: NIR. :type ...
def divisible_by(divisor, number): """Return True if the ``number`` is divisible by ``divisor``. >>> divisible_by(3, 6) True >>> divisible_by(5, 10) True >>> divisible_by(3, 4) False """ return number % divisor == 0
def dirplus(obj=None): """Behaves similar to the dir() function, but omits the "dunder" objects from the output. Examples: >>> blah = 'Here is some blah blah' >>> dirplus()\n ['dirplus', 'blah'] >>> type(blah)\n <class 'str'> >>> dirplus(blah)\n ['capitalize', 'casefold', 'center...
def replaceAll(initialString, translationHash): """ for each (toReplace, replacement) in `translationHash` applying the query-replace operation to `initialString` """ result = '' if initialString is not None: result = initialString for key, value in translationHash: r...
def _filter_case_action_diffs(diffs): """Ignore all case action diffs""" return [ diff for diff in diffs if diff.path[0] != 'actions' ]
def write_editor(editor_list: list) -> str: """ Given a list of editors, insert into XML snippet, and return XML snippet :param editor_list: A list of 1+ editors structured as [('First','Last'),('First','Last')] :return: XML snippet for editors >>> write_editor([('Bertha B.', 'Jorkins')]) #doctes...
def fib_recursive(n): """Find the n-th fibonacci number, recursively""" if n < 1: return 0 if n <= 2: return (n - 1) return fib_recursive(n - 1) + fib_recursive(n - 2)