content
stringlengths
42
6.51k
def str_or_none(arg): """Returns None or str from a `str_or_none` input argument. """ if arg is None or str(arg).lower() == 'none': return None return str(arg)
def find_digits_in_str(string: str) -> str: """Find digits in a given string. Args: string: str, input string with the desired digits Returns: digits: str, found in the given string """ return "".join(x for x in string if x.isdigit())
def _set_deferred_timeout(reactor, deferred, timeout): """ NOTE: Make sure to call this only from the reactor thread as it is accessing twisted API. Sets a maximum timeout on the deferred object. The deferred will be cancelled after 'timeout' seconds. This timeout represents the maximum allowed...
def get_index_comma(string): """ Return index of commas in string """ index_list = list() # Count open parentheses par_count = 0 for i in range(len(string)): if string[i] == ',' and par_count == 0: index_list.append(i) elif string[i] == '(': par_coun...
def fhex(x, nDigits=2, prefix="0x", upper=True): """ Returns a hex string of the number `x`, with a fixed number `nDigits` of digits, prefixed by `prefix`. If `upper` is `True`, hex digits are upper-case, otherwise lower-case. >>> fhex(15) '0x0F' >>> fhex(255, 4, "", False) '00ff' ...
def jaro_similarity(s1, s2): """ Computes the Jaro similarity between 2 sequences from: Matthew A. Jaro (1989). Advances in record linkage methodology as applied to the 1985 census of Tampa Florida. Journal of the American Statistical Association. 84 (406): 414-20. The Jaro distance...
def add_position_to_list_token(list_tokens): """add postion of each token in list of token Arguments: list_tokens {list} -- list of token Returns: list -- list of token with postion of each token """ list_tokens_pos = [] postion = 0 for token in list_tokens: list_t...
def split_by_value( total, nodes, headdivisor=2.0 ): """Produce, (sum,head),(sum,tail) for nodes to attempt binary partition""" head_sum,tail_sum = 0,0 divider = 0 for node in nodes[::-1]: if head_sum < total/headdivisor: head_sum += node[0] divider -= 1 else: ...
def string_to_bool(raw_input): """Convert ("True","true","TRUE") to (True)..""" mapping = { "True": True, "False": False, "true": True, "false": False, "TRUE": True, "FALSE": False, } if raw_input in mapping.keys(): return mapping[raw_input] el...
def hash_init(size): """ initialises new hash table INPUTS: size of 1D hash table, int size should be greater than length of data * 2 in order to reduce conflicts OUTPUTS: hash table EXAMPLES: >>> hash_init(); """ #initialise KV = {"key": "", "value": None}; hash =...
def mse(x, x_hats): """Mean squared error (MSE) cost function Args: x: One true value of $x$ x_hat: Estimate of $x$ Returns: ndarray of the MSE costs associated with predicting x_hat instead of x$ """ return (x - x_hats)**2
def get_max_value_key(dic): """ Fast method to get key for maximum value in dict. From https://github.com/nicodv/kmodes """ v = list(dic.values()) k = list(dic.keys()) return k[v.index(max(v))]
def iterative_lcm(x: int, y: int): """determine which is the smaller number among the 2 integer and do a iterative call of lcm % large_number""" if x < y: small = x large = y else: small = y large = x lcm = small while lcm%large !=0: lcm = lcm + small retu...
def make_pair(img_paths, label_paths): """Take a list of image paths and the list of corresponding label paths and return a list of tuples, each containing one image path and the corresponding label path. Arguments: img_paths (list of `Path`): list of paths to images. labels_paths (list of ...
def hex_to_rgb(hex): """ Converts hex to rgb colours Parameters ---------- hex : string 6 characters representing a hex color Returns ------- rgb : tuple (length 3) RGB values References ---------- https://towardsdatascience.com/beautiful-custom-colormaps-w...
def adder(x, y): """Add two numbers together.""" print("INSIDE ADDER!") return x + y
def render_location(data, query): """ location (l) """ return (data['override_location'] or data['location'])
def int_to_rgb(int_): """Integer to RGB conversion""" red = (int_ >> 24) & 255 green = (int_ >> 16) & 255 blue = (int_ >> 8) & 255 return red, green, blue
def getDAPI(filename): """ Simple string manipulation helper method to replace "FITC" with "DAPI" and "Blue" with "UV" of input FILENAME, Returns the modified string """ DAPI = filename.replace("FITC", "DAPI") DAPI = DAPI.replace("Blue", "UV") return DAPI
def _has_endpoint_name_flag(flags): """ Detect if the given flags contain any that use ``{endpoint_name}``. """ return '{endpoint_name}' in ''.join(flags)
def parse_price(params): """ Normalize price. """ params['price'] = int(params['price']) return params
def new_mean_temperature(area, height_external, temperature_external, heat): """ Calculates a new mean temperature for the volume. :param area: in m^2 :param height_external: in m :param temperature_external: in K :param heat: in J :return: temperature in K """ volume_air = area * h...
def chunk_sequence(sequence, chunk_length, allow_incomplete=True): """Given a sequence, divide it into sequences of length `chunk_length`. :param allow_incomplete: If True, allow final chunk to be shorter if the given sequence is not an exact multiple of `chunk_length`. If False, the incom...
def sanitize_input(data): """Sanitizes input for reddit markdown tables""" data = data.replace('|', '&#124;') data = data.replace('\n', '') data = data.replace('*', '\\*') return data
def transform(subject: int, loop_size: int) -> int: """Transform the ``subject`` in ``loop_size`` steps of a hard-coded algorithm.""" value = 1 for _ in range(loop_size): value *= subject value %= 20201227 return value
def remove_prefix(s, pre): """ Remove prefix from the beginning of the string Parameters: ---------- s : str pre : str Returns: ------- s : str string with "pre" removed from the beginning (if present) """ if pre and s.startswith(pre): return s[len(pre):] ...
def accuracy(a, b): """Function to return accuracy based on 10% difference""" scale = a * 0.1 if b <= a + scale and b >= a - scale: return 1 else: return 0
def flatten_bookmarks(bookmarks, level=0): """Given a list, possibly nested to any level, return it flattened.""" output = [] for destination in bookmarks: if type(destination) == type([]): output.extend(flatten_bookmarks(destination, level+1)) else: output.append((de...
def set_id(project_id, entity, args): """ :param project_id: :param entity: :param args: :return: """ entity["_id"] = str(project_id) + "-" + str(entity[args.get('id')]) return entity
def quantile(x,quantiles): """ Calculates quantiles - taken from DFM's triangle.py """ xsorted = sorted(x) qvalues = [xsorted[int(q * len(xsorted))] for q in quantiles] return list(zip(quantiles,qvalues))
def solution(nums: list) -> list: """ This function sorts the passed in array of numbers. """ if nums is None: return [] return sorted(nums)
def recursive_walker(tree, level=0, handlers=[], verbose=True): """recursive walker Recursively walk any tree-like structure such as dictionaries and lists. Common use cases are json or xml data. Arguments: - tree(dict): the tree to walk as dict - level(int): recursion depth information - ...
def find(element, JSON, path=None, all_paths=None, mutable=False): """Get paths to a value in JSON data. Usage: find(value, data) """ all_paths = [] if all_paths is None else all_paths path = tuple() if path is None else path if isinstance(JSON, dict): for key, value in JSON.items(): ...
def _shell_quote(s): """Copy of bazel-skylib's shell.quote. Quotes the given string for use in a shell command. This function quotes the given string (in case it contains spaces or other shell metacharacters.) Args: s: The string to quote. Returns: A quoted version of the string t...
def sensorOptimizer(horizontal, vertical, imageSize): """ Checks and adjusts a source image sensor size for compatiabilty with given image dimensions. Args: horizontal (float): sensor width in mm vertical (float): sensor height in mm imageSize (x,y): dimensions of given images in px...
def exp(x, epsilon=1e-16, maxiter=100): """ Computes an approximation of exp(x) using its series.""" epsilon = epsilon * x # relative precision nbiter = 1 exp_x = 1.0 x_power_n = x factorial_n = 1.0 delta_exp_x = x_power_n / factorial_n while delta_exp_x > epsilon and nbiter < maxiter: ...
def calculate_mturk_cost(payment_opt): """MTurk Pricing: https://requester.mturk.com/pricing 20% fee on the reward and bonus amount (if any) you pay Workers. HITs with 10 or more assignments will be charged an additional 20% fee on the reward you pay Workers. Example payment_opt format for paying r...
def merge_two_sorted_lists(list_1, list_2): """ Purpose: Merge two sorted lists into one sorted list Args: list_1 (List): Sorted List to Merge list_2 (List): Sorted List to Merge Returns: sorted_list (List): Merged Sorted List """ sorted_list = [] list_1_idx,...
def getid(obj): """ Abstracts the common pattern of allowing both an object or an object's ID as a parameter when dealing with relationships. """ try: return obj.id except AttributeError: return obj
def virtualTemperature(T,r): """ """ return T*(0.622+r)/(0.622*(1+r))
def tuple_in_group_with_wildcards(needle, haystack): """Checks if needle is in haystack, allowing for wildcard components. Returns True if either needle or haystack is None, or needle is in haystack. Components in haystack are tuples. These tuples can have entries equal to None which serve as wildcard componen...
def _dedupe_preserve_order(seq): """De-dupe a list, but preserve order of elements. https://www.peterbe.com/plog/uniqifiers-benchmark """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def canonical_gpu_indices(indices): """ If ``indices`` is not None, cast it to list of int. """ if isinstance(indices, str): return [int(idx) for idx in indices.split(',')] if isinstance(indices, int): return [indices] return indices
def augmentTermList(terms): """ Adds additional spellings and plurals to a list of cancer terms Args: terms (list of strings): List of strings of terms Returns: list of augmente strings """ # Lower case everything (if not already done anyway) terms = [ t.lower() for t in terms ] # A list of short c...
def _manhattan_distance(x0: float, y0: float, x1: float, y1: float) -> float: """Get manhattan distance between points (x0, y0) and (x1, y1).""" return abs(x0 - x1) + abs(y0 - y1)
def _bounded(original, default, maximum): """Makes sure a value is within bounds""" # If "original" comes from command line, it may be a string try: value = int(original) except ValueError: value = 0 # Check bounds if value < default: value = default if value > maximu...
def solver_problem2(position): """input position and return min fuel cost of alignment with linear costs""" min_fuel = float("Inf") for i in range(min(position), max(position)): dist = [0] * len(position) dist = [ abs(position[j] - i) * (abs(position[j] - i) + 1) // 2 ...
def extract_epoch(filename): """ Get the epoch from a model save string formatted as name_Epoch:{seed}.pt :param str: Model save name :return: epoch (int) """ if "epoch" not in filename.lower(): return 0 epoch = int(filename.lower().split("epoch_")[-1].replace(".pt", "")) retur...
def linear_search(array, n): """ - Definition - In computer science, linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. Line...
def checkdms(dms): """Verify a sexagesimal string; returns True if valid, False if not """ assert isinstance(dms, str) try: d=dms.split(':') for i in range(3): float(d[i]) return True except: return False
def _is_list(s): """Check a value is a CSV list.""" if s[0] == '[' and s[-1] == ']': return True else: return False
def pad(T, count): """Returns a 64-bit block padded to 8 bytes with PKCS#5 padding. pad assumes that its input is a byte array of length 8 and an integer between 1 and 8. The last count bytes of the array are assumed empty and will be overwritten with a byte representation of count. Some basic sani...
def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ # Your code here dicHelp = {} for item in L: if item in dicHelp.keys(): dicHelp[it...
def problem_19_2(table): """ Design an algorithm to figure out if someone has won in a game of tic-tac-toe. Complexity: O(n^2) Args: table: list of list, dimentions NxN, filled with 1s and 0s Returns: boolean, True if 1 wins or False if 0 wins. """ n = len(table) sum_col...
def buble_sort_naive(l): """ We start with this naive approach that just check if element close by and update the boolean variable and swap accondingly The complexity of this algorithm is O(n^2) """ swap = True while swap: swap = False for i in range(len(l)-1): ...
def sanitize_fb_return_data(results): """ sometimes integers are returned as string try to sanitize this a bit """ return_results = {} for instance in results: # turn None => 0 if results[instance] is None: return_results.update({instance: 0}) else: ...
def test_progress(arg1, arg2, kwd1, kwd2, progress): """Simple test target for submit_progress.""" return arg1, arg2, kwd1, kwd2
def in_festival(fest_coord, approx_loc, radius): """ # Calculates the distance between two coordinates # using the distance formula. Returns true if distance # is less than or equal to the given radius # (festival is in GPS radius). >>> in_festival([1,2], [2,4], 2) False >>> in_festival...
def deslugify(slug): """Turn a slug into human speak""" return slug.replace('-', ' ').title()
def addElementwiseListArray(list1, list2): """ Add together the arrays of two lists (takes the length of the list1) """ l3 = [] for i in range(len(list1)): l3.append(list1[i] + list2[i]) return l3
def _cal_output_shape(height, width, kernel_shape, strides, pad): """ Args: kernel_shape: [height, width] strides: [height, width] pad: 'SAME' or 'VALID' Returns: output_shape: [output_h, output_w] """ # check the options of padding if (pad != 'SAME' and pad != 'VALID'): raise Exception("the optio...
def mymap(x, r1, r2, s1, s2): """ Map x from range (r1, r2) to (s1, s2) """ rs = r2 - r1 ss = s2 - s1 return (x - r1)/rs * ss + s1
def _build_extended_bounds(from_ms=None, to_ms=None): """ Build extended_bounds """ bounds = {} if from_ms is not None: bounds['min'] = from_ms if to_ms is not None: bounds['max'] = to_ms return bounds
def kaiser_beta(a): """Compute the Kaiser parameter `beta`, given the attenuation `a`. Parameters ---------- a : float The desired attenuation in the stopband and maximum ripple in the passband, in dB. This should be a *positive* number. Returns ------- beta : float ...
def convert_indices_to_mesh_faces(indices, mesh): """ Given a list of indices convert them to the names of faces. """ faces = [] for index in indices: faces.append('%s.f[%s]' % (mesh, index)) return faces
def tint_green(text: str) -> str: """Tints a given text green. :param text: The text to be tinted :type text: str :returns: The same text but tinted green :rtype: str """ return ("\x1b[32m%s\x1b[0m" % text)
def cycle_prev(id,cycle_length): """ computes the previous id in a cycle Parameters ---------- id : integer The index of an item in the cycle. cycle_length : integer The length of the cycle. Returns ------- integer The index of the previous item in the cycle...
def check_meta_result(result, expected_value=None): """Check the result of a 'get' metadata operation """ if not isinstance(result, dict): return "pwrcmd output is not a dict" # Some errors return only the error itself if result['PWR_ReturnCode'] != 0 and "value" not in result: retur...
def which(program): """ Test to make sure that the program is executable """ import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: ...
def value(tab, i): """Return 3 digit value starting at position i[index starts from 1].""" return tab[i - 1] * 100 + tab[i] * 10 + tab[i + 1]
def _strip_tex_contents(lines, end_str): """Removes everything after end_str.""" for i in range(len(lines)): if end_str in lines[i]: if '%' not in lines[i]: return lines[:i + 1] elif lines[i].index('%') > lines[i].index(end_str): return lines[:i + 1] return lines
def unicode_str(string): """Converts a bytestring to a unicode string""" try: value = string.decode('utf-8') except AttributeError: value = string return value
def plural(items_or_count, singular: str, count_format='') -> str: """Returns the singular or plural form of a word based on a count.""" try: count = len(items_or_count) except TypeError: count = items_or_count num = f'{count:{count_format}}' if singular.endswith('y'): ret...
def _parser_choose_help(alt_words, index): """Take all the remain Word's as help (and respect Space's inside the Word's)""" help_tail = " ".join(alt_words[index:]) if not alt_words[index:]: help_tail = " ".join(_.lstrip("-") for _ in alt_words[:index]) help_tail = help_tail.replace("[", "")...
def list_contains(list1, list2): """Return True if any item in `list1` is also in `list2`.""" for m in list1: for n in list2: if n == m: return True return False
def _update_schema_1_to_2(table_metadata, table_path): """ Given a `table_metadata` of version 1, update it to version 2. :param table_metadata: Table Metadata :param table_path: [String, ...] :return: Table Metadata """ table_metadata['path'] = tuple(table_path) table_metadata['schema...
def validate_budget(data): """Validate budget input.""" errors = [] savings = data.get("savings") if savings and not 0 <= savings <= 100: errors.append("Savings is out of range.") income = data.get("income") if income and income < 0: errors.append("Income must be positive.") ...
def TYPE(expression): """ Returns a string that specifies the BSON type of the argument. See https://docs.mongodb.com/manual/reference/operator/aggregation/type/ for more details :param expression: The expression or variable :return: Aggregation operator """ return {'$type': expression}
def _BackendsToCell(backend_service): """Comma-joins the names of the backend services.""" return ','.join(backend.get('group') for backend in backend_service.get('backends', []))
def url_builder(cid, university): """Build URL for employee scraping.""" url_search_base = 'https://www.linkedin.com/search/results/people/?' url_search_people_company = '%sfacetCurrentCompany=["''%s''"]&page=' % (url_search_base, cid) url_search_people_university = '%s&facetSchool=["''%s''"]&origin=FAC...
def xor_hashes(*elements: object) -> int: """Combine all element's hashes with xor """ _hash = 0 for element in elements: _hash ^= hash(element) return _hash
def drain_semaphore_filename(component: str) -> str: """Obtain the canonical drain semaphore filename for the specified component name.""" return f".lta-{component}-drain"
def is_pysource(fname): """A file name is a python source file iff it ends with '.py' and doesn't start with a dot. """ return not fname.startswith('.') and fname.endswith('.py')
def add_session_message_padding(data: bytes, length): """Adds the custom padding that Session delivered the message with (and over which the signature is written). Returns the padded value.""" if length > len(data): data += b'\x80' + b'\x00' * (length - len(data)) return data
def get_github_headers(api_token): """ Load GH personal access token from file. """ gh_headers = {"AUTHORIZATION": f"token {api_token}"} return gh_headers
def decoupParagraphEnPhrases(paragraph): """returns the paragraph splited in phrases ignoring specifics titles. To be completed""" import re finsDePhrase = re.compile(r""" # Split sentences on whitespace between them. (?: # Group for two positive lookbehinds. (?<=[.!?...
def my_trim_whitespace(s): """ Returns a string that has at most one whitespace character between non-whitespace characters. >>> trim_whitespace(' hi there') 'hi there' """ buffer = '' for i, letter in enumerate(s): if letter.isspace(): try: if s[i +...
def compute_unique_count_drift(df_prob, ref_df_prob): """Find the difference in unique counts of two distributions and return as percentage""" df_diff = set(df_prob.keys()) - set(ref_df_prob.keys()) ref_df_diff = set(ref_df_prob.keys()) - set(df_prob.keys()) return sum([df_prob[k] for k in df_diff] + ...
def fibonacci_original(n): """calculates the fibonacci sequence Args: n (int): number to checvk Returns: int: value of fib """ if n == 1: return 1 elif n == 2: return 1 elif n > 2: return fibonacci_original(n - 1) + fibonacci_original(n - 2)
def relativize_paths(root, paths): """ Take a list of fully-qualified paths and remove the root, thus making them relative to something. """ clean_paths = [] for path in paths: clean_paths.append(path.replace("%s/" % root, '')) return clean_paths
def col_index_list(info, key, value): """Given a list of dicts 'info', return a list of indices corresponding to columns in which info[key] == value. Use to build lists of default columns, non-exportable columns, etc.""" index_list = list() if info != None: for i in range(0, len(info)): ...
def cal_width(value, max): """Get width >>> cal_width(70, 100) 140.0 """ if not value or not max: return "None" width = (value / float(max)) * 200 return width
def first_is_not(l, v): """ Return first item in list which is not the specified value. If all items are the specified value, return it. Parameters ---------- l : sequence The list of elements to be inspected. v : object The value not to be matched. Example: -------...
def get_scale_for_nth_feature_map(k, m=4, scale_min=0.1484375, scale_max=0.75): """Calculating scale value for nth feature map using the given method in the paper. inputs: k = nth feature map for scale calculation m = length of all using feature maps for detections, 6 for ssd300, 4 for blazeface...
def _has_balanced_parens(rhs): """Returns True if all '(' precede and are followed by a correspoding ')'.""" open_parens = 0 for token in rhs: for char in token: if char == "(": open_parens += 1 elif char == ")": open_parens -= 1 if open_parens < 0: return False ret...
def hexStringToRGB(hex): """ Converts hex color string to RGB values :param hex: color string in format: #rrggbb or rrggbb with 8-bit values in hexadecimal system :return: tuple containing RGB color values (from 0.0 to 1.0 each) """ temp = hex length = len(hex) if temp[0] == "#": ...
def sum_of_years_digits(year): """Calculate the sum of years' digits. Arguments: year (``int``): The year to calculate up to. Returns: int: The sum of years' digits. """ if year <= 0: return 0 return year + sum_of_years_digits(year-1)
def estimate_reading_time(text): """Estimates the time needed for a user to read a piece of text This is assuming 0.9 seconds to react to start reading plus 15 chars per second to actually read the text. Parameters ---------- text : str The text the reading time should be estimated for...
def filter(key: str, value: str, index: dict): """Filter index by key value pair""" return [i for i in index if i.get(key) == value]
def byte_ord(b): """ Return the integer representation of the byte string. This supports Python 3 byte arrays as well as standard strings. """ try: return ord(b) except TypeError: return b