content
stringlengths
42
6.51k
def CreatePattern(week_cap, days): """Smooth the weekly capacity over the selected number of days. Evenly spread the capacity across the week, with any excess added in increments of one starting at first day of the week. """ average = week_cap/days excess = week_cap%days pattern = [int(...
def GetElapsedMs(start_time, end_time): """Return milliseconds elapsed between |start_time| and |end_time|. Args: start_time: seconds as a float (or string representation of float). end_time: seconds as a float (or string representation of float). Return: milliseconds elapsed as integer. """ retu...
def generate_url(date: str) -> str: """ generate a url for the download, given a date string in format YYYY-mm-dd""" base_url = 'https://www.rollingstone.com/charts/albums/' url = base_url + date + '/' return url
def json_api_patch(original, patch, recurse_on=set({})): """Patch a dictionary using the JSON API semantics. Patches are applied using the following algorithm: - patch is a dictionary representing a JSON object. JSON `null` values are represented by None). - For fields that are not in `recursive_...
def breadcrumb(*args): """"Render a breadcrumb trail Args: args (list) : list of urls and url name followed by the final name Example: url1, name1, url2, name2, name3 """ def pairs(l): a = iter(l) return list(zip(a,a)) return { 'urls': pairs(ar...
def label_breakdown(data): """ Find the label breakdown in data. """ res = {} for row in data: # if valid label if (row[3]): res[row[1]] = row[7] neg, neu, pos = 0, 0, 0 for key in res.keys(): r = res[key] if (r == -1): neg += 1 ...
def encode(data): """Encodes a netstring. Returns the data encoded as a netstring. data -- A string you want to encode as a netstring. """ if not isinstance(data, (bytes, bytearray)): raise ValueError("data should be of type 'bytes'") return b''.join((str(len(data)).encode('utf8'), b':',...
def match_in_dat(query, target): """ Check if given query is matched in target object data. :param query: query to match. :param target: object to match query. :return: bool (True if matched, else False) """ intersection = set(query.items()).intersection(set(target.items())) intersectio...
def merge_list_of_lists(list_of_lists): """ Merge a list of lists into one flat list list_of_lists: a list contains many lists as items Return merged a list """ merged_list = sum(list_of_lists, []) return merged_list
def convert_feature_to_vector(feature_list): """ :param feature_list: :return: """ index = 1 xt_vector = [] feature_dict = {} for item in feature_list: feature_dict[index] = item index += 1 xt_vector.append(feature_dict) return xt_vector
def _get_short_satellite_code(platform_code): """ Get shortened form of satellite, as used in GA Dataset IDs. (eg. 'LS7') :param platform_code: :return: >>> _get_short_satellite_code('LANDSAT_8') 'LS8' >>> _get_short_satellite_code('LANDSAT_5') 'LS5' >>> _get_short_satellite_code('L...
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: ? Space Complexity: ? Does this have to be contiguous? """ if nums == None: return 0 if len(nums) == 0: retur...
def seperate(aln_dict, leaf_dict): """ Separate the query sequences from the reference sequences Parameters ---------- aln_dict : Sequence dictionary with taxon label keys leaf_dict : Sequence dictionary with leaf label keys (queries are not in backbone tree) Returns ------- se...
def is_iterable(obj): """ Semantics: Test whether an object is iterable. By definition, it is an iterable if it has an iter method implemented. Returns: Boolean """ try: iter(obj) except: return False else: return True
def factorial(x): """ Input: x: some integer number Output: factorial of input number. """ fact = 1 for n in range(1, x+1): fact *= n return fact
def to_field_name(value): """ This template tag is used to convert a list of words into a single word that does not contain spaces. The words are capitalized as they are joined. It is used in some templates to get the correct knowledge base link for fields or components. Es. 'text classific...
def anti_vowel(text): """takes a string text and returns the text with all of the vowels removed.""" result="" for i in text: if i in "aeiouAEIOU": pass else: result+=i return result
def clean_chars(command: str) -> str: """ replaces character with mongodb characters format :param command: discord command to be converted :type command: str :return: converted command :return type: str """ clean_freq_data = command if "." in clean_freq_data: cle...
def get_second_of_day(t): """ Converts a seconds since epoch timestamp to the number of seconds, that have elapsed on the current day of the timestamp. For example the timestamp 1619891033 represents Saturday, May 1, 2021 5:43:53 PM. This would be converted to 63833 since at this day, this number o...
def merge(arr1: list, arr2: list) -> list: """Merge two arrays for merge sort Args: arr1 (list): the first array arr2 (list): the second array Returns: list: the merged array """ merged = [] # Compare elements for both arrays while arr1 and arr2: if (arr1[0...
def find_bound_tuple(a, b, bounds): """If a and b are both included in a bounds tuple, return it. Otherwise return None. """ def inside(num, spanish): return num >= spanish[0] and num <= spanish[1] for span in bounds: if inside(a, span) and inside(b, span): retu...
def listToSqlStr(values): """Converts list items into SQL list sequence. :param list values: list of value to be converted into SQL list sequence :return: SQL list values representation :rtype: str >>> listToSqlStr([4, 5, "Ahoj"]) "(4, 5, 'Ahoj')" """ return str(values).replace("[", "(...
def parse_clnsig(acc, sig, revstat, transcripts): """Get the clnsig information Args: acc(str): The clnsig accession number, raw from vcf sig(str): The clnsig significance score, raw from vcf revstat(str): The clnsig revstat, raw from vcf transcripts(iterable(dict)) Returns...
def encode(sequences, converter=["<None>", "<Unknown>"]): """encode a set of sequences using a converter, building it as it goes""" newSeqs = [] for seq in sequences: newSeq = [] for filename in seq: if filename not in converter: converter.append(filename) ...
def retype(dictobj, dict_type): """ Recursively modifies the type of a dictionary object and returns a new dictionary of type dict_type. You can also use this function instead of copy.deepcopy() for dictionaries. """ def walker(dictobj): for k in dictobj.keys(): if isinstance...
def MarineRegionsOrg_LonghurstProvinceFileNum2Province(input, invert=False, rtn_dict=False): """ Get the Longhurst province Parameters ------- input (str): input string to use as key to return dictionary value invert (float): reverse the ke...
def _join_dicts(*dicts): """ joins dictionaries together, while checking for key conflicts """ key_pool = set() for _d in dicts: new_keys = set(_d.keys()) a = key_pool.intersection(new_keys) if key_pool.intersection(new_keys) != set(): assert False, "ERROR: dicts ...
def get_closest_dist(pts): """returns the closest point from the list of intersections. Uses Manhattan Distance as metric for closeness. Args: pts: a list of (x, y) tuples Returns the manhattan distance from (0,0) of the closest pt in pts """ dists = [(abs(pt[0]) + abs(pt[1])) ...
def is_bool(value): """Must be of type Boolean""" return isinstance(value, bool)
def is_leapyear(year): """ determines whether a given year is a leap year :param year: year to check (numeric) :return: boolean """ flag = year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) return flag
def percent(numerator, denominator): """ :param numerator: float Numerator of fraction :param denominator: float Denominator of fraction :return: str Fraction as percentage """ if denominator == 0: out = "0" else: out = str(int(numerator / float(denom...
def substitute_nested_terms(raw_query, substitutions): """ This function searches for keywords immediately followed by a dot ('.') that is not within double quotes and appends "_nested" to found keywords :param raw_query: :param substitutions: :return: Substituted raw_query """ subbed_ra...
def scale_range(value): """Scale a value from 0-320 (light range) to 0-9 (NeoPixel range). Allows remapping light value to pixel position.""" return round(value / 320 * 9)
def associate_prefix(firstname, lastname): """ Prepends everything after the first space-delineated word in [firstname] to [lastname]. """ if ' ' in firstname: name, prefix = firstname.split(' ',1) # split on first space else: name, prefix = firstname, '' space = ' '*(prefix ...
def __percent_format(x, pos=0): """Tick formatter to render as percentage """ return '%1.0f%%' % (100 * x)
def DemoNode(in_): """ +-----------+ | DemoNode | |-----------| o in_<> | | out<> o +-----------+ """ return {"out": in_}
def calc_primers(volume, primerinitial, primerfinal, samples): """primer calculation""" primers = round((volume / primerinitial) * primerfinal * samples, 1) return primers
def _nest_level(pl: list) -> int: """Compute nested levels of a list iteratively""" if not isinstance(pl, list): return 0 level = 0 for item in pl: level = max(level, _nest_level(item)) return level + 1
def changes_dict_to_set_attribute(metakey, changes_dict, end=";"): """Convert dictionart of changes to set_attribute instructions""" result = [] for key, (value, old) in changes_dict.items(): result.append("set_attribute({!r}, {!r}, {!r}, old={!r})".format(metakey, key, value, old)) return "\n"....
def floatlist(val): """Turn a string of comma-separated floats into a list of floats. """ return [float(v) for v in val.split(',')]
def connection(value): """ Return a string of comma-separated values """ if not value: return None else: # expecting a list of dicts like so: # [{'id': '5e7b63a0c279e606c645be7d', 'identifier': 'Some String'}] identifiers = [conn["identifier"] for conn in value] ...
def closest(values, elements, scope=None, strict=True): """Return closest (index, elem) of sorted values If 2 elements have same distance to a given value, second elem will be return has closest. Example: > closest([1, 4], [0, 2, 3]) [(1, 2), (2, 3)] """ res = [] def a...
def printd (msg): """ prints the debug messages """ #for debug #print msg return 0 f= open(Config.MONITOR_LOG,'r+') f.seek(0, 2) f.write(str(msg)+"\n") f.close()
def isECBEncrypted(data): """We'll consider that the data is ECB-encrypted iof we find twice the same block (block length is assumed to be 16 bytes)""" if len(data) % 16 != 0: raise Exception('Data length must be a multiple of 16 bytes') blocks = [data[i*16:(i+1)*16] for i in range(len(data)//16)] res = {}...
def e2f(b): """empty to float""" return 0 if b == "" else float(b)
def parse_spd_hexdump(filename): """Parse data dumped using the `spdread` command in LiteX BIOS This will read files in format: Memory dump: 0x00000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................ 0x00000010 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f ..........
def simple_filter(**kwargs): """Return a simple filter that requires all keyword arguments to be equal to their specified value.""" criteria = [] for key, value in kwargs.items(): criteria.append({'type': 'SIMPLE', 'propertyName': key, 'operator': 'Equals', 'operand': va...
def grid_points_2d(length, width, div, width_div=None): """Returns a regularly spaced grid of points occupying a rectangular region of length x width partitioned into div intervals. If different spacing is desired in width, then width_div can be specified, otherwise it will default to div. If div < 2 i...
def get_norm_value(json_entity, prop): """\ Get a normalized value for a property (always as a list of strings). """ value = json_entity.get(prop, []) if not isinstance(value, list): value = [value] try: return [_ if isinstance(_, str) else _["@id"] for _ in value] except (Ty...
def get_function_pointer(type_string): """ convert the function types to the pointer type """ return type_string[0:type_string.find('(')-1] + " (*)" + type_string[type_string.find('('):]
def absolute(n: int) -> int: """Gives the absolute value of the passed in number. Cannot use the built in function `abs`. Args: n - the number to take the absolute value of Returns: the absolute value of the passed in number """ if n < 0: n = -1 * n return n
def build_results_dict(tournament_results): """ builds results. Returns an object of the following form: { team-1: { matches_played: int, wins: int, draws: int, losses: int, points: int, } team-2: { ... }...
def size_scale(values, s_min, s_max): """ Parameters ---------- values : ndarray values to be displayed using the size of the scatter points s_min : float minimum value this set of values should be compared to s_max : float maximum value this set of values should be comp...
def expand_scope_by_name(scope, name): """ expand tf scope by given name. """ if isinstance(scope, str): scope += '/' + name return scope if scope is not None: return scope.name + '/' + name else: return scope
def generate_file(size_in_mb: int) -> str: """ Generate a file of a given size in MB, returns the filename """ filename = f"{size_in_mb}MB.bin" with open(filename, "wb") as f: f.seek(size_in_mb * 1024 * 1024 - 1) f.write(b"\0") return filename
def get_recursively(search_dict, field): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided. """ fields_found = [] keys=[] for key, value in search_dict.items(): if key == field: fields_found.append(value) ...
def permute_all_atoms(labels, coords, permutation): """ labels - atom labels coords - a set of coordinates permuation - a permutation of atoms Returns the permuted labels and coordinates """ new_coords = coords[:] new_labels = labels[:] for i in range(len(permutation)): new_...
def upper(value, n): """Converts a string into all uppercase""" return value.upper()[0:n]
def subtour_calculate(n, edges): """Given a list of edges, finds the shortest subtour""" visited = [False] * n cycles = [] lengths = [] selected = [[] for i in range(n)] for x, y in edges: selected[x].append(y) while True: current = visited.index(False) this_cycle =...
def fileNameOf(path): """Answer the file name part of the path. >>> fileNameOf('../../aFile.pdf') 'aFile.pdf' >>> fileNameOf('../../') is None # No file name True """ return path.split('/')[-1] or None
def remove_short_lines(lyrics): """ Takes the lyrics of a song and removes lines with less than 3 words. Normally these lines don't have any meaningful meaning """ try: paragraphs = lyrics.split("\r\n\r\n") new_paragraphs = list() new_lines = list() for paragraph...
def percent_change(d1, d2): """Calculate percent change between two numbers. :param d1: Starting number :type d1: float :param d2: Ending number :type d2: float :return: Percent change :rtype: float """ return (d2 - d1) / d1
def _build_arguments(keyword_args): """ Builds a dictionary of function arguments appropriate to the index to be computed. :param dict keyword_args: :return: dictionary of arguments keyed with names expected by the corresponding index computation function """ function_arguments = {"dat...
def is_annotated_with_loads(prop: property) -> bool: """ Is the property annotated with @lohasattr(prop, )ads_attributes? """ return hasattr(prop.fget, '_loads_attributes')
def is_array(obj): """ Checks if a given sequence is a numpy Array object. Parameters ---------- obj : object The input argument. Returns ------- test result : bool The test result of whether seq is a numpy Array or not. >>> import numpy as np >>> is_array([1,...
def partition_refinement(partition_a, partition_b): """Check if a refines b, returns Boolean (True/False). Trivial example, for a homogeneous network the bottom nodes (nothing merged) refines the top node (all merged), but not the other way round: >>> partition_refinement([0,1,2,3],[0,0,0,0]) ...
def get_elapsed_time_string(elapsed_time, rounding=3): """Format elpased time Parameters ---------- elapsed_time : float Elapsed time in seconds rounding : int Number of decimal places to round Returns ------- processing_time : float Scaled amount elapsed time ...
def mover_torre1(tablero, x_inicial, y_inicial, x_final, y_final): """ (list of list, int, int, int, int) -> list of list :param tablero: list of list que representa el tablero :param x_inicial: int que representa la posicion inicial en X :param y_inicial: int que representa la posicion inicial en Y...
def format_model_name(model_name, specific_params): """ Given the model name and input parameters, return a string ready to include as a name field in simulated graphs. """ batch_size = specific_params['batch_size'] if 'resnet' in model_name: layers = ''.join(filter(lambda x: x.isdigit()...
def get_payment_callback_payload(Amount=500, CheckoutRequestID="ws_CO_061020201133231972", MpesaReceiptNumber="LGR7OWQX0R"): """Response received from the server as callback after calling the stkpush process request API.""" return { "Body":{ "stkCallback":{ "MerchantRequestID":"19465-780693-1", "Checkout...
def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool: """Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s). Used primarily for checking against the registered command data from Discord. Will not work great if values inside the dictionary ca...
def FindOverlapLength( line_value, insertion_text ): """Return the length of the longest suffix of |line_value| which is a prefix of |insertion_text|""" # Credit: https://neil.fraser.name/news/2010/11/04/ # Example of what this does: # line_value: import com. # insertion_text: com.youcompleteme...
def normalise_to_zero_one_interval(y, ymin, ymax): """Because I always forget the bloody formula""" if ymin > ymax: raise TypeError('min and max values the wrong way round!') return (y - ymin) / (ymax - ymin)
def get_main_categories(categories): """ Given a list of categories, returns the top level categories with name""" main_categories = {} for key in categories.keys(): if len(str(key)) <= 2: main_categories[key] = categories[key] return main_categories
def nextpow2(i): """ Find the next power of 2 for number i """ n = 1 while n < i: n *= 2 return n
def lookup(registered_collection, reg_key): """Lookup and return decorated function or class in the collection. Lookup decorated function or class in registered_collection, in a hierarchical order. For example, when reg_key="my_model/my_exp/my_config_0", this function will return registered_collection["my_...
def parse_list_of_str(val): """Parses a comma-separated list of strings""" return val.split(',')
def dec(bytes: bytes) -> str: """Decodes bytes to a string using ASCII.""" return bytes.decode("ascii")
def least_difference(a, b, c): """Return the smallest difference between any two numbers among a, b and c. >>> least_difference(1, 5, -5) 4 """ diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3)
def precision_k(actuals: list, candidates: list, k: int) -> float: """ Return the precision at k given a list of actuals and an ordered list of candidates """ if len(candidates) > k: candidates = candidates[:k] return len(set(actuals).intersection(candidates)) / min(k, len(candidates))
def replacenewline(str_to_replace): """Escapes newline characters with backslashes. Args: str_to_replace: the string to be escaped. Returns: The string with newlines escaped. """ if str_to_replace is None: return None return str_to_replace.replace( "\r\n", "\\n").replace("\r", "\\n").rep...
def isolate_path_filename(uri): """Accept a url and return the isolated filename component Accept a uri in the following format - http://site/folder/filename.ext and return the filename component. Args: uri (:py:class:`str`): The uri from which the filename should be returned Returns: ...
def dp_make_weight(egg_weights, target_weight, memo = {}): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is always a egg of value 1. Parameters: egg_weights - tuple of integers, available egg wei...
def retangulo(lado_a,lado_b): """calcula a area de um retangulo""" area= lado_a*lado_b return area
def has_permission(request): """ Hard code has_permission for admin header """ return { 'has_permission': hasattr(request, 'user') and request.user.is_authenticated }
def try_int(num_string): """ short hand cast to number :param num_string: :return: int or None """ if num_string is not None: try: return int(num_string) except ValueError: pass return None
def parse_config(config_string): """ Parse the config string to a list of strings. Lines starting with '#' are ignored. Strings are split on commas :param config_string: String as read from the config file :return: List of general predicate strings to filter """ strings = [] ...
def _recursive_flatten(cell, dtype): """Unpack mat files in Python.""" if len(cell) > 0: while not isinstance(cell[0], dtype): cell = [c for d in cell for c in d] return cell
def get_tab_indent(n): """ Get the desidered number of indentations as string Parameters ------------- n Number of indentations Returns ------------- str_tab_indent Desidered number of indentations as string """ return "".join(["\t"] * n)
def new_tuple(nt_type, values): """ Create a new tuple of the same type as nt_type. This handles the constructor differences between tuple and NamedTuples :param nt_type: type of tuple :param values: values as sequence :return: new named tuple """ if nt_type == tuple: # Use regu...
def truncate(str, length = 60, reverse = False): """ Truncate a string to the specified length. Appends '...' to the string if truncated -- and those three periods are included in the specified length """ if str == None: return str if len(str) > int(length): if reverse: ...
def get_header_block(content, depth): """ generates the five column headers as exemplified below: AS/1 AS/1/LABEL AS/1/ID AS/1/NOTE AS/1/ABBR """ output = content + "/" + str(depth) + "\t" output += content + "/" + str(depth) + "/LABEL\t" output += content + "/" + str(depth) + "/ID\t" ou...
def func_x_a_kwargs(x, a=2, **kwargs): """func. Parameters ---------- x: float a: int kwargs: dict Returns ------- x: float a: int kwargs: dict """ return x, None, a, None, None, None, None, kwargs
def get_binary_category(score): """Get an integer binary classification label from a score between 0 and 1.""" if score < 0.5: return 0 else: return 1
def has_repeated_n_gram(tokens, disallowed_n=3): """ Returns whether the sequence has any n_grams repeated. """ seen_n_grams = set() for i in range(len(tokens) - disallowed_n + 1): n_gram = tuple(tokens[i: i + disallowed_n]) if n_gram in seen_n_grams: return True ...
def strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ('y', 'yes...
def invalid_request_body_with_invalid_priority( valid_client_model, valid_staff_model ): """ A fixture for creating a request body with invalid priority. Args: valid_client_model (Model): a valid client model created by a fixture. valid_staff_model (Model): a valid staff model created b...
def discreteTruncate(number, discreteSet): """ Truncates the number to the closest element in the positive discrete set. Returns False if the number is larger than the maximum value or negative. """ if number < 0: return False discreteSet.sort() for item in discreteSet: if number...
def count_common_tags(tags_list1, tags_list2): """ :param tags_list1: The first list of tags :param tags_list2: The second list of tags :return: The number of tags in common between these 2 slides """ common_tags_cpt = 0 tags_List1_tmp = tags_List2_tmp = [] if len(tags_list1) ...
def parse_commands(filename): """ Reads the configuration file with the model name and features, separated by spaces model_name feat1 feat2 feat3 .... """ models = [] with open(filename) as f: for line in f.read().split('\n'): tokens = line.split(' ') if len(token...