content
stringlengths
42
6.51k
def subset_or_none(dict1: dict, dict2: dict) -> dict: """ If the keys of dict2 are a subset of the keys of dict1, return a copy of dict1 updated with the values of dict2, otherwise return an empty dict of the same type as dict1 """ new_dict = dict1.copy() new_dict.update(dict2) if new_di...
def get_bracket_depth(idx, left_bracket_indices, right_bracket_indices): """ Get the bracket depth of index idx. Args: idx (int): the index. left_bracket_indices (list[int]): the left bracket index list. right_bracket_indices (list[int]): the right bracket index list. Returns: ...
def get_random_string(size=32): """Creates a random (hex) string which contains 'size' characters.""" return ''.join("{0:02x}".format(b) for b in open('/dev/urandom', 'rb').read(int(size/2)))
def generate_otp(label, user, key): """Generates a otpauth:// URI""" return "otpauth://totp/%s:%s?secret=%s&issuer=%s" % (label,user,key,label)
def remove_empty(d): """ Helper function that removes all keys from a dictionary (d), that have an empty value. """ for key in d.keys(): if not d[key]: del d[key] return d
def ensure_list(var): """Converts to a list, safely""" if isinstance(var, str): return [var] return var
def _parse_directories(dir_list): """Helper function for parsing and cleaning a list of directories for analysis. :param list[str] dir_list: A list of directories to parse. :rtype: list[str] :return: The cleaned up list of directories. """ return [line for line in dir_list if line is not None]
def _solution_to_selection(collector, solution_index, flat_vars, flat_vars_inverse, n_courses): """ Given a solution found by the solver, extract the list of indices of selected options. Specifically, if selection[i]=j, the j-th option of the i-th course was selected, selection[i]=None if the course was...
def _global_to_local_key_slice(global_key, globalshape, local_to_global_dict, axis=0): """ Helper method to process slice keys """ if global_key == slice(None): return global_key if local_to_global_dict is None: return global_key global_start, global_stop,...
def recursive_update(to_update, update): """ Recursively updates nested directories. Args: to_update (dict or collections.Mapping): dict to update. update (dict or collections.Mapping): dict containing new values. Returns: dict: to_update """ if ...
def is_summable(num1, num2): """ If two numbers can be summed in a needed way. Examples ----- 9000 80 -> True (9080) 20 30 -> False (20 30) 1 2 -> False (1 2) 2 1 -> False (2 1) 20 1 -> True (21) ----- """ if num1 == 10 or num2 == 0: return False place = len(...
def _FormatBytes(byts): """Pretty-print a number of bytes.""" if byts > 2**20.0: byts /= 2**20.0 return '%.2fm' % byts if byts > 2**10.0: byts /= 2**10.0 return '%.2fk' % byts return str(byts)
def without_fixed_prefix(form, prefix_length): """ Return a new form with ``prefix_length`` chars removed from left """ word, tag, normal_form, score, methods_stack = form return (word[prefix_length:], tag, normal_form[prefix_length:], score, methods_stack)
def probably_reconstruction(file) -> bool: """Decide if a path may be a reconstruction file.""" return file.endswith("json") and "reconstruction" in file
def viz_b(body): """Create HTML b for graphviz""" return '<B>{}</B>'.format(body)
def get_mouse_pos(mouse_pos, rows, width): """ Return the cell that has been clicked on with the mouse. params: mouse_pos (int, int): position of the cursor rows (int): number of rows in the grid width (int): width of the scren return: row, col (int, int): coordin...
def filter_colons(part): """Funtion to filter out timestamps (e.g. 08:30) and websites (e.g. http://site.com)""" new_parts = [] split_part = part.split(':') for idx in range(0, len(split_part)): if idx == 0: new_parts.append(split_part[idx]) elif split_part[idx][0].isalpha(...
def get_date_shortcode(date_str): """ Get shortcode for the standard date strings, to use in submodel names """ if date_str == "std_contest": return "SC" elif date_str == "std_contest_daily": return "SCD" elif date_str == "std_future": return "SF" elif date_str == "st...
def age_similarity_scorer(age_1, age_2): """Compares two ages, returns 0 if they match, returns penalty of -1 otherwise. Conservative assumptions: 1) If age cannot be cleanly cast to int, consider comparators to be a match 2) If ages are within 2 years, consider comparators to be a match ...
def easy_iseven(x): """Takes a number and returns True if it's even, otherwise False""" return x % 2 == 0
def _flatten(indices) -> tuple: """Return a flat tuple of integers to represent the indices. Slice objects are not hashable, so we convert them. """ result = [] for x in indices: if isinstance(x, slice): result.extend([x.start, x.stop, x.step]) else: result.a...
def int_to_bytes(integer_value: int) -> list: """ Converts a single integer number to an list with the length 2 with highest byte first. The returned list contains values in the range [0-255] :param integer: the integer to convert :return: the list with the high byte first """ if not (is...
def find_sigfigs(text): """Parse through a snippet of text that states what the values are in.""" text = text.lower() if text.find('million') != -1: text = 'million' return text elif text.find('thousand') != -1: text = 'thousand' return text elif text.find('billion') ...
def permutations(l): """ Return all the permutations of the list l. Obivously this should only be used for extremely small lists (like less than 9 members). Paramters: l - list to find permutations of Return value: list of lists, each list a permutation of l. """ if len(l) ...
def test_string_content(string): """Detects if string is integer, float or string. Parameters ---------- string : string An input string to be tested. Returns ------- string A string with value 'int' if input is an integer, 'float' if the input is a float an...
def bubbleSort_decr1(array): """ It repeatedly swaps adjacent elements that are out of order it has O(n2) time complexity larger numbers are sorted first """ for i in range(len(array)): for j in range(len(array)-1,i,-1): if array[j-1] < array[j]: array[j], array[j-1] = array[j-1], array[j] return arr...
def title(name, code): """ Build a new valid title route for the rickroll > http://rr.noordstar.me/ef8b2bb9 > http://rr.noordstar.me/the-title-that-emphasizes-your-point-well-ef8b2bb9 These are interpreted the same way. """ url = "" for char in name: char = cha...
def filter_empty_layer_containers(layer_list): """Filter out nested layers from containers.""" existing = set() to_visit = layer_list[::-1] filtered = [] while to_visit: obj = to_visit.pop() obj_id = id(obj) if obj_id in existing: continue existing.add(obj...
def find_duckling_conflict_queries(duckling_outputs): """ Finds queries where duckling predicts multiple entities for the SAME span :param duckling_outputs: PARSED duckling responses, dicts from dimension to a dict mapping tuple spans to values :return: """ conflict_responses = {} for i, re...
def running_mean(mylist, N): """ return the list with a running mean acroos the array, with a given kernel size @param mylist array,list over which to average @param value length of the averaging kernel """ cumsum, moving_aves = [0], [] for i, x in enumerate(mylist, 1): cumsum...
def MapLines(f, s): """Apply a function across each line in a flat string. Args: f: A string transform function for a line. s: A string consisting of potentially multiple lines. Returns: A flat string with f applied to each line. """ return '\n'.join(f(line) for line in s.split('\n'))
def get_lang_probability(lang_prob): """ Takes a string with the format lang:probability and returns a tuple (lang, probability) Args: lang_prob: str """ lang, probability = lang_prob.split(":") try: probability = float(probability) except Exception as e: print(...
def ij_to_list_index(i, j, n): """ Assuming you have a symetric nxn matrix M and take the entries of the upper triangular including the diagonal and then ravel it to transform it into a list. This function will transform a matrix location given row i and column j into the proper list index. :param i...
def format_data_ascii(data): """Try to make an ASCII representation of the bytes. Non printable characters are replaced by '?' except null character which is replaced by '.'. """ msg_str = '' for byte in data: char = chr(byte) if char == '\0': msg_str = msg_str + '.'...
def bool2yn(b): """Helper function, returns \"yes\" if *b* is True, \"no\" if *b* is False.""" return ["no", "yes"][b]
def moveDWValues(tokens: list) -> list: """ Takes sanitised, tokenised URCL code. Returns URCL code with all DW values moved to the end. """ DWValues = [] index = 0 while index < len(tokens): line = tokens[index] if line[0] == "DW": DWValues.append(...
def url_join(*parts: str) -> str: """ Join the different url parts with forward slashes. """ return "/".join([part.strip("/") for part in parts]) + ("/" if parts and parts[-1].endswith("/") else "")
def map_box(sbox, dbox, v): """ sbox is (lat1, lat2, long1, long2), dbox is (x1, x2, y1, y2), v is (lat, long). result is (x, y) """ xscale = abs(dbox[1]-dbox[0])/abs(sbox[3]-sbox[2]) yscale = abs(dbox[3]-dbox[2])/abs(sbox[1]-sbox[0]) x = (v[1]-sbox[2]+dbox[0])*xscale y = (v[0]-...
def options_from_form(spawner, formdata): """Extract the passed form data into the self.user_options variable.""" options = {} if formdata.get('is_custom_image', ["off"])[0] == "on": options["image"] = formdata.get('custom_image', [None])[0] else: options["image"] = formdata.get('define...
def make_region(chromosome, begin, end): """ Create region string from coordinates. takes 2 (1 for human 1-9) digit chromosome, begin and end positions (1 indexed)""" region = "chr" + str(chromosome) + ":" + str(begin) + "-" + str(end) return region
def cve_is_about_system(cpe_type): """ Determines whether CVE is about system. :param cpe_type: One of {'a', 'o', 'h'} = application, operating system, hardware :return: true if CVE is about system. """ return ('o' in cpe_type or 'h' in cpe_type) and 'a' not in cpe_type
def round_float_math(number: float) -> int: """ Unified rounding in all python versions. Parameters: ---------- number : float Input number. Returns: ------- int Output rounded number. """ if abs(round(number) - number) == 0.5: return int(2.0 * round(0.5...
def get_sample_t(ref_t, idx, num_samples, sr): """ Calculates Unix time for individual sample point (within a record). The sample point time is calculated by subtracting a multiple of 1/sr from the reference time corresponding to the final sample point in the record, where sr is the sample rate. ...
def standardise_signal_pattern(signal_pattern: str) -> str: """ Sorts the letters in the given signal pattern alphabetically """ return "".join(sorted(signal_pattern))
def process_procedure(procedure): """ Cleans and sets new style division for calculations procedures. Used by both the :view:`qa.perform.Upload` & :view:`qa.perform.CompositeCalculation` views. """ return "\n".join([procedure, "\n"]).replace('\r', '\n')
def divup(x: int, y: int) -> int: """Divide x by y and round the result upwards.""" return (x + y - 1) // y
def can_semnops(f): """ checks if function has any semnops that can be replaced """ if hasattr(f, 'displaced_bytes'): return True return False
def get_linked_to_dff_skills(dff_shared_state, current_turn, prev_active_skill): """Collect the skill names to turn on (actually this should be the only skill because active skill is the only) which were linked to from one dff-skill to another one. Returns: list of skill names to turn on ""...
def getdtype(real, logical): """ Converts a (real, logical) pair into one of the three types: 'real', 'complex' and 'binary' """ return "binary" if logical else ("real" if real else "complex")
def create_C1(data_set): """ Create frequent candidate 1-itemset C1 by scaning data set. Args: data_set: A list of transactions. Each transaction contains several items. Returns: C1: A set which contains all frequent candidate 1-itemsets """ C1 = set() for t in data_set: ...
def nullable_string_tuple_to_string_array(nullable_string_tuple): """ Converts a nullable string tuple to an array representing it. Parameters ---------- nullable_string_tuple : `None` or `tuple` of `str` The value to convert. Returns ------- array : `list` of `str` ...
def Interpolate(a, b, p): """\ Interpolate between values a and b at float position p (0-1) """ return a + (b - a) * p
def gray_code(n: int): """Problem 48: Gray Code. Parameters ---------- n : int The number of Returns ------- """ gray_code_list = ['0', '1'] if n == 1: return gray_code_list for i in range(0, n - 1): # Prefix list elements with '0' gray_code_left = ['0' + x for x in gray_code_list] gray_code_lis...
def add_leading_zeros(input_string: str, out_len: int) -> str: """This function adds leading zeros to the input string. The output string will have length == out_len Args: input_string (str): the input string out_len (int): length of output string with leading zeros Returns: out_stri...
def lowercase(text): """Converts all text to lowercase""" return text.lower()
def get_gene_palette(num_cls=182): #Ref: CCNet """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_cls palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] =...
def _update_link(link): """The database contains links in the format 'http://leafe.com/download/<fname>'. I want this to be more explicit by specifying the link as '/download_file/<fname>', so this function does that. When I convert the site to use exclusively this newer code, I can update the datab...
def calc_check_digit(number): """Calculate the check digit.""" # Old NIT if number[10:13] <= '100': weights = (14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2) total = sum(int(n) * w for n, w in zip(number, weights)) return str((total % 11) % 10) # New NIT weights = (2, 7, 6, 5, 4...
def check_game_status(board): """Return game status by current board status. Args: board (list): Current board state Returns: int: -1: game in progress 0: draw game, 1 or 2 for finished game(winner mark code). """ for t in [1, 2]: for j i...
def IsResultFailure(result_data): # pragma: no cover """Returns true if result_data indicates a failure.""" while isinstance(result_data, list): result_data = result_data[0] if not result_data: return False # 0 means SUCCESS and 1 means WARNINGS. return result_data not in (0, 1, '0', '1')
def get_file_content_type(extension): """ :param string extension: file extension :returns string: mime type based on file extension """ try: mime_types = { 'docx': 'application/vnd.openxmlformats-officedocument' '.wordprocessingml.document', 'xls...
def evenFibSum(limit): """Sum even Fib numbers below 'limit'""" sum = 0 a,b = 1,2 while b < limit: if b % 2 == 0: sum += b a,b = b,a+b return sum
def find_id(list, type): """Find id of given type in pubmed islist""" matches = [x for x in list if x['idtype'] == type] if matches: return matches[0]["value"] else: raise KeyError("Id of type '" + type + "' not found in idlist.")
def metric(grams): """ Converts grams to kilograms if grams are greater than 1,000. """ grams = int(grams) if grams >= 1000: kilograms = 0 kilograms = grams / 1000.0 # If there is no remainder, convert the float to an integer # so that the '.0' is removed. if not (gra...
def helper(n, big): """ :param n: int, an integer number :param big: the current largest digit :return: int, the final largest digit """ n = abs(n) if n == 0: return big else: # check the last digit of a number if big < int(n % 10): big = int(n % 10) # check the rest of the digits return helper(n/1...
def _truncate_bitmap(what): """Determine the index of greatest byte that isn't all zeros, and return the bitmap that contains all the bytes less than that index. """ for i in range(len(what) - 1, -1, -1): if what[i] != 0: return what[0: i + 1] return what[0:1]
def AmbiguousCst(cst_lst): """ Returns properly formated string for declaring ambiguous constraints, it takes a list of Rosetta-formated constraints string. """ header = 'AmbiguousConstraint\n' for cst in cst_lst: header += cst header += 'END_AMBIG...
def check_in_field(pos, field_config): """ Return flag to indicate whether the object is in the field """ k1 = field_config['borderline'][0] k2 = field_config['borderline'][1] b = field_config['borderline'][2] flag = k1 * pos[0] + k2 * pos[1] + b > 0 return flag
def expand_comma(value): """ Adds a space after each comma, to allow word-wrapping of long comma-separated lists.""" return value.replace(",", ", ")
def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (iterable of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions ...
def appstruct_to_inputs(request, appstruct): """ Transforms appstruct to wps inputs. """ # LOGGER.debug("appstruct=%s", appstruct) inputs = [] for key, values in list(appstruct.items()): if key in ['_async_check', 'csrf_token']: continue if not isinstance(values, list...
def asplit(string:str, number=2) -> list: """ Splits a string ever n characters -> default is 2 """ return [string[i:i+number] for i in range(0, len(string), number)]
def load_txs(file): """ Load tsv format TXS annotation Args: file (str): TXS file Returns: list: TXS list """ if not file: return list() with open(file, "r") as f: txs_text = f.readlines() txs_data = list(map(lambda x: x.rstrip("\n").split("\t"), txs_...
def pluralize(value: int, noun: str) -> str: """Pluralize a noun.""" nouns = {"success": "successes", "die": "dice"} pluralized = f"{value} {noun}" if value != 1: if noun in nouns: pluralized = f"{value} {nouns[noun]}" else: pluralized += "s" return pluraliz...
def add_content_in_dict(sample_dict, key, list_of_values): """Append multiple values to a key in the given dictionary""" if key not in sample_dict: sample_dict[key] = "" sample_dict[key]=(list_of_values) # because it initializes, it replaces the first key value pair return sample_dict
def _error_connection_handler(sock, client_addr, header): """ utility handler that does nothing more than provide a rejection header @param sock: socket connection @type sock: socket.socket @param client_addr: client address @type client_addr: str @param header: request header @type h...
def to_bits(cs): """Split a string into a list of numeric and non-numeric substrings.""" if not cs: return [] out = [] tmp = "" is_number = True first = True for c in cs: if c in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: if is_number: t...
def get_gcd(a, b): """ The GCD (greatest common divisor) is the highest number that evenly divides both width and height. """ return a if b == 0 else get_gcd(b, a % b)
def pad_or_truncate(to_pad, length): """ Truncate or pad (with zeros) a GT text field :param to_pad: text to pad :type to_pad: either string or bytes :param length: grow or shrink input to this length ("Procrustean bed") :type length: int :return: processed text field :rtype: """ ...
def mb_bl_ind(tr1, tr2): """Returns the baseline index for given track indices. By convention, tr1 < tr2. Otherwise, a warning is printed, and same baseline returned. """ if tr1 == tr2: print("ERROR: no baseline between same tracks") return None if tr1 > tr2: print("WARN...
def get_lock_status_flags(lock_status_value): """ Decode a lock status value provided as a hex string (like '0880'), returning an array of strings representing the parsed bits into textual described flags. """ flags = [] try: status_value = bytearray.fromhex(lock_status_value) if not status_value:...
def max_pairwise_product(numbers): """ max_pairwise_product gets the two biggest numbers and returns the product of them TimeComplexity: O(n) """ biggest = -9999999999999 second_bigest = -9999999999999 for ele in numbers: if ele > biggest: biggest, second_bigest = ele, bi...
def transitionsCount(trans): """Statistic function. Returs the count of the atuomaton transtions. The calculation is done only from the a given transition dictionary. The forward and backward transtion dictionary might coresponded, for better results. Args: trans (dict): Transition dictiona...
def get_test_node(request_or_item): """ Return the test node, typically a _pytest.Function. Provided arg may be the node already, or the pytest request :param request_or_item: :return: """ try: return request_or_item.node except AttributeError: return request_or_item
def valid_sequence(seq): """ Checks if the given sequences if valid. """ for chr in seq: if not (chr == 'A' or chr == 'C' or chr == 'G' or chr == 'T'): return False return True
def first_letter_lower(input_string): """ Returns a new string with the first letter as lowercase :param input_string: str :return: str """ return input_string[:1].lower() + input_string[1:]
def lists_of_series_are_equal(list_of_series_1,list_of_series_2): """Equality test for list of series""" return all([(s1==s2).all() for s1,s2 in zip(list_of_series_1,list_of_series_2)])
def passport_is_valid_1(passport): """ Determines whether a passport is valid or not only checking the presence of the fields. :param passport: passport :return: boolean """ return all(field in passport.keys() for field in ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])
def sifchain_fees(sifchain_fees_int): """returns a string suitable for passing to sifnoded""" return f"{sifchain_fees_int}rowan"
def deep_access(x, keylist): """Access an arbitrary nested part of dictionary x using keylist.""" val = x for key in keylist: val = val.get(key, 0) return val
def bound(x, m, M=None): """ :param x: scalar Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR* have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1]. """ if M is None: M = m[1] m = m[0] # bound x between min (m) and Max (M)...
def reverseListOrder(query): """Reverse the order in a list.""" list_query = list(query) list_query.reverse() return list_query
def get_binary_class(value, thresh=4.0): """ Map a continuous value to a binary classification by thresholding. """ return int(value > thresh)
def _is_valid_ip_address(ipaddr): """ <Purpose> Determines if ipaddr is a valid IP address. 0.X and 224-255.X addresses are not allowed. Additionally, 192.168.0.0 is not allowed. <Arguments> ipaddr: String to check for validity. (It will check that this is a string). <Returns> True if a va...
def project_onto_basis(x, y, z, xx, xy, xz, yx, yy, yz, zx, zy, zz): """Project vector onto different basis. Parameters ---------- x : float or array-like X component of vector y : float or array-like Y component of vector z : float or array-like Z component of vector ...
def print_totals(hist_dict, filename): """ Parameters ---------- hist_dict : Dictionary Histogram dictionary containing number of repeats with certain length. filename : String Output file name. Returns ------- total : Int Total number of repeats ...
def double_number(number): """Multiply given number by 2 :param number: :return: """ print("Inside double_number()") return number * 2
def update_activity(p_dict, slug): """Updates activity by slug""" updated_param = { "name": p_dict["name"] if "name" in p_dict else "Testing Infra", "slug": p_dict["slug"] if "slug" in p_dict else slug, "uuid": "3cf78d25-411c-4d1f-80c8-a09e5e12cae3", "created_at": "2014-04-16", ...
def f1d7p(f, h): """ A highly accurate seven-point finite difference stencil for computing derivatives of a function. """ fm3, fm2, fm1, f1, f2, f3 = [f(i*h) for i in [-3, -2, -1, 1, 2, 3]] fp = (f3-9*f2+45*f1-45*fm1+9*fm2-fm3)/(60*h) return fp
def verify_unit_interval(value): """Throw an exception if the value is not on the unit interval [0,1]. """ if not (value >= 0 and value <= 1): raise ValueError("expected value on the interval [0, 1].") return value