content
stringlengths
42
6.51k
def insert_underscores(in_str): """ Return the argument separating with '_' on each 4 characters form the head """ new_str = "" for i in range(0, len(in_str), 4): new_str = new_str + in_str[i:i + 4] + ('_' if i != len(in_str) - 4 else '') return new_str
def is_list_empty(in_list): """Check if a list is empty ref: https://stackoverflow.com/questions/1593564/python-how-to-check-if-a-nested-list-is-essentially-empty""" if isinstance(in_list, list): # Is a list in_list = [x for x in in_list \ if x != ''] # remove empty strings ...
def _GetValue(skey, tlist): """Get data for subfield code skey, given the subfields list.""" for (subkey, subval) in tlist: if skey == subkey: return subval return None
def _qif_header_and_transactions_to_contents(header, transactions): """Given a QIF header block and a list of transaction blocks, combine into one text block.""" return header + '\n' + ''.join([t + '\n^\n' for t in transactions])
def edit_initiator_keys(host_initiators, include_key_list): """ For each host initiator, remove keys not in the include_key_list. For FCs, add a long address. This is the address with colons inserted. Return the edited host initiators list. """ trimmed_initiators = [] for init in host_initia...
def figsize(relwidth=1, aspect=.618, refwidth=6): """ Return figure dimensions from a relative width (to a reference width) and aspect ratio (default: 1/golden ratio). """ width = relwidth * refwidth return width, width*aspect
def is_not_excluded_path(path, exclude_paths): """Return False if path excluded, else True""" if exclude_paths: for exclude_path in exclude_paths: if exclude_path.lower().strip() in path.lower(): return False return True
def invert_colors(colors): """ Generates inverted colours for each colour in the given colour list, using a simple inversion of each colour to the opposite corner on the r,g,b cube. :return: inverted_colors - A list of inverted (r,g,b) (r,g,b) values are floats between 0 and 1. """ inverted_col...
def charencode(string): """String.CharCode""" encoded = '' for char in string: encoded = encoded + "," + str(ord(char)) return encoded[1:]
def convert_string_to_dbxref(string): """ A dbxref is dictionary with two keys: db and id. """ split = string.split(':', 1) if len(split) > 1: return {'db': split[0], 'id': split[1]} else: # invalid dbxref. nevertheless return a valid dbxref object with the value as the db and a empt...
def quote_ident(value): """Indent the quotes.""" return "\"{}\"".format(value .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n"))
def replace(body, keys): """For each key and value, replace '%key%' with value""" for key, value in keys.items(): body = body.replace("%" + key + "%", value) return body
def _version_format(version): """Return version in dotted string format.""" return '.'.join(str(x) for x in version)
def get_words(utterance): """Splits an utterance into words, removes some characters not available in spoken dialogue systems, uppercases the text. :param utterance: a string :return: a list of string (words) """ for c in '?!.,': utterance = utterance.replace(c, ' ').replace(' ', ' ') ...
def process_multiple(input_multiple): """ To process multiple parameter - replacing %2C for "," Might as well be using the text type.. perhaps we're not using the multiple type correctly? """ processed_strings = [] for multiple in input_multiple: if ('%2C' in multiple): for individual_string in multiple.spli...
def dynamical_tolerance(tolerance_range, gaussbock_iterations, step): """Calculate the model's convergence threshold dynamically for the given iteration. The variational Bayesian non-parametric Gaussian mixture model used in this code requires a convergence t...
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_rec2 = (rec2[2] - rec2[0]) * (rec2[3]...
def line_intersect(a_p1, a_p2, b_p1, b_p2, tolerance = 0.001): """ Finds the intersection between two lines a and b defined by their respective endpoints p1 and p2 """ # Check if lines intersect if a_p1[0] > b_p1[0] and a_p1[0] > b_p2[0] and a_p2[0] > b_p1[0] and a_p2[0] > b_p2[0]: return False...
def generate_listing_urls(url: str, max_count: int): """Generate urls for all the pages, based on the number of pages. Creating urls such as: * https://www.immowelt.at/liste/wien-10-favoriten/wohnungen/mieten?cp=2 * https://www.immowelt.at/liste/wien-10-favoriten/wohnungen/mieten?cp=3 Where "?cp=x...
def proceed_with_training(ensemble, run): """back in action""" return True # Some handy values accumulated here asymptotes_dict = ensemble.asymptotes(active_only = True) asymptote = asymptotes_dict[run.identifier] del asymptotes_dict[run.identifier] other_asymptotes = asymptotes_dict.val...
def get_email_name(email_from): """parse email from header and return the name part First Last <ab@cd.com> -> First Last ab@cd.com -> "" """ if "<" in email_from: return email_from[: email_from.find("<")].strip() return ""
def sortArray(timestamps): """ Sorts an array of tuples by timestamp \n :param timestamps: An array with tuples of timestamps and pages. \t :type timestamps: [(Time,str)] \n :returns: Sorted array with tuples. \t :rtype:: [(Time,str)] \n """ # Use a lambda function to sort by first eleme...
def linear_search(lst, value): """ Searches for a specified value in a list. It performs linear search in an iterative way. @param lst: a list containing numbers @param value: value to search @return: True if value is found. Otherwise, False. """ for element in lst: ...
def __svn_resp_to_tags(resp): """ Helper to convert svn response to tags """ tags = [] for line in resp.splitlines(): items = line.split() for item in items: if item[-1] == "/": tags.append(item[:-1]) break return tags
def chat_color(color): """ Stepmania chat color format :param str color: Color in hex format :Example: >>> chat_color("cecece") '|c0cecece' """ return "|c0%s" % color
def BirchMurnaghanPV_EOS(V, params): """ Args: V: volume params: tuple of B0,V0,B0p Returns: Pressure of Birch-Murnaghan EOS at V with given parameters E0, B0, V0 and B0p """ V0, B0, B0p = params[0], params[1], params[2] n = (V0 / V) ** (1. / 3) # Note this definition is...
def isinsrange(bits, val): """ Helper function to test if value is withing range. """ msb = 1 << (bits - 1) ll = -msb return val <= (msb - 1) and (val >= ll)
def is_integer(test_str): """Returns True if the string appears to be a valid integer.""" try: int(test_str) return True except ValueError: pass return False
def get_forward_slash_diagonal(grid, uppermost_coordinates): """ Gets the forward slash-type diagonal of a grid based on the coordinates of the uppermost element. :param grid: The base matrix :param uppermost_coordinates: Tuple with the coordinates of the uppermost element of the form (row, column) ...
def is_instance(obj, klass): """Version of is_instance that doesn't access __class__""" return issubclass(type(obj), klass)
def merge_lists(two_d_list): """Merges a 2d array into a 1d array. Ex: [[1,2],[3,4]] becomes [1,2,3,4]""" # I know this is a fold / reduce, but I got an error when I tried # the reduce function? return [i for li in two_d_list for i in li]
def merge_dicts(*dictionaries): """Return a new dictionary by merging all the keys from given dictionaries""" merged_dict = dict() for dictionary in dictionaries: if not dictionary: continue merged_dict.update(dictionary) return merged_dict
def five_five(n): """ This checks if n is a power of 2 (or 0). This is because the only way that n and (n-1) have none of the same bits (the & check) is when n is a power of 2, or 0. """ return ((n & (n-1)) == 0)
def HermiteGi(ti, tiplus, riprime, ri, riplus): """Spline coefficient in Hermite Interpolation""" return (tiplus - ti) * riprime - (riplus - ri)
def _select_auth_scheme(url, auth_configs): """ Select authentication scheme by inspecting `url`. If `url` starts with any of the keys in auth_config, return the value, a dict containing necessary parameters for the selected auth scheme, of the first key match. :param url: the URL to be inspected ...
def search_in_binary(number_list, start, end, query): """ Search query in number_list or not. Arguments: number_list -- a list contain all the elements. start -- start index. end -- end index. query -- a element. Returns: True/False -- if query in number_list return True, e...
def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): """Convert to base""" return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
def snake_to_capwords(s: str) -> str: """Returns a new str in CapWords, given an str in snake_case. Removes all underscore before and after. Examples: >>> snake_to_capwords('snake_to_capwords') 'SnakeToCapwords' >>> snake_to_capwords('__snake_to_capwords__') 'SnakeToCapwords...
def checkForQuote(file): """add quotes if find spaces in file name""" f = str(file) if f.find(" ") >= 0: return "'" + f + "'" return f
def list_primes(limit): """Finds a list of all primes below the input limit""" bits = [0] + [1 for _ in range(limit)] # we filter out 0 bits[1] = 0 # and also one. primes = [] for num, prime in enumerate(bits): if not prime: continue primes.append(num) index = ...
def build_profile(first, last, **user_info): """Build a dictionary containing everything we know about a user.""" profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile
def binaryToDecimal(b): """ This function is only used to log the secret key in decimal format.""" sec_dec = "" if b != None: sec_dec = int(str(b),2) else: sec_dec = "Not set yet!" return sec_dec
def find_intersection(p1, p2, p3, p4): """Find the point of intersection between two line. Work on 3D plane. The two lines are p1 --> p2 and p3 --> p4. Reference:http://csharphelper.com/blog/2020/12/enlarge-a-polygon-that-has-colinear-vertices-in-c/ :param p1: line 1's start point :type...
def infer_bg_func(background_params): """Infers which background function was used, from parameters. Parameters ---------- background_params : list of float Parameters that describe the background of a power spectrum. Returns ------- background_mode : {'fixed', 'knee'} Whic...
def insertionSort(nums): """ Original version :type nums:list[int] :rtype list[int] """ res=list(nums) for i in range(1,len(res)): #find a place for res[i] j=i-1 while j>=0: if res[i]>res[j]: break j-=1 #if we get one ...
def charindices(sent, indices, indices2=None): """Project token indices to character indices. >>> sorted(charindices(['The', 'cat', 'is', 'on', 'the', 'mat'], {0, 2, 4})) [0, 1, 2, 3, 8, 9, 10, 14, 15, 16, 17]""" cur = 0 ind = {} for n, a in enumerate(sent): ind[n] = range(cur, cur + len(a) + (n != len(sen...
def irun_first(runs): """Returns the 1st (int) run number from list or string or int """ return runs[0] if isinstance(runs, list) else\ runs if isinstance(runs, int) else\ int(runs.split(',',1)[0].split('-',1)[0])
def blend(a, b, alpha): """ Blends to images using a weight factor. Args: a (numpy.array): Image A. b (numpy.array): Image B. alpha (float): Weight factor. Returns: numpy.array: Blended Image. """ return alpha * a + (1 - alpha) * b
def anagram_sorted(s1, s2): """Write a method to decide if two strings are anagrams or not.""" # O(nlogn) time, O(n) space return sorted(s1) == sorted(s2)
def count_digit_one(n): """ Count the number of 1's between 0 and n :param n: given number :type n: int :return: number of 1's between 0 and n :rtype: int """ ones, m = 0, 1 while m <= n: # traverse each digit of n, if n=3401512 # for m=100, split n into a=n//m=34015...
def s2human(time): """Convert a time in second into an human readable string""" for delay, desc in [(86400,'d'),(3600,'h'),(60,'m')]: if time >= delay: return str(int(time / delay)) + desc return str(int(time)) + "s"
def as_list(obj): """ Makes sure `obj` is a list or otherwise converts it to a list with a single element. """ return obj if isinstance(obj, list) else [obj]
def chop(x, y, ymax=None, ymin=None, xmin=None, xmax=None): """Chops x, y.""" if xmax: y = y[x < xmax] x = x[x < xmax] if xmin: y = y[x > xmin] x = x[x > xmin] if ymax: x = x[y < ymax] y = y[y < ymax] if ymin: x = x[y > ymin] y = y[...
def calcPolygonRect(pointArray): """ receives a point list and returns the rect that contains them as a tupple -> tuple left, top, right, bottom """ # init to ridiculously big values. not very elegant or eficient l, t, r, b = 10000000, 10000000, -10000000, -10000000 ## l = pointArray[0] ## t = poi...
def mean(numberList): """ Objective: estimate mean of an input variable e.g., >>>x=(1,2,3) >>>mean(x) 2.0 >>>x=[1,1,2] >>>mean(x) 1.3333333333333333 """ if len(numberList) == 0: return float('nan') floatNums = [float(x) for x in numberList] return sum...
def friendly_list(items, conjunction='and'): """Translate a list of items to a human-friendly list of items. Examples: Here are a few example usages of this function: >>> from cloudmarker import util >>> util.friendly_list([]) 'none' >>> util.friendly_list(['apple']) ...
def vis16(n): # DONE """ O .O ..O OOO .OOO OOOOO Number of Os: 1 4 9""" result = '' for i in range(n): result += ('.' * (n - i - 1)) + ('O' * (i * 2 + 1)) + '\n' return result
def _is_excluded_from_filename (key): """ Determine if given key's value shall not be part of the filename. @param key name of the value to check for. @return true if to be excluded, false otherwise """ if (key.find('feature_')!=-1 or key.find('accuracy')!=-1 or key.find('data_')!=-1 or key.find('normaliz...
def iou(a, b): """ Calculates intersection over union (IOU) over two tuples """ (a_x1, a_y1), (a_x2, a_y2) = a (b_x1, b_y1), (b_x2, b_y2) = b a_area = (a_x2 - a_x1) * (a_y2 - a_y1) b_area = (b_x2 - b_x1) * (b_y2 - b_y1) dx = min(a_x2, b_x2) - max(a_x1, b_x1) dy = min(a_y2, b_y2)...
def weekday_list_to_hexweek(weekday_list): """ Helper to convert list of integers represending weekdays into speaker's hex representation of weekdays. :param hexweek: List of weekday integers e.g. [0, 1, 2, 3, 4] :returns: Hex string .e.g. 0x3E """ # Mon, Tue, Wed, Thu, Fri, Sat, Sun weekda...
def set_bit(val, bitNo, bit): """ given a value, which bit in the value to set, and the actual bit (0 or 1) to set, return the new value with the proper bit flipped """ mask = 1 << bitNo val &= ~mask if bit: val |= mask return val
def calc_prime_numbers(n): """Sieve of Eratosthenes""" if n == 1: return [] is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False for i in range(2, int(n ** 0.5) + 1): for j in range(2 * i, n + 1, i): is_prime[j] = False prime_number_list = [] for i in r...
def encode_textfield_ncr(content): """ Encodes the contents for CIF textfield in Numeric Character Reference. Encoded characters: * ``\\x09``, ``\\x0A``, ``\\x0D``, ``\\x20``--``\\x7E``; * '``;``', if encountered on the beginning of the line; * '``\\t``' * '``.``' and '``?``...
def _bit_string(value, min_length=1): """Given an int value, returns a bitwise string representation that is at least min_length long. For example, read._bit_string(42, 8) returns '0b00101010'. """ # Get value and trim leading '0b' value = bin(value)[2:] # Pad value = value.rjust(min...
def clip_alpha(aj, H, L): """ cLips alpha vaLues tHat are greater tHan H or Less tHan L """ if aj > H: aj = H if L > aj: aj = L return aj
def split_when(predicate, list): """Takes a list and a predicate and returns a pair of lists with the following properties: the result of concatenating the two output lists is equivalent to the input list; none of the elements of the first output list satisfies the predicate; and if the second output li...
def do_lstrip(s): """ Removes all whitespaces (tabs, spaces, and newlines) from the beginning of a string. The filter does not affect spaces between words. https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/lib/liquid/standardfilters.rb#L96 """ return s.lstrip()
def checking_duplicate_box_among_tubes(frm_list, tubes): """ checking boxes that are using by different tubes """ valid_flag=False for frm_idx, frm_id in enumerate(frm_list): for tube_id, tube_info in enumerate(tubes): tmp_box = tube_info[frm_id] for tube_id2 in rang...
def get_last_version(file_names): """ Return's the latest version stored as checkpoint """ return int(file_names[-1].split("_v")[1].split(".tar")[0])
def _general_parser(stdout): """Parse any kubectl output with column like output""" lines = stdout.splitlines() result = {} kws = lines[0].split() for line in lines[1:]: parsed_line = line.split() item = {} for i in range(len(kws)): item[kws[i]] = parsed_line[i] ...
def dA_A_star_of_M(M, *args): """Calculates d(A/A*)/dM as a function of M and gamma""" gamma = args[0] a = 1.0+0.5*(gamma-1.0)*M**2 b = (a/(gamma+1.0))**((gamma+1.0)/(2.0*(gamma-1.0))) c = (M**2-1.0)/(M**2*(2.0+M**2*(gamma-1.0)))*b return 2.0**((1.0-3.0*gamma)/(2.0-2.0*gamma))*c
def _FinishedNodesShape(unused_op): """Shape function for FinishedNodes Op.""" return [[None], [None]]
def as_list(maybe_element): """helps to regularize input into list of element. No matter what is input, will output a list for your iteration. **Basic Examples:** >>> assert as_list("string") == ["string"] >>> assert as_list(["string", "string"]) == ["string", "string"] >>> assert as_list(("s...
def i2osp(x: int, x_len: int) -> bytes: """ Integer-to-Octet-String primitive """ if x >= 256 ** x_len: raise ValueError("integer too large") digits = [] while x: digits.append(int(x % 256)) x //= 256 for _ in range(x_len - len(digits)): digits.append(0) r...
def define_directions(pairs: list): """Define pairwise relations between indices. Takes a list of index pair dicts, and determines on which side they are overlapping. The dictionary is updated with the keywords `side0`/`side1`. """ for pair in pairs: i0, j0 = pair['idx0'] i1, j1...
def humansize(nbytes): """ convert size in Byte into human readable: kB, MB, GB https://stackoverflow.com/questions/14996453/python-libraries-to-calculate-human-readable-filesize-from-bytes """ suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] i = 0 while nbytes >= 1024 and i < len(suffixes)-1:...
def _fmt_date(date_as_bytes): """Format mail header Date for humans.""" date_as_string = date_as_bytes.decode() _month = { 'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, ...
def octet(ip, n): """get octet n (0-3) of ip address ip. 0 is the first (left) octet.""" s = (3-n) * 8 return (ip >> s) & 0xff
def argv_to_dict(argv, defaults={}, dot_dict=True): """ Convert a list of (simple) command-line arguments to a dictionary. Parameters ---------- argv : list of strings E.g., ``sys.argv[1:]``. defaults : dict Default dictionary dot_dict : bool If true, t...
def check_arg(argument: str, arg) -> bool: """Helper util to check if an argument is in a sequence. Returns a boolean indicator if the argument was found in the supplied sequence""" if argument.lower() in arg: return True return False
def harmonic_mean(l: list): """ calculate the harmonic mean of a list of classes :param l: a list holding elements :return: """ return len(l) / sum([1 / x for x in l])
def count_parse(parse, index, const_parsed=[]): """ Compute Constituents Parsed metric for ListOps style examples. """ mathops = ["[MAX", "[MIN", "[MED", "[SM"] if "]" in parse: after = parse[index:] before = parse[:index] between = after[: after.index("]")] ...
def find_columns(items_to_look_for, list_to_search_in): """Search entries of list items in a list, return indexes.""" found_indexes = [] # to collect numbers of columns to remove for item_to_look_for in items_to_look_for: # search multiple entries for idx, item_to_search_in in enumerate(lis...
def clean_response(result): """ Clean a response by removing unnecessary fields """ result = result["PET"] try: del result["BLOQ"] except (KeyError, TypeError): pass return result
def v6_add(matrix1, matrix2): """Add corresponding numbers in given 2-D matrices. Turning the outer loop into a list-comprehension. """ return [ [n + m for n, m in zip(row1, row2)] for row1, row2 in zip(matrix1, matrix2) ]
def toposort(graph): """ Does topological sort of graph dict ( {'one': ['two','three'], 'two':['three'], etc} ) and returns ordered list of keys Cyclic dependencies are ignored. """ def get(n, d): if n not in done: done.append(n) for m in d[n]: ...
def ext_gcd(a, b): """ Extended Euclidean Algorithm. Find the result for ax + by = gcd(a, b). Parameters ---------- a: int b: int """ if b == 0: return 1, 0 elif a % b == 0: return 0, 1 else: x, y = ext_gcd(b, a % b) return y, x - y * (a // b)
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is not tuple: kernel_size = ...
def time_to_str(delta_t, mode="min"): """Convert elapsed time to string representation Parameters -------- delta_t: time difference Elapsed time mode: str Time representation manner, by "minitues" or "seconds". Returns -------- delta_str: str Elapsed time string...
def plot_path(path): """ Takes a found path and prints a formated version of the path Args: Path: (List) A set of all the links in the wikipedia article Returns a string verion of the path """ if path == []: print("No path found, try more steps between pages!") return N...
def gm_labels(matrix_dim): """ Gell-Mann basis labels. Parameters ---------- matrix_dim : int The labels (names) of the Gell-Mann basis elements with a given matrix dimension. Returns ------- list """ if matrix_dim == 0: return [] if matrix_dim == 1: return ...
def image_type(data: list, image_type: str) -> list: """ The parameter might be 'all' (both is_pano == true and false), 'pano' (is_pano == true only), or 'flat' (is_pano == false only) :param data: The data to be filtered :type data: list :param image_type: Either 'pano' (True), 'flat' (False)...
def _synthesize_station_lists(left, right): """ Pairwise synthesis op. Submethod of the above. """ # First, find the pivot. pivot_left = pivot_right = -1 for j in range(len(left)): station_a = left[j] for k in range(len(right)): station_b = right[k] if sta...
def select_from_batch(advs, batch): """ Take a rollout-shaped list of lists and select the indices from the mini-batch. """ indices = zip(batch['rollout_idxs'], batch['timestep_idxs']) return [advs[x][y] for x, y in indices]
def getsize(filename): """The length of a file in bytes or 0 if te file does not exists""" from os.path import getsize try: return getsize(filename) except OSError: return 0
def fib(n): """Testing if it can evaluate deep recursion.""" return n if n < 2 else fib(n-2) + fib(n-1)
def getNumBits(numValues): """ Gets the minimum number of bits required to encode given number of different values. This method implements zserio built-in operator numBits. :param numValues: The number of different values from which to calculate number of bits. :returns: Number of bits required to...
def sample_details_extraction(image_data, method_parameters): """Sample of image details extraction""" parameter = method_parameters["test_parameter"] print(f"Sample detail extraction start with parameter: {parameter}") return "image details"
def check_question_mark(s): """ Returns True if the question mark is present. :param s: String :return: True if question mark is present else False. """ if "?" in s: return True else: return False
def getKITTIGroundTruth(labels, categories, categoriesOpt, mode = 'moderate'): """Get mandatory and optional ground truth out of a list of labels The KITTI dataset defines criteria which labels have to be detected in order to avoid a false negative. There are three evaluation modes 'easy', 'moderate' and '...