content
stringlengths
42
6.51k
def get_length(dur, sr): """Return total number of samples based on duration in second (dur) and sampling rate (sr)""" if isinstance(dur, float): length = int(dur * sr) elif isinstance(dur, int): length = dur else: raise TypeError("Unrecognise type for dur, int (samples) or float...
def _freeze_dict(dct): """Tries to freeze a dict to make it hashable.""" result = [] for key, value in dct.items(): if isinstance(value, dict): value = _freeze_dict(value) result.append((key, value)) result.sort() return tuple(result)
def modular_inverse(a, mod): """ Compute modular inverse using Extended Euclidean algorithm """ r_prev, u_prev, v_prev, r, u, v = a, 1, 0, mod, 0, 1 while r != 0: q = r_prev // r r_prev, u_prev, v_prev, r, u, v = ( r, u, v, r_prev - q * r, ...
def auto_int(x): """ Convert a string (either decimal number or hex number) into an integer. """ return int(x, 0)
def radians(degree: int) -> float: """radians. helper function converts degrees to radians. Args: degree: degrees. """ pi_on_180 = 0.017453292519943295 return degree * pi_on_180
def check_for_empty_values(dictionary): """ checking dict for empty values :param dictionary: dict for checking :return: check result """ return all(dictionary.values())
def VectorVector_additon(vectorA, vectorB): """ N diemnsional. Return an array as a vector resulting from vectorA + vectorB""" result_vector = [] for i in range(0,len(vectorA)): result_vector.append(vectorA[i] + vectorB[i]) return result_vector
def parse_colormode(colormode: int, blink: bool, bright: bool, bold: bool) -> int: """Parse colormode setters into colormode. Returns the colormode in int. Blink and Bright will override colormode. Bold overrides colormode if :py:`colormode == 8`. Args: colormode: Colormode...
def bold(string: str) -> str: """ Add bold md style. :param string: The string to process. :type string:str :return: Formatted String. :rtype: str """ return f"**{string}**"
def __gcd(a: int, b: int) -> int: """ Return the greatest common denominator of `a` and `b`. """ while b != 0: a, b = b, a % b return a
def search_index(max_len, num_of_depend, num_for_predict, points_per_hour, units): """ Parameters ---------- max_len: int, length of all encoder input num_of_depend: int, num_for_predict: int, the number of points will be predicted for each sample units: int, week: 7 * 24, day: 24, recent(ho...
def word(*args): """ WORD word1 word2 (WORD word1 word2 word3 ...) outputs a word formed by concatenating its inputs. """ return ''.join(map(str, args))
def recursive_find_dependencies(source_filename, source_to_source, gen_header_to_lib, visited=None): """ Recursively traverse dependency graph given by *source_to_source* and *gen_header_to_lib* to find libraries that may be required for *source_filename*. """ # this function can be sped up usin...
def page_not_found(error): """Return generic 404 page""" return 'Requested page does not exist', 404
def modified_dict(input_dict, modification_dict): """Returns a dict, with some modifications applied to it. Args: input_dict: a dictionary (which will be copied, not modified in place) modification_dict: a set of key/value pairs to overwrite in the dict """ output_dict = input_dict.copy() output_dict...
def compute_metrics_MCL(pred, gt): """ Compute the metrics {Precision, Recall, F1-score} for MCL. :param pred: target algorithm's output :param gt: ground truth :return dictionary of computed metrics """ metrics = {} tp = len(set(pred).intersection(set(gt))) fp = len(set(pred).dif...
def find_closure(rel, attrs): """ Finds the closure of attrs under the relations in rel. Arguments: rel (list[(list[str], str)]) : relationships to find closure under attrs (list[str]) : attributes to find the closure of Returns: closure (set[str]) : attrs' closure, aka the att...
def lon_to_x(lon: float, zoom: int) -> float: """ Longitude to x tile :param lon: :param zoom: :return: """ if not (-180 <= lon <= 180): lon = (lon + 180) % 360 - 180 return ((lon + 180.0) / 360) * pow(2, zoom)
def get_sanitized_bot_name(dict, name): """ Cut off at 31 characters and handle duplicates. :param dict: Holds the list of names for duplicates :param name: The name that is being sanitized :return: A sanitized version of the name """ if name not in dict: new_name = name[:31] # Make...
def _parse_ipmi_nic_capacity(nic_out): """Parse the FRU output for NIC capacity Parses the FRU output. Seraches for the key "Product Name" in FRU output and greps for maximum speed supported by the NIC adapter. :param nic_out: the FRU output for NIC adapter. :returns: the max capacity supporte...
def int_type(value): """Integer value routing.""" print(value + 1) return "correct"
def ConcaveMinima(RowIndices,ColIndices,Matrix): """ Search for the minimum value in each column of a matrix. The return value is a dictionary mapping ColIndices to pairs (value,rowindex). We break ties in favor of earlier rows. The matrix is defined implicitly as a function, passed as the ...
def prop_is_none(value): """ Checks if property value is None. """ return (value is None or (isinstance(value, dict) and 'value' in value and value['value'] is None))
def get_ratios(vect1, vect2): """Assumes: vect1 and vect2 are lists of equal length of numbers Returns: a list containing the meaningful values of vect1[i]/vect2[i]""" ratios = [] if len(vect1) != len(vect2): raise ValueError('get_ratios called with bad arguments') for inde...
def good_info_integration(request, asset, lang): """ From the SEP """ return { "types": { "bank_account": { "fields": { "dest": {"description": "your bank account number"}, "dest_extra": {"description": "your routing number"}, ...
def bin2dec (s): """ Convert binary value to integer :param s: string :returns: integer """ s = str(s) return int(s,2)
def quadratic(a, b, c): """ Always returns the smallest root as t0 """ discrim = b**2 - 4 * a * c if discrim < 0: return (False, 0, 0) rootd = discrim**(1/2) if b < 0: q = -0.5*(b - rootd) else: q = -0.5*(b + rootd) t0 = q / a t1 = c / q if t1 > t0: tm...
def handle_tensorboard_timeout(e): """Handle exception: TensorBoard does not respond.""" return "Tensorboard does not respond. Sorry.", 503
def add_startxref(article, pos_index): """ """ o_num, o_gen, o_ver = article['o_num'], article['o_gen'], article['o_ver'] xref = article['content'] ret = '' ret += f'<div id="obj{o_num}.{o_gen}.{o_ver}">\n<pre>\n' ret += f'startxref\n' if xref == 0: ret += f'0\n' else: re...
def Mc_m1_m2(m1, m2): """ Computes the chirp mass (Mc) from the component masses input: m1, m2 output: Mc """ Mc = (m1*m2)**(3./5.)/(m1+m2)**(1./5.) return Mc
def clip_positions_count(nh, nw, fh, fw, padding=0, stride=1): """ Counts the number of positions where the filters can be applied on activations. :return: A pair (number of horizontal positions, number of vertical positions) """ if padding >= fh or padding >= fw: raise ValueError(f...
def find_index(f, seq): """Return the index of the first item in sequence where f(item) == True.""" for index, item in enumerate(seq): if f(item): return index
def tarai(x, y, z): """Simple implementation of tarai(x, y, z) as it is.""" if x <= y: return y return tarai(tarai(x - 1, y, z), tarai(y - 1, z, x), tarai(z - 1, x, y))
def divisors_of(n): """Returns list with all the divisors of the natural number n""" vector = [1] for x in range(2, n + 1): if n % x == 0: vector.append(x) return vector
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_unique...
def capitalize(data: str): """Function for capitalizing the input string.""" # zero!!!111! why not just use str.capitalize!!!! # something like "hard demon".capitalize() returns "Hard demon", while this function returns "Hard Demon" resp: str = '' for i in data.split(' '): resp += ...
def scale_width(num_filters, width_coefficient, width_divisor, min_width): """ Calculates the scaled number of filters based on the width coefficient and rounds the result by the width divisor. """ if not width_coefficient: return num_filters num_filters *= width_coefficient min_wid...
def _extractFeatureClasses(lookupIndex, subtableIndex, classDefs, coverage=None): """ Extract classes for a specific lookup in a specific subtable. This is relatively straightforward, except for class 0 interpretation. Some fonts don't have class 0. Some fonts have a list of class members that are c...
def issequence(obj): """returns True if obj is non-string iterable (list, tuple, ect)""" return getattr(obj, '__iter__', False)
def is_hashable(obj): """Returns true if *obj* can be hashed""" try: hash(obj) except TypeError: return False return True
def get_address(master_host, master_port): """Get master address.""" return "tcp://{}:{}".format(master_host, master_port)
def report_count_table_sort(s1, s2): """ """ # Sort order: Class and scientific name. columnsortorder = [0, 2, 3, 6] # Class, species, size class and trophy. # for index in columnsortorder: s1item = s1[index] s2item = s2[index] # Empty strings should be at the end. ...
def maxDepth(root): """ :type root: TreeNode :rtype: int """ def traverse(node, depth=0): if node is None: return depth l_depth = traverse(node.left, depth + 1) r_depth = traverse(node.right, depth + 1) return max(l_depth, r_depth) return traverse(ro...
def compute_eta(avg_time_per_step: float, remaining_steps: int) -> str: """ todo """ remaining_time = int(avg_time_per_step * remaining_steps) m, s = divmod(remaining_time, 60) h, m = divmod(m, 60) return f"{h:d}:{m:02d}:{s:02d}"
def representsInt(s): """ Returns True if the passed string can be represents an integer, False otherwise. """ try: int(s) return True except ValueError: return False
def ExpandMedia(media_str, media_dict, mediaExclude): """ Args: media_str: (str) Name of the media media_dict: (d) media (str) -> list<compound_l> where compound_l list<compound (str), concentration (str), units (str)> e.g. [Ammonium chloride, 0.25, g...
def int_to_si(n): """Convert integer to string with SI magnitude. `n` will be truncated. Examples: 5432 ==> 5k, 12345678 ==> 12M Args: n: Integer to represent as a string. Returns: String representation of `n` containing SI magnitude. """ m = abs(n) sign = -1 if n < 0 else 1 if m < 1e3: ...
def gcd(a, b): """Calculate and return greatest common divisor using Euclid's Algorithm.""" while b: a, b = b, a % b return a
def S_calc(va,vb,vc,ia,ib,ic): """Function to calculate apparent power.""" return (1/2)*(va*ia.conjugate() + vb*ib.conjugate() + vc*ic.conjugate())*1.0
def num_to_dashes(n: int) -> str: """Create a string of hyphens with length n.""" return "-" * n
def lookup_size(delta, dull): """ :type delta: float :type dull: dict, a dictionary of small, medium, large thresholds. """ delta = abs(delta) if delta <= dull['small']: return False if dull['small'] < delta < dull['medium']: return True if dull['medium'] <= del...
def generate_source_static(n_bins): """Create the source structure for the given number of bins. Args: n_bins: `list` of number of bins Returns: source """ binning = [n_bins, -0.5, n_bins + 0.5] data = [120.0] * n_bins bkg = [100.0] * n_bins bkgerr = [10.0] * n_bins ...
def add_pos_eff(pos_effects, new_poss_eff): """ Handles new poison effect :param pos_effects: List to add to :param new_poss_eff: new poison effect return: modified list """ if new_poss_eff not in pos_effects: pos_effects.append(new_poss_eff) return pos_effects else: ...
def column(matrix, i): """Return column row as list. """ return [row[i] for row in matrix]
def mean(array_list): """Returns the mean of an array or list""" count = 0.0 for value in array_list: count += value return count/len(array_list)
def fib(id): """ id: index (zero-based) returns: Fibonacci number for the given index id: 0 1 2 3 4 5 6 7 Fib: 0 1 1 2 3 5 8 13 """ if id < 0: return 0 if id == 0: return 0 if id == 1: return 1 first = 0 second = 1 counter = 2 fib_num = 0...
def thin_out_by_dislikes(client_list: list, dislikes: list) -> list: """Receives a list of clients and returns a list of clients that don't have the specified dislikes D. Args: client_list (list): List of clients that has the form [[L,D,N]*]. dislikes (list): A list of dislikes in the form of a...
def _line_in_file(to_find, filename): """Return True if the specified line exists in the named file.""" assert "\n" not in to_find try: with open(filename) as f: for line in f: if to_find in line: return True return False except FileNot...
def wrap_with_double_check(test_string): """Wraps test_string with a check for fp64 if appropriate""" string = 'if (testDevice.has(sycl::aspect::fp64)) {\n' string += test_string string += '}\n' return string
def get_formatted_wwn(wwn_str): """Utility API that formats WWN to insert ':'. """ if (len(wwn_str) != 16): return wwn_str else: return ':'.join( [wwn_str[i:i + 2] for i in range(0, len(wwn_str), 2)])
def two_pair(ranks): """If there are two pair, return the two ranks as a tuple: (highest, lowest); otherwise return None.""" two_pair = set() for r in ranks: if ranks.count(r) == 2: two_pair.add(r) two_pair_lst = list(two_pair) two_pair_lst.sort(reverse = True) return tuple(two_pair_...
def _find_annotations(name, config_obj): """Return a list of config objects containing an 'annotations' element.""" result = [] if isinstance(config_obj, dict): if "annotations" in config_obj: result.append(f"{name}.annotations") else: for k, v in config_obj.items(): ...
def borda(voteList): """ This function takes the preference ranking data as an input parameter. It computes the Borda score for each candidate and returns the scores in a dictionary. Parameters: voteList - The preference ranking data as a list of lists. Return Value: The Borda results for eac...
def kv_parser(inp): """ Converts a url-encoded string to a dictionary object. """ return {obj[0]:obj[1] for obj in (obj.split('=') for obj in inp.split('&')) if len(obj) == 2}
def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type """ color = '#6495ED' # Default if layertype == 'Convolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF...
def physical_focal_length_from_calibration( f: float, sensor_diagonal_mm: float, image_diagonal_pixels: float ) -> float: """Compute the physical focal length of our camera, in millimeters. Args: f (float): Calibrated focal length, using pixel units. sensor_diagonal_mm (float): Length acros...
def MIN(*expression): """ Returns the minimum value. See https://docs.mongodb.com/manual/reference/operator/aggregation/min/ for more details :param expression: expression/expressions or variables :return: Aggregation operator """ return {'$min': list(expression)} if len(expression) > 1 ...
def readable_keyword(s): """Return keyword with only the first letter in title case.""" if s and not s.startswith("*") and not s.startswith("["): if s.count("."): library, name = s.rsplit(".", 1) return library + "." + name[0].title() + name[1:].lower() else: ...
def argsort(seq): """ Same as NumPy's :func:`numpy.argsort` but for Python sequences. :param seq: a sequence :return: indices into `seq` that sort `seq` """ return sorted(range(len(seq)), key=seq.__getitem__)
def build_conditional(column, row): """Build string for conditional formatting formula for exporting to Excel.""" substring = '' if isinstance(row, list): for country in row: substring = substring + f'$A4="{country}",' substring = 'OR(' + substring[:-1] + ')' # remove last comma,...
def move(position, instruction): """ Take a position and offset it based on instuction, or raise an error on invalid instruction. Keyword arguments: position --- current position as a tuple (x,y) Instruction --- single-character instruction to move in ["^", "v", ">", "<"] """ if instruction == "^": ...
def is_empty_list(l): """Check if a list only contains either empty elements or whitespace """ return all(s == '' or s.isspace() for s in l)
def clean_schema(lst): """This method cleans the list items so that they can be compared. - Strips space - Remove trailing/leading spaces - convert to lower case Args: lst (list): List to be cleaned Returns: list : Cleaned list """ schema=[] for col in lst:...
def every(predicate, seq): """True if every element of seq satisfies predicate. Ex: every(callable, [min, max]) ==> 1; every(callable, [min, 3]) ==> 0""" for x in seq: if not predicate(x): return False return True
def sort_by_timestamp(messages): """ Sort a group of messages by their timestamp. """ return sorted(messages, key=lambda x: x["timestamp"])
def remove_apostrophe(text): """Remove apostrophes from text""" return text.replace("'", " ")
def override_kwargs(block_kwargs, model_kwargs): """ Override model level attn/self-attn/block kwargs w/ block level NOTE: kwargs are NOT merged across levels, block_kwargs will fully replace model_kwargs for the block if set to anything that isn't None. i.e. an empty block_kwargs dict will remove kwa...
def get_grid_coordinates(img_num, grid_size, w, h): """ given an image number in our sprite, map the coordinates to it in X,Y,W,H format""" y = int(img_num / grid_size) x = int(img_num - (y * grid_size)) img_x = x * w img_y = y * h return "%s,%s,%s,%s" % (img_x, img_y, w, h)
def exception_models_to_message(exceptions: list) -> str: """Formats a list of exception models into a single string """ message = "" for exception in exceptions: if message: message += "\n\n" message += f"Code: {exception.code}" \ f"\nMessage: {exception.message}" \ ...
def summarize_numeric(st): """ Summarize a set of numbers. Args: st: The set to summarize. Returns: The the min, max, and mean value in the set. """ ret = dict() ret['max'] = max(st) ret['min'] = min(st) ret['mean'] = float(sum(st)) / len(st) # for extra mark :) r...
def to_bin(s): """ :param s: string to represent as binary """ r = [] for c in s: if not c: continue t = "{:08b}".format(ord(c)) r.append(t) return '\n'.join(r)
def _normalizeWhitespace(text): """ Remove leading and trailing whitespace and collapse adjacent spaces into a single space. @type text: C{unicode} @rtype: C{unicode} """ return u' '.join(text.split())
def isint(str): """ Is the given string an integer >>> isint(str('1234')) 1 >>> isint(str('11a')) 0 """ ok = 1 if not str: return 0 try: int(str) except ValueError: ok = 0 except TypeError: ok = 0 return ok
def dynamic(array, length): """For k = 2""" if length == 1: return array[0] if length == 2: return array[1] return max( array[-1] + dynamic(array[:-1], length - 1), array[-2] + dynamic(array[:-2], length - 2) )
def _ensure_width(inp: str, width: int): """ Ensure that string `inp` is exactly `width` characters long. """ return inp[:width].ljust(width)
def hex_to_bool(val): """Converts hex string or boolean integer to a clean boolean value. Returns a boolean data type True or False """ if type(val) == str: val = val.strip("0x").rstrip("0") if val: return True else: return False
def determine_overall_status(qc_json): """Currently PASS no matter what """ qc_json.update({'overall_quality_status': 'PASS'}) return qc_json
def decode_image(layers, w, h): """ 0 - black, 1 - white, 2 - transparent """ result = [0 for x in range(w * h)] for y in range(h): for x in range(w): for layer in layers: p = layer[y * w + x] if p == 2: continue else: ...
def each(xs:list, f) -> list: """each(xs, f) e.g. xs >> each >> f Answers [f(x) for x in xs]""" return [f(x) for x in xs]
def double_RandomizedBenchmarkingDecay(numCliff, p, offset, invert=1): """ A variety of the RB-curve that allows fitting both the inverting and non-inverting exponential. The amplitude of the decay curve is constrained to start at 0 or 1. The offset is the comm...
def bio2ot_ote(ote_tag_sequence): """ perform bio-->ot for ote tag sequence :param ote_tag_sequence: :return: """ new_ote_sequence = [] n_tags = len(ote_tag_sequence) for i in range(n_tags): ote_tag = ote_tag_sequence[i] if ote_tag == 'B' or ote_tag == 'I': ne...
def get_progress(processed, total): """ Based on how many items were processed and how many items are there in total return string representing progress (e.g. "Progress: 54%") :param processed: number of already processed items :param total: total number of items to be processed :return: string ...
def GetMangledParam(datatype): """Returns a mangled identifier for the datatype.""" if len(datatype) <= 2: return datatype.replace('[', 'A') ret = '' for i in range(1, len(datatype)): c = datatype[i] if c == '[': ret += 'A' elif c.isupper() or datatype[i - 1] in ['/', 'L']: ret += c....
def format_text(info, item, indentation): """Format text with embedded code fragment surrounded by backquote characters.""" new_lines = [] for line in info[item].split("\n"): if "`" in line and line.count("`") % 2 == 0: fragments = line.split("`") for index, fragment in enume...
def merge_dicts(*dict_args): """Merges the dictionaries given in arguments together.""" result = {} for dictionary in dict_args: result.update(dictionary) return result
def hook_with_extra_is_in_hooks(word, hooks): """ Determine if the word given is the name of a valid hook, with extra data hanging off of it (e.g., `validhookname=extradata`). hook_with_extra_is_in_hooks( 'validhookname=stuff', ['validhookname', 'other']) #=> True ho...
def interpolate(value, arg): """ Interpolates value with argument """ try: return format(value % arg) except: return ''
def my_func_2(x: float, y: int) -> float: """Returns the result of pow(x, y). >>> my_func_2(2, -2) 0.25 """ result = 1 for i in range(abs(y)): result /= x return result
def transform_to_dict(closest_list: list) -> dict: """ Returns dict {(latitude, longitude): {film1, film2, ...}, ...} from closest_list [[film1, (latitude, longitude)], ...], where film1, film2 are titles of films, (latitude, longitude) is a coordinates of a place where those films were shoot. ...
def power_n( data, power=2.0, verbose=False ): """Returns the voxel-wise power of either a data array or a NIfTI-1 image object. To get the nth root, use 1/power. nth root of either a data array or a NIfTI image object. E.g. power_n(nii, 1./3) returns a NIfTI image whose voxel values are cube ...