content
stringlengths
42
6.51k
def endx(eta,merger_type): """ Gives ending value/upper boundary for integration of post-Newtonian parameter, based on Buskirk et al. (2019) equation 23. Parameters ---------- eta: float Symmetric mass ratio of the binary, can be obtained from get_M_and_eta(). merger_typ...
def camels_to_move(camel_dict, space, height): """Getting information about camels that need to move Parameters ---------- camel_dict : nested dict Dictionary with current camel positions space : int Space the camel is on height : int Height of the camel Returns ...
def extract_version_from_path(path): """extracts version number ("_v%03d") as an integer from the given path :param path: The path to extract the version number from """ import re version_matcher = re.compile("([\w\d/]+_v)([0-9]+)([\w\d._]+)") m = re.match(version_matcher, path) if m: ...
def subdict(fromdict, fields, default=None, *, force=False): """ Return a dictionary with the specified selection of keys from `fromdict`. If `default` is not None or `force` is true, set missing requested keys to the value of `default`. (Argument `force` is only needed if the desired default is Non...
def stringround(main, rest): """ Given a file size in either (mb, kb) or (kb, bytes) - round it appropriately. """ # divide an int by a float... get a float value = main + rest/1024.0 return str(round(value, 1))
def p_int(x): """Attempts to convert x to positive int. Parameters ---------- x : object Returns ------- float """ x = int(x) if x < 1: raise ValueError("x cannot be converted to positive float") return x
def order(sentence: str) -> str: """ Sorts a given string by following rules: 1. Each word in the string will contain a single number. This number is the position the word should have in the result. 2. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). 3. I...
def unify(comparisons, weights='actual', threshold=0.5): """Unify all comparisons in one way and with appropriate weights. Unify all comparisons: a = b => a = b and b = a a < b => a < b a > b => b < a where 0 means = and 1 means <. The appropriate weight can be chose either as - actual:...
def calculate_test_values( total_words, ocr_recognized_words, tp, tn, fn ): """ Calculates the model test values : TP : True Positive (There are words and every word has been recognized) TN : True Negative (There is no word and no word has been recognized) FP : False Positive (There ...
def position_is_bomb(bombs, position): """Check if a given position is a bomb. We don't check the board because that is an unreliable source. An agent may be obscuring the bomb on the board. """ for bomb in bombs: if position == bomb["position"]: return True ret...
def seconds_to_string(seconds): """ Format a time given in seconds to a string HH:MM:SS. Used for the 'leg time/cum. time' columns of the table view. """ hours, seconds = divmod(int(seconds), 3600) minutes, seconds = divmod(seconds, 60) return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
def concat_filter_strings(filter_strings, operator='&'): """ Helper function to combine ami filter strings Parameters ---------- filter_strings: ``list`` The valid filter strings to combine operator: ``str`` The operator to place between the filter strings. This can either be ...
def count_stair_ways(n): """Count the numbers of ways to walk up a flight of stairs with 'n' steps while taking a maximum of 2 steps at a time >>> count_stair_ways(2) 2 >>> count_stair_ways(3) 3 >>> count_stair_ways(4) 5 >>> count_stair_ways(5) 8 """ """BEGIN PROBLEM 3.1""" ...
def parse_input(input_parameter): """From a syntax like package_name#submodule, build a package name and complete module name. """ split_package_name = input_parameter.split("#") package_name = split_package_name[0] module_name = package_name.replace("-", ".") if len(split_package_name) >= 2...
def get_text(result, blocks_map, confidence): """ Add confidence + remove comma """ text = '' if 'Relationships' in result: for relationship in result['Relationships']: if relationship['Type'] == 'CHILD': for child_id in relationship['Ids']: w...
def pad_with_obj_up_to_k(lst, k, pad_with=-1): """ Pads a list with an object so resulting length is k e.g. _pad_with_zeros_up_to_k([1,2,3], 5, 0) => [1,2,3,0,0] """ assert k >= len(lst) return lst + (k - len(lst)) * [pad_with]
def hexToRgb(hex): """ Converts hex colour codes eg. #FFF or #00FF0F to rgb array Args: hex (string): colour code # followed by 3 or 6 hexadecimal digits Returns: Array [r, g, b] each in the range of 0 - 255 inclusive """ # strip '#' if hex[0] == "#": hex = hex[1:] ...
def kegg_properties_to_models(kegg_attributes): """Modify the kegg attribute dictionary to match the db '{}_id' formatting. :param dict kegg_attributes: kegg description dictionary :rtype: dict :return: dictionary with bio2bel_kegg adapted keys """ return { '{}_id'.format(key.lower()): ...
def find_merge_commit_in_prs(needle, prs): """Find the merge commit `needle` in the list of `prs` If found, returns the pr the merge commit comes from. If not found, return None """ for pr in prs[::-1]: if pr['merge_commit'] is not None: if pr['merge_commit']['hash'] == needle[1...
def _divide_and_round(a, b): """divide a by b and round result to the nearest integer When the ratio is exactly half-way between two integers, the even integer is returned. """ # Based on the reference implementation for divmod_near # in Objects/longobject.c. q, r = divmod(a, b) # round ...
def unescape_html(escaped_html_data): """This function unescapes an escaped HTML string. Args: escaped_html_data: str. Escaped HTML string to be unescaped. Returns: str. Unescaped HTML string. """ # Replace list to unescape html strings. REPLACE_LIST_FOR_UNESCAPING = [ ...
def current_state(states, fixed_index, periods_since_fixed): """Return the state of some day based on how it was last fixed. Arguments: states - An array of states, or anything really. fixed_index - The index of the state last specified. periods_since_fixed - The number of periods since...
def pad_same(in_dim, ks, stride, dilation=1): """ Refernces: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/common_shape_fns.h https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/common_shape_fns.cc#L21 """ assert strid...
def get_column(A, j): """ returns the specified column of the given matrix """ return[A_i[j] for A_i in A]
def parse_proxy(proxy_str): """Parses proxy address user:pass@host:port into a dict suitable for httplib2""" proxy_dict = {} if proxy_str is None: return if '@' in proxy_str: user_pass, host_port = proxy_str.split('@') else: user_pass, host_port = '', proxy_str if ':' in ...
def is_adjective(word, adjectives): """ Check whether the given word is an adjective or not :param word: the input word :param adjectives: list of all adjectives in the English language :return: True if the word is an adjective, False otherwise """ if word in adjectives: return True ...
def read_file(path): """Read contents of file at given path as bytes.""" with open(path, 'rb') as f: return f.read()
def add_element_wise(list1, list2): """Adds the two lists interleaved by eachother""" return [a + b for a, b in zip(list1, list2)]
def truncate_seeds(data): """ If not all runs have the same seeds (typically, a run is missing some seeds), remove data which is not in the intersection of all seeds. Args: data (dict): The data to prune """ seeds = set() first = True for mk, mv in data.items(): for ck,...
def _FormatChar(ch): """Convert a character into its C source description.""" code = ord(ch) if code < 32 or code > 127: return "'\\%d'" % code else: return "'%s'" % ch
def convert_dict(dicts: dict) -> dict: """ Convert all the values in a dictionary to str and replace char. For example: <class 'torch.Tensor'>(unknow type) to torch.Tensor(str type). Args: dicts (`dict`): The dictionary to convert. Returns: (`dict`) The...
def get_basename(path, extension): """Returns the filename (without its whole path) without its extension. Argument: path: str extension: str: The extension (with a dot if there is one). Example: >>> print get_basename("~/Meshes/my_mesh.mesh", ".mesh") ... my_mesh "...
def get_label(row, col, direction): """Provides a string that follows a standard format for naming constraint variables in Maze. Namely, "<row_index>,<column_index><north_or_west_direction>". Args: row: Integer. Index of the row. col: Integer. Index of the column. direction: String ...
def getFactors(x): """Returns a list of factors of the given number x. Basically, finds the numbers between 1 and the given integer that divide the number evenly. For example: - If we call getFactors(2), we'll get [1, 2] in return - If we call getFactors(12), we'll get [1, 2, 3, 4, 6, 12] in return...
def fib(n): """ Of course the cleanest solution is to use a Python Decorator so the used doesn't need to decorate nothing on its own """ if n <= 1: return n else: return fib(n - 1) + fib(n - 2)
def makeBytes(text): """Make sure the argument is bytes, converting with UTF-8 encoding if it is a string.""" if isinstance(text, bytes): return text elif isinstance(text, str): return text.encode("utf-8") else: raise ValueError("Expected str or bytes!")
def get_values(line): """ Returns the portion of an INSERT statement containing values """ return line.partition(b'` VALUES ')[2]
def pig_latinize(noun): """ convert one word into pig latin """ # http://pythonicprose.blogspot.com/2009/09/python-pig-latin-generator.html word = noun.lower() m = len(word) vowels = "a", "e", "i", "o", "u", "y" # short words are not converted if m<3 or word=="the": return word ...
def check_exact_match(numerators_0, denominators_0, numerators_1, denominators_1): """Returns whether the first fraction matches the second fraction. Args: numerators_0 (tuple, list): Numerators of the first fraction. denominators_0 (tuple, list): Denominators of the first...
def radix_sort(lst): """Implement radix sort algorithm.""" if len(lst) < 2: return lst def fill_buckets(lst, iteration): """Divide.""" buckets = [[] for x in range(10)] for number in lst: digit = (number // (10 ** iteration)) % 10 buckets[digit].appen...
def is_digit(character): """ Function to determine whether a given character is a digit. :param character: The character to be checked :return: Whether the character is a digit or not as a boolean value """ if ord('0') <= ord(character) <= ord('9'): return True else: return F...
def build_role_arn(account, role_name): """Build role arn :param account: AWS account ID :param role_name: role name :return: string """ if role_name is None or account is None: return None return "arn:aws:iam::{}:role/{}".format(account, role_name)
def representsInteger(str): """ Checks if a string only contains integers :param str str: string we want to check only has integers :return: if string only contains integers :rtype: boolean """ try: int(str) return True except ValueError: return False
def filter_data(data): """ filter ordinals from string greater than 128 :param data: original input string data :return: filtered string """ return ''.join(list(filter(lambda x: ord(x) <= 128, data)))
def nb_of_attrs_mismatch(source, target): """Generate a query which returns the number of attributes of a node which are not in its image.""" query = ( "REDUCE(invalid = 0, k in filter(k in keys({}) WHERE k <> 'id' AND k <> 'count') |\n".format(source) + "\tinvalid + CASE\n" + "\t\tW...
def equivalent(doc1, doc2, method=None): """Determine whether two dict/array/literal documents are structurally equivalent.""" if method == 'acl_binding': # fill in defaults to avoid some false negatives on acl binding comparison if not isinstance(doc1, dict): return False de...
def b(r, Rmax): """ Inflow angle of the cyclonic wind fields direction according to Grey and Liu (2019)""" if r < Rmax: b = 10 * r / Rmax elif r >= 1.2*Rmax: b = 10 else: b = (75 * r / Rmax) - 65 return b
def get_extension(file): """ Return the Extension of a filename """ return file.split('.')[-1]
def safe_value_fallback(obj: dict, key1: str, key2: str, default_value=None): """ Search a value in obj, return this if it's not None. Then search key2 in obj - return that if it's not none - then use default_value. Else falls back to None. """ if key1 in obj and obj[key1] is not None: r...
def add(n1, n2, base=10): """Add two numbers represented as lower-endian digit lists.""" k = max(len(n1), len(n2)) + 1 d1 = n1 + [0 for _ in range(k - len(n1))] d2 = n2 + [0 for _ in range(k - len(n2))] res = [] carry = 0 for i in range(k): if d1[i] + d2[i] + carry < base: ...
def get_extension(file_path: str): """ Returns a file's extension if any, else None :param str file_path: :return: """ split = file_path.rsplit('.', 1) return split[1] if len(split) > 1 else None
def common_elements_solution2(list1, list2): """ Time: O(max(n, m)), n,m: sizes of list1, list2. Space: O(min(n, m)) """ result = [] i = j = 0 while i < len(list1) and j < len(list2): if list1[i] == list2[j]: result.append(list1[i]) i += 1 j += ...
def negotiation_failed(err=None): """ Construct a template for SSH connection """ tpl = { 'ssh-event': 'negotiation-failed' } if err is not None: tpl['error'] = err return tpl
def get_fields_of_class(cls): """ returns the fields of a single class """ # this relies on https://www.python.org/dev/peps/pep-0520 # and Python 3.6 (see Note in PEP520) return [(n,v) for n,v in cls.__dict__.items() if not n[0] == '_']
def dmka(D, Ds): """Multi-key value assign Multi-key value assign Parameters ---------- D : dict Main-dict. Ds : dict Sub-dict. """ for k, v in Ds.items(): D[k] = v return D
def unorderable_list_difference(expected, actual, ignore_duplicate=False): """Same behavior as sorted_list_difference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance. """ missing = [] unexpected = [] while ...
def msgid(uid, host='localhost'): """ Formatted id for email headers. ie. <UIDUIDUIDUIDUID@localhost> """ return "<%s@%s>"%(uid, host)
def whitespace_around_comma(logical_line): """ Avoid extraneous whitespace in the following situations: - More than one space around an assignment (or other) operator to align it with another. JCR: This should also be applied around comma etc. Note: these checks are disabled by default ...
def get_item(dictionary, key): """ :param dictionary: dict :param key: :return: """ if dictionary is None: return None return dictionary.get(key, None)
def fib(num): """ >>> fib(5) 5 >>> fib(0) 0 >>> fib(10) 55 >>> fib(20) 6765 """ if num == 0: return 0 elif num == 1: return 1 else: return fib(num - 1) + fib(num - 2)
def remove_near_elements(arr, time_difference, time_idx) -> list: """Remove list elements within a specified time difference. Args: arr: a list of arrays or tuples time_difference: the minimum time difference between elements time_idx: the index of each arr element with an integer time ...
def clean_profile(evolution_profile): """ This function is to clean the calculated profile from binary search. Redundant trial results are pruned out, with only transition points left. """ raw_data = list(evolution_profile.items()) raw_data.sort() clean_set = [raw_data[0]] for i in range...
def pop_kwargs_with_prefix(prefix: str, kwargs: dict) -> dict: """Pop all items from a dictionary that have keys beginning with a prefix. Parameters ---------- prefix : str kwargs : dict Returns ------- kwargs : dict Items popped from the original directory, with prefix removed...
def get_same_source_meta(pkg_descriptor_elements, source_code): """Grab the the source metadata of the same dataset from all datapackages.""" samezies = [] for sources in pkg_descriptor_elements['sources']: for source in sources: if source['source_code'] == source_code: s...
def evaluate_field(record, field_spec): """ Evaluate a field of a record using the type of the field_spec as a guide. """ if type(field_spec) is int: return str(record[field_spec]) elif type(field_spec) is str: return str(getattr(record, field_spec)) else: return str(fiel...
def initialize_output() -> tuple: """ Sets up structs for ouput. Listed here for visual clarity. Called by manage_generation() controller. """ initialized_output_dct = { 'meta': { 'date_produced': None, 'elapsed_time': None, 'referents_count': None, ...
def flatten_list(lol, max_deg=1): """ recursively flatten list into single depth list. """ flat_list = [] for item in lol: if hasattr(item, '__iter__') and max_deg > 0: flat_list += flatten_list(item, max_deg-1) else: flat_list.append(item) return flat_list
def tuplemut(tpl, val, idx): """ Return a tuple with *idx* changed to *val* """ lst = list(tpl) lst[idx] = val return tuple(lst)
def adjust_functions(content): """ Adds ':' after ')' """ for n,line in enumerate(content): count = 0 if line.strip().startswith('def'): i = line.find('(') if i >= 0: count = 1 for k in range(i,len(line)): #print(k, ...
def my_split(inputdata): """my own split method equal to stirng.split()""" # # Your task is to write your own function, # which behaves almost exactly like the original split() method # 1. it should accept exactly one argument - a string; # 2. it should return a list of words created from the st...
def repeat(s, n): """ (str, int) -> str Return s repeated n times; if n is negative, return empty string. >>> repeat('yes', 4) 'yesyesyesyes' >>>repeat('no', 0) '' """ return (s * n)
def trim_docstring(docstring): """ Uniformly trims leading/trailing whitespace from docstrings. Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation """ if not docstring or not docstring.strip(): return '' # Convert tabs to spaces and split into lines lin...
def add(x, y): """An addition endpoint.""" return {"result": x + y}
def _trim_duplicates(all_matches): """Remove redundant sub-graph matches. Is there a better way to do this? Like when we format the subgraphs, can we impose an ordering so it's easier to eliminate redundant matches? """ trimmed_list = [] for match in all_matches: if ( match ...
def range_generate_doborder(gen, mi, ma): """Uses gen to generate a random number inside [mi, ma]. If it falls out of [mi, ma] bounds, it returns mi or ma, respectively. """ ans = gen() if ans >= ma: return ma if ans <= mi: return mi return ans
def create_pentagon_numbers(limit): """Return a set of pentagon numbers up to limit.""" pentagons = {0} increment = 1 value = 0 while True: value += increment increment += 3 if value > limit: break pentagons.add(value) return pentagons
def unzip(i, iterable): """ Returns the item at the given index from inside each tuple in the list. """ return [x[i] for x in iterable]
def GetModuleName(cvspath): """ get module name from it's cvspath Args : cvspath : module's cvspath Returns : module name """ if cvspath.endswith('/'): cvspath = cvspath[:-1] module_name = cvspath.split('/')[-1] return module_name
def extract_keys(list_of_dicts, *keys): """Turn a lists of dicts into a tuple of lists, with one entry for every given key.""" res = [] for k in keys: res.append([d[k] for d in list_of_dicts]) return tuple(res)
def get_mention_with_fallback(span_start_offset, span_end_offset, mention_set, strict=False): """ http://e-gitlab.bbn.com/text-group/jserif/blob/364-add-event-from-json/serif-util/src/main/java/com/bbn/serif/util/AddEventMentionFromJson.java#L316 http://e-gitlab.bbn.com/text-group/jserif/blob/364-add-event-...
def format_cardinality(left_cardinality, right_cardinality): """Return a string describing the cardinality of the relation.""" cardinality_string = ( ','.join([str(x) for x in left_cardinality]) + ' to ' + ','.join([str(x) for x in right_cardinality]) ) return cardinality_string
def qualify_name(name_or_qname, to_kind): """ Formats a name or qualified name (kind/name) into a qualified name of the specified target kind. :param name_or_qname: The name to transform :param to_kind: The kind to apply :return: A qualified name like: kind/name """ if '/' in name_or_qn...
def Qsub(q1, q2): """ Qsub """ return (q1[0] - q2[0], q1[1] - q2[1], q1[2] - q2[2], q1[3] - q2[3])
def levenshtein(a, b): """Calculates the Levenshtein distance between a and b. The code was copied from: http://hetland.org/coding/python/levenshtein.py """ n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a, b = b, a n, m = m, n current = list(range(n + 1)) for i in range(1, m...
def get_next_version(req_ver, point_to_increment=-1): """Get the next version after the given version.""" return req_ver[:point_to_increment] + (req_ver[point_to_increment] + 1,)
def check_name(str_arg): """ Check the role and feature file name. """ if str_arg == "" or str_arg[0] == "#": return False return True
def dictionary_to_EE_upload_command(d): """ Convert a dictionary to command that can be appended to upload command ------------------------------------------------------------------------------- Args: d (dictionary) : Dictionary with metadata. nodata_value ...
def rgbi2rgbf(rgbf): """Converts a RGB/integer color into a RGB/float. """ return (int(rgbf[0]*255.0), int(rgbf[1]*255.0), int(rgbf[2]*255.0))
def max_value(input_list): """ brief: return the maxValue and the index of this a value of a given list Args: @param input_list : the input list to be scanned Raises: throws an exception (ValueError) when the list is empty Return: The maxValue of a List and the index """ if ...
def filter_names(names, text=""): """ Returns elements in a list that match a given substring. Can be used in conjnction with compare_varnames to return a subset of variable names pertaining to a given diagnostic type or species. Args: ----- names: list of str Input list of ...
def bubble_format(value: int, max_: int, fill_from_right=False): """Returns a bubble string to represent a counter's value.""" used = max_ - value filled = '\u25c9' * value empty = '\u3007' * used if fill_from_right: return f"{empty}{filled}" return f"{filled}{empty}"
def set_input_variable(ctx, var_, config_file_name, default_value): """ Set the variable defined by var_ to one of the following: - Itself if it has a value - The value from the config file if that exists - The default define default_value This sets the order for inputs to: ...
def next_smaller_pow2(n): """Returns the largest power of 2 that is strictly less than n.""" return 1 << ((n - 1).bit_length() - 1)
def removeGameRelations(gtitle: str) -> str: """Return a query to remove all of a game's relations.""" return (f"DELETE FROM appears_in " f"WHERE gtitle='{gtitle}';" )
def MakeCopyBoard(board, size): """Make a copy of the board""" #newlist = a copied list of the current board #row = the current row being added to the list newlist = [] for rows in range(size): row = [] for cols in range(size): row.append(board[rows][cols]) ...
def dict_concat(args): """Concatenates elements with the same key in the passed dictionaries. Parameters ---------- args : sequenece of dict Dictionaries with sequences to concatenate. Returns ------- dict The dictionary with the union of all the keys of the dictionaries ...
def get_section_syntax_indicator(data): """Get the section syntax indicator from the given section data Parses the given array of section data bytes and returns the section syntax indicator. If True, then this is an extended table. If False then it is a simple section. """ if data[1] & int('10000000', 2): return...
def topo_sort(items): """ Topological sort with locality Sorts a list of (item: (dependencies)) pairs so that 1) all dependency items are listed before the parent item, and 2) dependencies are listed in the given order and as close to the parent as possible. Returns the sorted list of items and a li...
def cut(code,p): """ cut message into p lists (extension of the "oddEven" function) in : code (str) > message you want to cut, p (int) number of list you want out : d (list of list) > list containing the p list you just cut >>>cut("abcabcabc", 3) [["a","a","a"], ["b","b","b"],["c","c","c"]] ...
def separate_ccds(cubes: list) -> tuple: """Return a tuple of six values, either HiColorCubes, or None.""" red4 = red5 = ir10 = ir11 = bg12 = bg13 = None for c in cubes: if c.ccdnumber == "4": red4 = c elif c.ccdnumber == "5": red5 = c elif c.ccdnumber == "10"...