content
stringlengths
42
6.51k
def get_max_array_dimension(signature): """Gets the number of array dimensions in this signature.""" return_value = 0 while signature.find((return_value + 1) * 'a') != -1: return_value += 1 return return_value
def is_prefix(x, pref): """Check prefix. Args: x (list): token id sequence pref (list): token id sequence Returns: (boolean): whether pref is a prefix of x. """ if len(pref) >= len(x): return False for i in range(len(pref)): if pref[i] != x[i]: ...
def merge_option_dicts(old_opts, new_opts): """ Update the old_opts option dictionary with the options defined in new_opts. Instead of a shallow update as would be performed by calling old_opts.update(new_opts), this updates the dictionaries of all option types separately. Given two dictionarie...
def compute_image_size(args): """Computes resulting image size after a convolutional layer i=input channel, o=output channel, k = kernel size, s = stride, p = padding, d = dilation old_size = size of input image, new_size= size of output image. """ old_size, i, o, k, s, p, d = args new_size ...
def maxVelocity(l1, l2, v2): """ This function takes perihelion, aphelion distances and minimum velocity to calculate the maximum velocity at the aphelion in AU/year. This equation is taken from Lab4 handout. """ return (l2*v2)/l1
def _check_sectors(sect): """Checks the sectors input to :py:func:`partition_demand_by_sector` and :py:func:`partition_flexibility_by_sector`. :param set/list sect: The input sectors. Can be any of: *'Transportation'*, *'Residential'*, *'Commercial'*, *'Industrial'*, or *'All'*. :return: (*set*...
def GetMultiRegionFromRegion(region): """Gets the closest multi-region location to the region.""" if (region.startswith('us') or region.startswith('northamerica') or region.startswith('southamerica')): return 'us' elif region.startswith('europe'): return 'eu' elif region.startswith('asia') o...
def g_iter(n): """Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) 10 >>> g_iter(5) 22 >>> from construct_check import check >>> # ban recursion >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion']) Tr...
def in_bin(input_num, bin_len): """ in_bin stands for "in binary" """ assert len(bin(input_num)) - 2 <= bin_len format_str= "{0:0"+ str(bin_len) + "b}" return format_str.format(input_num)
def stage_changer(stage_string): """ Input: A string specifying the stage of the given tumor. Output: An integer representing the stage of the given tumor. """ if (stage_string == 'stage i') or (stage_string == 'stage ia') or (stage_string == 'stage ib') or (stage_string == 'stage ic') or (stage_str...
def bright_color(color: str): """ Return the bright version of color, doens't work for RESET""" if color != "\u001b[0m": return color.replace("m", ";1m") return color
def to_collection(val, val_type, col_type): """ Validate and cast a value or values to a collection. Args: val (object): Value or values to validate and cast. val_type (type): Type of each value in collection, e.g. ``int`` or ``str``. col_type (type): Type of collection to return, e...
def sort(array): """ The most naive version of Selection Sorting algorithm. """ length = len(array) # Traverse through all elements in array for i in range(len(array)): # Find the minimum element in remaining unsorted array index = i for j in range(i+1, len(array)): ...
def guard_none(obj): """ Return a value, or a placeholder to draw instead if it is None. """ if obj is None: return "-" return obj
def slope(x1, y1, x2, y2): """ Finds slope from two points """ return (y2-y1)/(x2-x1)
def build_person(first_name, last_name, age=''): # Returning a dictionary. """Return a dictionary of information about a person.""" if age: return {'first': first_name, 'last': last_name, 'age': age} return {'first': first_name, 'last': last_name}
def check_choice(choice): """Validate choice for yes or no""" return choice == 'y' or choice == 'n'
def replace(key: str, value: str, line: str) -> str: """ Replaces a key with a value in a line if it is not in a string or a comment and is a whole word. Complexity is pretty bad, so might take a while if the line is vvveeeerrrrryyyyyy long. """ i = 0 in_string = False in_comment = Fals...
def _label(label): """ Returns a query item matching a label. Args: label (str): The label the message must have applied. Returns: The query string. """ return f"label:{label}"
def modular_exponentiation(b, e, m): """produced modular exponentiation. https://en.wikipedia.org/wiki/Modular_exponentiation :param b: a base number. :param e: an exponent. :param m: a modulo. :return: a reminder of b modulo m. """ x = 1 y = b while e > 0: if e % 2 == 0...
def dart_web_application_outputs(output_js, dump_info, emit_tar, script_file): """Returns the expected output map for dart_web_application.""" output_js = output_js or "%s.js" % script_file.name outputs = { "js": output_js, "deps_file": "%s.deps" % output_js, "sourcemap": "%s.map" % ...
def _is_xml(s): """Return ``True`` if string is an XML document.""" return s.lower().strip().startswith('<?xml ')
def has_imm(opcode): """Returns True if the opcode has an immediate operand.""" return bool(opcode & 0b1000)
def fetch_priority(repset, args_array, **kwargs): """Function: fetch_priority Description: Stub holder for mongo_rep_admin.fetch_priority function. Arguments: (input) repset -> Replication set instance. (input) args_array -> Array of command line options and values. """ err_ms...
def str2bool(val): """ Convert string expression to boolean :param val: Input value :returns: Converted message as boolean type :rtype: bool """ return val.lower() in ("yes", "true", "t", "1")
def int_if_close(floating_number, tolerance=0.0001): """ Numbers printed in log files etc. (even integers) may have many decimal places. In programming integers may be more useful. This function converts such floating numbers to integers. :type floating_number: float | str :param floati...
def get_string_trailing(line, begin_at): """get the training part of sub-string starting from provided index Args: line (str): string line begin_at (int): sub-str start point Raises: TypeError: Raise error if input is invalid or sub-string falls outside Returns: str: sub-string """ tr...
def __get_int_ordinals(string): """ Return the integer ordinals of a string. """ output = "" for char in string: output += str(ord(char)).rjust(3, " ") + ", " output = output.rstrip(", ") return output
def clean_text(text): """ split and clean the text. :param text: text tokennized. :return: """ #text = re.sub("[A-Za-z0-9]", "", text) text = [x for x in text.split(" ") if x!=''] return text
def factorial(n: int) -> int: """Implement factorials recursively Raise: - TypeError for given non integers - ValueError for given negative integers """ if type(n) is not int: raise TypeError("n isn't integer") if n < 0: raise ValueError("n is negative") result = 1 ...
def make_version_string(version_info): """ Turn a version tuple in to a version string, taking in to account any pre, post, and dev release tags, formatted according to PEP 440. """ version_info = list(version_info) numbers = [] while version_info and isinstance(version_info[0], int): ...
def ClearAllIntegers(data): """ Used to prevent known bug; sets all integers in data recursively to 0. """ if type(data) == int: return 0 if type(data) == list: for i in range(0, len(data)): data[i] = ClearAllIntegers(data[i]) if type(data) == dict: for k, v i...
def add_variables_to_expression(query_dict: dict, variables: dict) -> dict: """Attempt to make it easier to develop a query""" ea_names = query_dict.get("ExpressionAttributeNames", {}) ea_values = query_dict.get("ExpressionAttributeValues", {}) for k, v in variables.items(): name = f"#{k}" ...
def convert_annotation_to_actions(annotations): """ annotations: dict that map a string to a list of annotated sections. Each section is defined by a list of ordered frame indices """ result_str = "" return result_str
def genomic_dup5_rel_38(genomic_dup5_loc): """Create test fixture relative copy number variation""" return { "type": "RelativeCopyNumber", "_id": "ga4gh:VRC.vy8SSVFuaeZTkUCCv6izNCkF0zgbBG7G", "subject": genomic_dup5_loc, "relative_copy_class": "partial loss" }
def _check_delimiter(output_filename, delim=None): """Detect delimiter by filename extension if not set""" if output_filename and (delim is None): delimiters = {"tsv": "\t", "csv": ","} delim = delimiters[output_filename.rsplit(".", 1)[-1].lower()] assert delim, "File output delimiter no...
def wikilinks_files(path): """ :param path: directory where wikilinks files are stored :return: a list of wikilinks files (assuming their names are in form data-0000x-of-00010 """ filenames = [path + '/data-0000{0}-of-00010'.format(i) for i in range(10)] return filenames
def convertb2d_(res, decimals): """Round the result.""" cad = str(round(res, decimals)) return cad
def find_factors(num): """Find factors of num, in increasing order. >>> find_factors(10) [1, 2, 5, 10] >>> find_factors(11) [1, 11] >>> find_factors(111) [1, 3, 37, 111] >>> find_factors(321421) [1, 293, 1097, 321421] """ return_lst = [] for i in range(1, num + 1): ...
def _replace_pairwise_equality_by_equality(pc): """Rewrite pairwise equality constraints to equality constraints. Args: pc (list): List of dictionaries where each dictionary is a constraint. It is assumed that the selectors in constraints were already processed. Returns: pc (li...
def prune_empty(d): """ Remove empty lists and empty dictionaries from d (similar to jsonnet std.prune but faster) """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): if len(d) > 0: return [v for v in (prune_empty(v) for v in d) if v is not None]...
def station_data(filename): """ Returns data from filename such as Route number, station index, station id, station name """ station = dict() raw_data = filename.split('-') station['route_nr'] = raw_data[0] station['order'] = raw_data[1] station_data_raw = ''.join(raw_data[2:]) ...
def contains_recursive(text, pattern, index=None): """Return a boolean indicating whether pattern occurs in text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) if index is None: index = 0 ...
def roundPrecision(number, precision=4): """ Rounds the given floating point number to a certain precision, for output.""" return float(('{:.' + str(precision) + 'E}').format(number))
def cmp_compat(a, b): """ Simple comparison function :param a: :param b: :return: """ return (a > b) - (a < b)
def kaldi_lvl_to_logging_lvl(lvl: int) -> int: """Convert kaldi level to logging level""" if lvl <= 1: lvl = lvl * -10 + 20 else: lvl = 11 - lvl return lvl
def is_palindrome(s): """ Decide if a string is a palindrome or not. >>> is_palindrome("abba") True >>> is_palindrome("python") False """ return s == s[::-1]
def split_in_half(input_points): """ This function takes in a list of points, splits this list in half and return the two new lists containing each subset of the input points. Parameters ---------- input_points : list The set of points to be split Returns -------...
def noll_to_zernike(j): """ Convert linear Noll index to tuple of Zernike indices. j is the linear Noll coordinate, n is the radial Zernike index, and m is the azimuthal Zernike index. Parameters ---------- j : int j-th Zernike mode Noll index Returns ------- (n, m) : tuple...
def eval_func_tuple(f_args): """Takes a tuple of a function and args, evaluates and returns result""" return f_args[0](*f_args[1:])
def header(data): """Returns the netstring header for a given string. data -- A string you want to produce a header for. """ return str(len(data)).encode('utf8') + b":"
def normalize_knot_vector(knot_vector, decimals=4): """ Normalizes the input knot vector between 0 and 1. :param knot_vector: knot vector to be normalized :type knot_vector: list, tuple :param decimals: rounding number :type decimals: int :return: normalized knot vector :rtype: list """...
def cnn_pooling_output_length(input_length, filter_size, pooling_size, border_mode, stride, dilation=1): """ Compute the length of the output sequence after 1D convolution along time. Note that this function is in line with the function used in Convolution1D class from Keras. ...
def wrap(string, left="[", right="]"): """Wrap a string in two delimiters iff the string is non empty (or None).""" if string: return left+string+right return ""
def rgb_to_xy(red, green, blue): """ conversion of RGB colors to CIE1931 XY colors Formulas implemented from: https://gist.github.com/popcorn245/30afa0f98eea1c2fd34d Args: red (float): a number between 0.0 and 1.0 representing red in the RGB space green (float): a number between 0.0 and 1.0 ...
def splitFirstLine(data): """Extracts the first line from `data' and returns a tuple: (firstline, rest).""" part = data.partition("\n") return (part[0], part[2])
def hide_graph(input): """Only show graph if there is data.""" if input: return {"display": "block"} else: return {"display": "none"}
def euclidean_gcd(a, b): """ Euclidean algorithm Complexity: O(log(min(A, B)) Euclidean algorithm to find the GCD of two numbers. It takes advantage of the property GCD(a, b) = GCD(b, a%b). Cool property: GCD(a, b) * LCM(a, b) = a * b """ if b == 0: return a return euc...
def SplitNewStyleEmpty(newstyle): """Splits according to one of the forms of path elements this code uses. See tests/test-path_utils.py for semantics. Args: newstyle: 'newstyle' path. Returns: List of tokens from path argument. """ tokens = newstyle.split(".") newstyle_tokens = [] while to...
def rob(nums): """ You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent...
def items_to_text(items: list) -> str: """ Converting more items to text for easy use in prettify. """ output = '' for item in items: output += item + ', ' return output[:-2]
def lookup_config_from_database(database): """ Read configuration values that might be already defined in the database configuration file. """ if database is not None: annotation_type = database.annotation_type fixed_positions = database.fixed_positions memory_demanding = ( ...
def reduced_mass(mass1, mass2): """ Calculates reduced mass :param mass1: mass 1 :param mass2: mass 2 :return: reduced mass """ top = mass1 * mass2 bot = mass1 + mass2 output = top / bot return output
def delete_before(list, key): """ Return a list with the the item before the first occurrence of the key (if any) deleted. """ if list == (): return () else: head1, tail1 = list if tail1 == (): return list else: head2, tail2 = tail1 ...
def get_detector_type(meta): """ Gets the IRIS detector type from a meta dictionary. In this function, FUV1 and FUV2 are just assigned as FUV. Parameters ---------- meta: dict-like Dictionary-like object containing entry for "detector type" Returns ------- detector_type: `...
def strip_endlines(in_arg): """Remove eol characters Linux/Win/Mac (input can be string or list of strings).""" if isinstance(in_arg, (tuple, list)): buff = [] for x in in_arg: if isinstance(x, bytes): buff.append(x.rstrip().decode('utf-8')) elif isinstan...
def normalize_0_1_min_max(data, _min, _denominator, reverse=False): """ Normalize data in a [0, 1] interval, using the minmax technique. It involves subtracting the minimum, and then dividing by the range (maximum - minimum) :param data: the data to normalize; normalization is NOT performed in situ, so ...
def s3_key_for_revision_metadata(wiki, pageid, revid): """Computes the key for the S3 object storing metadata about a revision.""" return '{:s}page_{:08d}/rev_{:08d}.yaml'.format( wiki['s3_prefix'], pageid, revid )
def consistent_typical_range_stations(stations): """Applies typical_range_consistent to a list of station objects and returns a list of all station OBJECTS which have consistent data""" # Creates empty list output_list = [] # Iterates over stations to find all stations with inconsistent range ...
def is_master(config): """True if the code running the given pytest.config object is running in a xdist master node or not running xdist at all. """ return not hasattr(config, 'slaveinput')
def isUniqueSFW(str): """ Given a string, checks if the string has unique charachters Note that this solution is inefficient as it takes O(n^2) """ l = len(str) for i in range(l): for j in range(l): if i != j and not ord(str[i]) ^ ord(str[j]): return False ...
def circulation_cds_extension_max_count(loan): """Return a default extensions max count.""" unlimited = loan.get("extension_count", 0) + 1 return unlimited
def read_vocabulary(vocab_file, threshold): """read vocabulary file produced by get_vocab.py, and filter according to frequency threshold. """ vocabulary = set() for line in vocab_file: word, freq = line.split() freq = int(freq) if threshold == None or freq >= threshold: ...
def correlate_lists(lst1, lst2, ignore_pin_nums=False): """ """ if ignore_pin_nums: for k in range(len(lst1)): lst1[k] = lst1[k].split(".")[0] # try: # pin_num = lst1[k].split(".")[1] # except: # pin_num = '' # if pin_n...
def get_companies_house_number(activity): """Returns the companies house number of an activity""" return activity['object']['attributedTo']['dit:companiesHouseNumber']
def get_version(iterable) -> str: """ Get the version of the WDL document. :param iterable: An iterable that contains the lines of a WDL document. :return: The WDL version used in the workflow. """ if isinstance(iterable, str): iterable = iterable.split('\n') for line in iterable: ...
def convert_bool(value): """helper to make sure bools are bools""" if value in (True, False): return value if value is None: return False if str(value).lower() in ('true', '1'): return True return False
def reduce_list(data_set): """ Reduce duplicate items in a list and preserve order """ seen = set() return [item for item in data_set if item not in seen and not seen.add(item)]
def day_of_week_one_line(y, m, d): """Oneliner just for fun.""" return (y - (m < 3) + (y - (m < 3)) // 4 - (y - (m < 3)) // 100 + (y - (m < 3)) // 400 + ord('-bed=pen+mad.'[m]) + d) % 7
def bytes_to_str(data: bytes) -> str: """Converts a list bytes to a string of 1s and 0s. """ output = '' for b in data: bb = bin(b)[2:].ljust(8, '0') output += bb return output
def get_current_version(config): """Return the current version of the config. :return: current config version or 0 if not defined """ return config.get('CONFIG_VERSION', {}).get('CURRENT', 0)
def combine_segments(segment_list): """Combines a list of lists that are segments (each segment is list of strings) and returns a single list of strings, segments are assumed to be the same length""" combined_list=[] for index,row in enumerate(segment_list[0]): new_row="" for segment in ...
def _google_temp_unit(units): """Return Google temperature unit.""" if units: return "F" return "C"
def wild_card_find_doc(inverted_index, wild_card_tokens): """search in inverted index and find posting lists of all words which find them related to the wildcars Arguments: inverted_index {dictionary} -- dictionary of tokens and posting-lists wild_card_tokens {list} -- all words find them b...
def calculateBounds(sentences): """Given a list of sentence strings, calculate their bounds as character offsets from 0 """ curbound, bounds = 0, [] for s in sentences: bounds.append((curbound, curbound + len(s))) curbound += len(s) + 1 commabounds = [','.join((str(b) for b in bnds))...
def lat_fixed_formatter(y): """Simple minded latitude formatter. Only because those available in cartopy do not leave a blank space after the degree symbol so it looks crammed. If used outside this module, bear in mind this was thought to be used as part of an iterator to later be included in a ...
def deduplicate_non_disjoint_tuple_spans(list_tuple_span): """ auxiliary function for find_all_with_dict_regex given the input list of tuple spans, when there are two spans that span on one another, eliminate the smallest from the list """ list_tuple_span = sorted(list_tuple_span, key=lambda ...
def get_position (pair, s_mention) : """Get the position of the antecedent : {beginning (0) , middle(1), end (2)} of the sentence """ antd_index=int(pair[0][-1])-1 if antd_index == 0 : return 0 if antd_index == len(s_mention) -1 : return 2 return 1
def getFirstPlist(textString): """Gets the next plist from a text string that may contain one or more text-style plists. Returns a tuple - the first plist (if any) and the remaining string after the plist""" plist_header = '<?xml version' plist_footer = '</plist>' plist_start_index = textStr...
def max_profit(stocks: list) -> int: """ Time Complexity: O(n) Space Complexity: O(1) """ start, end = 0, len(stocks) - 1 result: int = 0 while start < end: buy = stocks[start] index = start + 1 profit = 0 while index <= end and buy < stocks[index]: ...
def recurrence_str_to_sec(recurrence_str): """Convert recurrence string to seconds value. Args: recurrence_str: The execution recurrence formatted as a numeric value and interval unit descriptor, e.b., 1d for a daily recurrence. Returns: Recurrence in seconds or None if input is...
def shape_attr_name(name, length=6, keep_layer=False): """ Function for to format an array name to a maximum of 10 characters to conform with ESRI shapefile maximum attribute name length Parameters ---------- name : string data array name length : int maximum length of strin...
def passenger_spawn(state, next_state): """ Compare state with next state to determine if new passenger is spawn """ return (state[7] == -1 and state[8] == -1) and (next_state[7] != -1 and next_state[8] != -1)
def should_skip(cls, res): """Determine if the subnetwork is especially small, and if we should skip it. """ return (cls == 'Property' and len(res) < 4000) or (cls == 'Gene' and len(res) < 125000)
def is_atom(unknown_object): """Determines whether an object is an atom or a collection""" if hasattr(unknown_object, 'shape'): return True if hasattr(unknown_object, '__len__') and not hasattr(unknown_object, 'keys'): return False return True
def modular_pow(base, exponent, modulus): """Source: https://en.wikipedia.org/wiki/Modular_exponentiation""" if modulus == 1: return 0 c = 1 for i in range(0, exponent): c = (c * base) % modulus return c
def serialize_persona_fisica_moral(persona): """ '#/components/schemas/tipoPersona' """ if persona: return "FISICA" else: return "MORAL"
def build_dir_list(project_dir, year_list, product_list): """Create a list of full directory paths for downloaded MODIS files.""" dir_list = [] for product in product_list: for year in year_list: dir_list.append("{}\{}\{}".format(project_dir, product, year)) return dir_list
def format_bytes_size(val): """ Take a number of bytes and convert it to a human readable number. :param int val: The number of bytes to format. :return: The size in a human readable format. :rtype: str """ if not val: return '0 bytes' for sz_name in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']: if val < ...
def convert_el(edges): """ Convert from a relation dictionary to single edgelist representation. :param edges: :param n: :return: A dictionary mapping nodes to outgoing triples. """ res = [] for rel, (froms, tos) in edges.items(): for fr, to in zip(froms, tos): res....