content
stringlengths
42
6.51k
def _quadmin(a, fa, fpa, b, fb): """Finds the minimizer for a quadratic polynomial that goes through the points (a,fa), (b,fb) with derivative at a of fpa. """ D = fa C = fpa db = b - a B = (fb - D - C * db) / (db ** 2) xmin = a - C / (2. * B) return xmin
def is_letter(s): """ Determines if a string is a simple multiple choice letter. (A, B, C, D) Returns true if this is the case, false otherwise """ return s == 'A.' or s == 'B.' or s == 'C.' or s == 'D.'
def reverse_edges(edges): """Reverses direction of dependence dict. Parameters ---------- edges : dict Dict of the form {a: {b, c}} where b and c depend on a Returns ------- Dict of the form {b: (a,), c: (a,)} where b and c depend on a Example ------- >>> d = {'a': (1...
def get_sample_id(sample): """Return id attribute of the object if it is sample, otherwise return given value.""" return sample.id if type(sample).__name__ == "Sample" else sample
def _average_units(shape): """ Average shape dim. """ if not shape: return 1. if len(shape) == 1: return float(shape[0]) if len(shape) == 2: return float(shape[0] + shape[1]) / 2. raise RuntimeError("not support shape.")
def permute(seq, p): """Permute the elements of a sequence according to a permutation. :param seq: a sequence to be permuted :param p: a permutation (sequence of integers between ``0`` and ``len(seq) - 1``) :returns: ``tuple(seq[i] for i in p)`` :rtype: tuple """ return tuple(...
def flip_lambda(Lambda): """ Flip the lambda tensors (part of the canonical peps) horizontally Args: Lambda : Returns: Lambda : The horizontally flipped version of the lambda tensor. This is flipped such that ... """ if Lambda is not None: # Get...
def convert_to_uri_encoding(value): """Convert given value to uri component.""" return value.replace( '%21', '!').replace('%2A', '*').replace('%27', "'").replace( '%28', '(').replace('%29', ')')
def note2ratio(note, cents=0): """ Converts semitones to a frequency ratio. """ ratio = 2 ** ((note + cents / 100) / 12) return ratio
def log1(sequence, message, *values): """ log1 :param sequence: :param message: :param values: :return: """ if not values: print('{0}: {1}'.format(sequence, message)) else: values_str = ', '.join(str(x) for x in values) print('{0}: {1}: {2}'.format(sequence, m...
def classic_example_3(sequence_of_sequences, what_to_count, what_to_mutate_into): """ Shows counting and mutating in a sequence of LISTS. -- Counts and returns the number of 'what_to_count' occurrences. -- Mutates those occurrences into the 'what_to_mutate_into'. """ pr...
def merge_two_lists_of_dicts(list_of_dicts_1, list_of_dicts_2, parameter1, parameter2): """ Combine the list of dicts 1 and with list of dicts 2 using the household indicator and year keys. """ d1 = {(d[parameter1], d[parameter2]):d for d in list_of_dicts_2} list_of_dicts_1 = [dict(d, **d1.get((d[...
def set_effective_list(column, row): """ Function: Create an effective matrix and use (0: invalid 1: valid) to record the path that can be taken. :param column: (int) x direction :param row: (int) y direction :return: (list) List of valid paths """ effective_list = [[0 for i in range(column + 2)] for j in rang...
def kaldi_to_nt_example_id(example_id: str): """ >>> kaldi_to_nt_example_id('P28_S09_LIVING.R-0714562-0714764') 'P28_S09_0714562-0714764' >>> kaldi_to_nt_example_id('P05_S02_U02_KITCHEN.ENH-0007012-0007298') # doctest: +ELLIPSIS Traceback (most recent call last): ... NotImplementedError: Ar...
def evaluate_sampler( sampler_fn, obs, action ): """ :param sampler_fn: fn(o,k) Function returning sample value [p1,p2..] List of values per-arm p1 Scalar value for all arms :param obs: :param action: :return: """ if callable(sampler_fn): sampl...
def bitmap(num, ind=0): """docstring""" bits = [] bit = ind while num: if num & 1: bits.append(bit) # num >>= 1 bit += 1 # return bits
def bubble_sort(items): """ Implementation of bubble sort """ out = items.copy() # in place protection on items for i in range(len(out)): for j in range(len(out)-1-i): if out[j] > out[j+1]: out[j], out[j+1] = out[j+1], out[j] # Swap! return out
def get_mse_norm(series1, series2): """ normalized values the series will be sorted and normalized to maximum value in any series maximum value = 1.0 """ assert len(series1) == len(series2) mse = 0.0 max_v = max(max(series1), max(series2)) s1 = tuple((value/max_v for value in series...
def expandYear(year): """Expands a 2-digit year into a 4-digit year. Takes a guess at the century, assuming that any year value < 40 was in the 1900's. """ if not year: return None intYear = 0 if type(year) is str: intYear = int(year) elif type(year) is int: intYear = year if intYear < 1...
def to_str(x): """Convert all non-str lists to string lists for Word2Vec.""" ret = " ".join([str(y) for y in x]) if isinstance(x, list) else str(x) return ret
def convtograyscale(rgb): """Conversion of RGB to grayscale. http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale :keyword seq rgb: sequence of rgb float values (0 to 1) :returns: Float for grayscale value """ return (rgb[0]*.3 + rgb[1]*.59 + rgb[2]*.11)
def create_wav_header(sampleRate, bitsPerSample, num_channels, num_samples): """Generate WAV file header.""" datasize = num_samples * num_channels * bitsPerSample // 8 o = bytes("RIFF", "ascii") # (4byte) Marks file as RIFF o += (datasize + 36).to_bytes( 4, "little" ) # (4byte) File size i...
def hash_str(gram_str): """hash fun""" gram_bytes = bytes(gram_str, encoding='utf-8') hash_size = 18446744073709551616 h = 2166136261 for gram in gram_bytes: h = h ^ gram h = (h * 1677619) % hash_size return h
def _convert_to_flattened_list(comment): """This handles cases, where strings are quoted on the command line""" splitted = [] for item in comment: print(splitted) if ' ' in item: splitted.extend(item.split()) else: splitted.append(str(item)) print(splitted...
def isIPAddress(addr): """ Determine whether the given string represents an IPv4 address. @type addr: C{str} @param addr: A string which may or may not be the decimal dotted representation of an IPv4 address. @rtype: C{bool} @return: C{True} if C{addr} represents an IPv4 address, C{False} ...
def f1_from_roc(fpr, tpr, pos, neg): """Calculate f1 score from roc values. Parameters ---------- fpr : float The false positive rate. tpr : float The true positive rate. pos : int The number of positive labels. neg : int The n...
def compare_motif_cterm_nopos(peptide, motif): """C-term not position specific motif match.""" motif_ct = peptide[-6:].count(motif) return motif_ct
def _validate_args(args, valid_args): """Validate args in format '--key=value'.""" return { arg.replace("--", "").split("=")[0]: arg.replace("--", "").split("=")[1] for arg in args if arg.startswith("--") and "=" in arg and arg.replace("--", "").split("=")[0] in valid_args }
def endsInNewline(s): """ Returns C{True} if this string ends in a newline. """ return (s[-len('\n'):] == '\n')
def calc_highest_peak(info, wt_fraction, average_depth): """ Calculate the highest peak """ highest_frac=wt_fraction for loci, details in info.items(): details['allele_fraction'] = float(details['mutant_depth'])/average_depth if details['allele_fraction'] >= highest_frac: ...
def user_name_to_file_name(user_name): """ Provides a standard way of going from a user_name to something that will be unique (should be ...) for files NOTE: NO extensions are added See Also: utils.get_save_root """ # Create a valid save name from the user_name (email) ...
def list_br_html_addition(l): """ # Replace the /n by the <br> HTML tag throughout the list :param l: The list :return: List """ for sublist in l: for i in range(len(sublist)): if isinstance(sublist[i], str): sublist[i] = sublist[i].replace("\n", "<br>") r...
def get_username(entity, mention=True, log=False): """Get username of chat or user. If no username is available, will return user first_name (+last_name if present) or chat title. If mention is True and target is mentionable, a mention will be returned (either with @ or with a tg deeplink). If log is True,...
def to_ms(ip_str): # FIX ME """Convert a HH:MM:SS:MILL to milliseconds""" try: #ip = ip_str.split(':') hh, mm, ss = ip_str.split(':') hh = int(hh) * 60 * 60 mm = int(mm) * 60 ss = int(ss) except ValueError: hh = 0 try: mm, ss = ip_str.split...
def ordinalize(n): """ Ordinalize a number. Examples -------- >>> [ordinalize(n) for n in range(1, 4 + 1)] ['1st', '2nd', '3rd', '4th'] """ mapper = { 1: 'st', 2: 'nd', 3: 'rd', } return str(n) + mapper.get(n % 10, 'th')
def format_seconds(ms: int) -> str: """Formats milliseconds into min:sec:ms format""" sec, ms = divmod(ms, 1000) min, sec = divmod(sec, 60) return "%01d:%02d.%03d" % (min, sec, ms)
def is_num_tuple(t,size): """ Checks whether a value is a sequence of numbers. If the sequence is not of the given size, it also returns False. :return: True if t is a sequence of numbers; False otherwise :rtype: ``bool`` :param t: The value to test :type t: any :param size: The si...
def format_decorators(source_lines: list) -> list: """ Tidies up decorators, removing unneeded syntax for docs :param source_lines: Source code lines of a function :return: List of tidy decorators for doc """ raw_step_decorators = [line for line in source_lines if re.match(r'@[a-z]+\(', line)] ...
def get_bits(val, length): """\ Gets an array of bits for the given integer (most significant digits first), padded with 0s up to the desired length """ bits = [int(bit_val) for bit_val in '{:b}'.format(val)] padding = [0] * max(0, length - len(bits)) return padding + bits
def opt_err_func(params, x, y, func): """ Error function for fitting a function using non-linear optimization. Parameters ---------- params : tuple A tuple with the parameters of `func` according to their order of input x : float array An independent variable. y : ...
def escape_html(s, quote=True): """ Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ s = s.replace("&", "&amp;") ...
def remove_http_request_body(client, event): """ Removes request.body from context :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ if "context" in event and "request" in event["context"]: event["context"]["request"].pop(...
def snaga_tokarenje(glavna_sila, brzina_rezanja): """ """ return glavna_sila*brzina_rezanja/60e3
def merge(input, second = []): """ Merges 2 lists together, assuming both lists are already sorted. """ i = 0 j = 0 n = len(input) + len(second) out = [] for _ in range(0, n): try: inp = input[i] except IndexError: out += second[j:] bre...
def short_hamming(ident: int, len1: int, len2: int) -> float: """Compute the normalized Hamming distance between two sequences.""" return 1 - ident / min(len1, len2)
def season(x): """ Returns a season (as an int value) for a given day of a year :param x: int Day of the year :return: int with the season value """ fall = range(80, 172) winter = range(172, 264) spring = range(264, 355) if x in spring: return 3 if x in winter: r...
def get_parameters(tp): """Return type parameters of a parameterized type as a tuple. """ try: return tp.__parameters__ if tp.__parameters__ is not None else () except: return ()
def init_next(pat): """ returns table with strict borders for each prefix length from prefix[:0]="" until prefix[:]=pat """ m = len(pat) B = (m+1)*[-1] if m==1 or (m > 1 and pat[0]!=pat[1]): B[1] = 0 i = 1 j = 0 while i < m: while i+j < m and pat[j]==pat[i+j]: ...
def get_eta_transmission(district_type): """ Returns efficency of lhn based on Fraunhofer Umsicht: Leitfaden Nahwaerme (p.51) Parameters ---------- district_type : string type of district (big, medium, small) Returns ------- eta_transmission : float efficiency factor fo...
def computeArea(originalPolygon): """Compute 'area' of a polygon as defined with latitude, longitude points""" if len(originalPolygon) < 3: raise ValueError("Polygon must have 3 or more points") # # Copy polygon = originalPolygon # # Confirm it's closed if polygon[0] != polygon[-...
def secant_method(tol, f, x0): """ Solve for x where f(x)=0, given starting x0 and tolerance. Arguments ---------- tol: tolerance as percentage of final result. If two subsequent x values are with tol percent, the function will return. f: a function of a single variable x0: a starti...
def add_three(a, b, c): """Just another example function that's called async.""" return a + b + c
def parse_variant( variant_string ): """ Splits the given string of the form "key=value key=value ..." into a dict and returns it. """ D = {} for s in variant_string.strip().split(): L = s.split('=',1) if len(L) == 1: D[s] = None else: ...
def is_adult_division(locations): """Checks if any of the locations is Central's adult division""" if locations is None: return False if "03" in locations: return True elif "04" in locations: return True elif "11" in locations: return True elif "12" in locations...
def prettify_MA_rank(rank: int) -> str: # Independent of mi18n """Turn the rank returned by the API into the respective rank name displayed in-game.""" brackets = (0, 0.20, 2, 7, 17, 35, 65) return f"{brackets[rank - 1]:1.2f} ~ {brackets[rank]:1.2f}"
def utf8_to_binary(text): """ Convert unicode (utf-8) text to binary Args: text -- string -- the text to convert return the binary value of text """ return ''.join("{0:08b}".format(ord(c)) for c in text)
def strrev(s): """Reversing a String.""" if type(s) == str: return s[::-1] else: raise Exception('Not a string')
def parse_convergence_section(convergence_section_dict): """ Parse the convergence section dictionary Parameters ---------- convergence_section_dict: ~dict dictionary """ convergence_parameters = ['damping_constant', 'threshold', 'fraction', 'hold_iterations'] fo...
def is_palindrome_v1(string): """check if the string is palindrome or not.(while loop)""" i, n = 0, len(string) - 1 while i < n and string[i] == string[n]: i += 1 n -= 1 return n <= i
def split_seq(seq, size): """ Split up seq in pieces of size. Args: seq: size: Returns: """ return [seq[i:i + size] for i in range(0, len(seq), size)]
def square_soft(input_list): """ Returns a list with all values squared and sorted """ squared = [] # Separate negative and positive values # Reverse the negative array to preserve order # ex: [-3, -2, -1] -> [-1, -2, -3] -> [1, 4, 9] neg = [x**2 for x in input_list if x < 0] pos = ...
def find_supremum(fun, thresh, start, step, max_iter, tol = 1e-5, debug=False): """Given a function fun:X -> R and a (float) threshold thresh, approximate the supremum \sup_x \{fun(x) \leq thresh\}. Adapted version of the bisection method. Parameters: - fun (function): f:X->R. The function for w...
def convert_to_babylonian_time(seconds): """ Convert time value to seconds to HH:MM:SS >>> convert_to_babylonian_time(3661) '01:01:01' """ hours = int(seconds / 3600) seconds %= 3600 minutes = int(seconds / 60) seconds %= 60 return "{:02d}:{:02d}:{:02d}".format(hours, minutes, ...
def keywordSearch(text_list, include_keywords, exclude_keywords=None): """ Searches a list of text arguments and returns a list that includes/excludes the list elements that contain the keywords. Useful when searching for column names in a large dataframe, for example. Parameters ---------...
def max_ones(n): """ Given a base-10 integer,n , convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation. When working with different bases, it is common to show the base as a subscript.""" print(bin(n)) resul...
def idems(dit): """Convenience function for iterating dict-likes. If dit.items is defined, call it and return the result. Otherwise return dit itself. """ return dit.items() if hasattr(dit, 'items') else dit
def convert_header(header): """Converts fastapi headers into a dict of strings FastAPI comes in as a tuple of byte strings. convert_header turns those headers into a dict of str. This is necessary for the JSON marshalling to work. """ res = dict() for a, b in header: res[a.decode("utf-8"...
def scale3D(v,scale): """Returns a scaled 3D vector""" return (v[0] * scale, v[1] * scale, v[2] * scale)
def solve_quad_mod (a, b, c, n): """ Solve a quadratic equation modulo n. Find all solutions to the quadratic equation a*x^2 + b*x + c = 0 mod n for integer n. Here a, b, c are integers. """ solutions = [] for x in range (n): poly_val = (a*x*x + b*x + c) % n if poly...
def true_param(p): """Check if ``p`` is a parameter name, not a limit/error/fix attributes. """ return (not p.startswith('limit_') and not p.startswith('error_') and not p.startswith('fix_'))
def browse(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ # TBD: should calculate url url='https://github.com...
def qualified_field(alias, field): """ Qualifies the SQL `field` with `alias`. If `alias` is empty, then no qualification is used. (Just `field` is returned.) """ if not alias: return field else: return '%s.%s' % (alias, field)
def info_from_jenkins_auth(username, password, required_scopes): """ Check and retrieve authentication information from basic auth. Returned value will be passed in 'token_info' parameter of your operation function, if there is one. 'sub' or 'uid' will be set in 'user' parameter of your operation functi...
def isiterable(x): """Checks whether the input is a non-string iterable. Args: x: The object to check for iterability. Returns: bool: True if the input is a valid iterable, otherwise False. """ return hasattr(x, "__iter__") and not hasattr(x, "upper")
def return_request(data): """ Arguments: data Return if call detect: list[dist1, dist2, ...]: dist = { "feature": feature } Return if call extract: list[dist1, dist2, ...]: dist = { "confidence_score": predict p...
def remove_old_friends(my_friends, my_mutual_friends): """Removes friends from the my_mutual_friends that are no longer friends of the user (those not in my_friends) """ if len(my_friends) < len(my_mutual_friends): for oldfriend in set(my_mutual_friends.keys()) - set([u['id'] for u in my_fr...
def any(fun, values): """ A function that will return True if the predicate is True for any of the provided values. Complexity: O(n) params: fun: the predicate function values: the values to test against returns: boolean """ for element in values: if fun(element)...
def get_different_feature_positions_axelrod(agent_traits, neighbor_traits): """ Returns a list of the positions at which two lists of traits differ (but not the differing traits themselves). """ features = [] for i in range(0, len(agent_traits)): if agent_traits[i] != neighbor_traits[i]:...
def parse_durn(durn): """ >>> parse_durn('30s') 30 >>> parse_durn('1m') 60 >>> parse_durn('1m30s') 90 >>> parse_durn(' 2m 30s ') 150 >>> parse_durn(' ') >>> parse_durn('1') >>> parse_durn('5m3') """ durn_value = 0 while durn: durn = durn.strip() ...
def query_by_ids(ids): """Get documents from ES based on specified ID. Args: ids (list): selected IDs fields (list): selected fields Returns: search_params (dict): ES query """ search_params = {"query": {"terms": {"_id": ids}}} return search_params
def _get_recipe_keys(args, remove_prefix=None, add=None, allow_skips=True): """ Obtain the recipe keys from reipce "args" :param args: Dictionary containing key, value pairs where keys are the argument names and values are instances of DrsArgument :param remove_prefix: string or None, ...
def utf8_attrs(info): """ Convert bytes to utf8 args: info dict() return: info dict() (decoded to utf8) """ for key, val in info.items(): if isinstance(val, bytes): info[key] = val.decode("utf8") return info
def split_filename(filename): """ Pass in a standard style rpm fullname Return a name, arch, epoch, version, release e.g.:: foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386 1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64 """ if filename[-4:] == '.rpm': filename = filename[:...
def valid(bo, pos, num): """ Returns if the attempted move is valid :param bo: 2d list of ints :param pos: (row, col) :param num: int :return: bool """ # row check for i in range(0, len(bo)): if bo[pos[0]][i] == num and pos[1] != i: return False # col check ...
def clean_var(var): """Clean variable name, removing accidental commas, etc.""" return var.strip().replace(',', '')
def postorder(root): """Postorder depth-first traverse a binary tree.""" ans = [] node, stack = root, [] while node or stack: if node: if node.right: stack.append(node.right) stack.append(node) node = node.left continue node = stack.pop()...
def twoSum_2(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ otherIndex = -1 for i in nums: other = target - i if other in nums: if other == i and nums.count(i) == 1: continue else: ot...
def compare_history(first_file, second_file): """ Compares _history field on files. Addons in these scenarios are very unlikely to have versions, so we must compare their _history. """ first_hist = first_file['_history'] second_hist = second_file['_history'] if first_hist and second_hist: ...
def calcweight( readings, calibrations ): """ Determine the weight of the user on the board in hundredths of a kilogram """ weight = 0 #weight = sum(calibrations.next()) #print("Peso") #print(weight) for sensor in ('right_top', 'right_bottom', 'left_top', 'left_bottom'): reading ...
def _adjust(x): """Adjust x for sorting in a lambda function. If x is less than 0 then add 3600 to it else just edit it as normal. :param x: a string to be evaluated and compared. :return: the adjusted value. """ if eval(x) > 0: return eval(x) else: return eval(x)+3600
def __format(escape, string): """ Apply desired format """ return "\x1b[{0}m{1}\x1b[0m".format(escape, string.replace("\x1b[0m", ''))
def _to_label(repo, path, name): """ Returns the target string to pass to buck Args: repo: The name of the cell, or None path: The path within the cell name: The name of the rule Returns: A fully qualified target string """ return "{}//{}:{}".format(repo or "",...
def log_pipeline(source, *passes): """ Log processing pipeline. """ composed_iter = source # Apply previous generator to next pass for pass_func in passes: composed_iter = pass_func(composed_iter) # Collect into a list return list(composed_iter)
def add_extra_nonce_to_tx_extra(extra, extra_nonce): """ Appends nonce extra to the extra buffer :param extra: :param extra_nonce: :return: """ if len(extra_nonce) > 255: raise ValueError("Nonce could be 255 bytes max") extra += b"\x02" + len(extra_nonce).to_bytes(1, "big") + ext...
def IXGBE_SRRCTL(index): """ Split and Replication Receive Control Registers 00-15 : 0x02100 + n*4 16-64 : 0x01014 + n*0x40 64-127: 0x0D014 + (n-64)*0x40 """ if index <= 15: return 0x02100 + index * 4 if index < 64: return 0x01014 + index * 0x40 return 0x0D014 + (inde...
def productExceptSelf(nums): """ Input: [1,2,3,4] Output: [24,12,8,6] """ pre, ret = 1, [] for n in nums: ret.append(pre) pre *= n pre = 1 for i in range(len(nums)-1, -1, -1): ret[i] = ret[i]*pre pre *= nums[i] return ret
def insertion_sort(lst): """ Sort list using the InsertionSort algorithm. >>> insertion_sort([24, 6, 12, 32, 18]) [6, 12, 18, 24, 32] >>> insertion_sort([]) [] >>> insertion_sort("hallo") Traceback (most recent call last): ... TypeError: lst must be a list """ if not ...
def localize_settings(settings, local_paths): """ Localizes the dictionary recursively, by replacing any string values containing <localization> keys. The replacement is done on a deep copy, which is returned. Inputs: settings python dict local_paths python dict containing th...
def nicesize(nbytes: int, space: str = "") -> str: """ Uses IEC 1998 units, such as KiB (1024). nbytes: Number of bytes space: Separator between digits and units Returns: Formatted string """ data = { "PiB": 1024 ** 5, "TiB": 1024 ** 4, "GiB":...
def sort_by_frequencies(alphas): """ sorts string by frequencies """ items = [] temp = [alphas[0]] for x in range(1, len(alphas)): if alphas[x] == alphas[x - 1]: temp.append(alphas[x]) else: items.append(''.join(temp)) temp = [alphas[x]] it...