content
stringlengths
42
6.51k
def listify(iterable): """Try to force any iterable into a list sensibly.""" if isinstance(iterable, list): return iterable if isinstance(iterable, (str, int, float)): return [iterable] if not iterable: return [] if callable(iterable): iterable = iterable() return...
def strip_resolution(key): """ Removes the resolution from the lookup key. Args: (str): Lookup key (col&exp&chan&resolution). Returns: (str) """ return key.rsplit('&', 1)[0]
def create_import_error_msg( extra_module: str, forte_module: str, component_name: str, pip_installable: bool = True, ): """ Create an error message for importing package extra required by a forte module. Args: extra_module: module name should be installed by pip. forte...
def peal_speed_to_blow_interval(peal_minutes: float, num_bells: int) -> float: """ Calculate the blow interval from the peal speed, assuming a peal of 5040 changes """ peal_speed_seconds = peal_minutes * 60 seconds_per_whole_pull = peal_speed_seconds / 2520 # 2520 whole pulls = 5040 rows return seconds...
def num_to_emoji(n): """ Convert number to discord emoji Parameters ---------- n : str string number Returns ------- str discord emoji if valid, False otherwise """ num_emoji_map = { "1": ":one:", "2": ":two:", "3": ":three:", "4": ":four...
def flatten_list(input_list): """ Args: input_list: 2-d list Returns: 1-d list """ output_list = [] for i in input_list: output_list.extend(i) return output_list
def expand_dotted_dict(root): """ Expand dotted dictionary keys. Parameters ---------- root : dict The dictionary to expand. Returns ------- dct : dict The expanded dictionary. """ if not root: return {} if not isinstance(root, dict): raise ...
def verify_approval_skip(data, env, env_configs): """Determines if a approval stage can be added/removed from a given environment pipeline stage based on environment setting. Defaults to false, and verifies administrators allow skips in given environments. Args: data (dict): environment config d...
def _generate_command_by_dict( mydict: dict, # Debug verbose: bool = False, ): """ Generate an array based on dictionary with keys and values """ array_command = [] # append to a list for key, value in mydict.items(): array_command.extend([key, value]) if verbose: ...
def reverse_log(log): """Concatenates lines in reverse order""" return "\n".join(log.split("\n")[::-1])
def partition3_direct_dp(arr): # (Max time used: 0.16/10.00, max memory used: 19165184/536870912.) """ In order to equally partition the souvenirs into 3 bags, each bag must have size = sum(arr) / 3, since the input are all integers, the partition size must be integers rather than float numbers. Let A ...
def parse_hpo_gene(hpo_line): """Parse hpo gene information Args: hpo_line(str): A iterable with hpo phenotype lines Yields: hpo_info(dict) """ if not len(hpo_line) > 3: return {} hpo_line = hpo_line.rstrip().split("\t") hpo_info = {} hpo_info["h...
def _str(s): """ Convert PTB tokens to normal tokens """ if (s.lower() == '-lrb-'): s = '(' elif (s.lower() == '-rrb-'): s = ')' elif (s.lower() == '-lsb-'): s = '[' elif (s.lower() == '-rsb-'): s = ']' elif (s.lower() == '-lcb-'): s = '{' elif (s.lowe...
def is_number(item: str) -> bool: """Return True if the string is a number, False otherwise. """ try: float(item) return True except TypeError: return False except ValueError: return False
def recursiveFactorial(num): """assumes num is a positive int returns an int, num! (the factorial of n) """ if num == 0: return 1 else: return num * recursiveFactorial(num-1)
def t_name_to_flan_pattern_name(t_name: str) -> str: """Converts `t_name` to flan `PATTERN` key. Some seqio tasks use the same flan patterns. Args: t_name: Task config name. Returns: a key for `PATTERNS`. """ if 'para_crawl' in t_name: return 'para_crawl' elif 'wmt16_translate' in t_name: ...
def index_in_complete_solution(individual, complete_solution): """Returns the index of an individual in a complete solution based on its type.""" for i in range(len(complete_solution)): if type(complete_solution[i]) == type(individual): return i # else: # return None
def merge_two_dicts(x, y): """Merges two dicts, returning a new copy.""" z = x.copy() z.update(y) return z
def _static_folder_path(static_url, static_folder, static_asset): """ Returns a path to a file based on the static folder, and not on the filesystem holding the file. Returns a path relative to static_url for static_asset """ # first get the asset path relative to the static folder. # stati...
def tflops_per_second(flops, dt): """ Computes an effective processing rate in TFLOPS per second. TFLOP/S = flops * / (dt * 1E12) Args: flops: Estimated FLOPS in the computation. dt: Elapsed time in seconds. Returns: The estimate. """ return flops / (1E12 * dt)
def bindingType(b): """ Function returns the type of a variable binding. Commonly 'uri' or 'literal'. """ type = b['type'] if type == "typed-literal" and b['datatype'] == "http://www.w3.org/2001/XMLSchema#string": type = 'literal' return type
def suffix_unless_suffixed(text: str, suffix: str) -> str: """ Passed string either suffixed by the passed suffix if this string is not yet suffixed by this suffix *or* this string as is otherwise (i.e., if this string is already suffixed by this suffix). Parameters ---------- text : str ...
def _find_tools_paths(full_args): """Finds all paths where the script should look for additional tools.""" paths = [] for idx, arg in enumerate(full_args): if arg in ['-B', '--prefix']: paths.append(full_args[idx + 1]) elif arg.startswith('-B'): paths.append(arg[2:]) ...
def zellers_congruence(day, month, year): """ For a given date year/month/day this algorithm returns the weekday of that date (1 = Monday, 2 = Tuesday, etc.) For details see https://en.wikipedia.org/wiki/Zeller%27s_congruence """ # Consistent variable names with the formula on on Wikipedia ...
def rand_bytes(number_of_bytes: int) -> bytes: """ generate random bytes :param number_of_bytes: the number of bytes :return: the bytes """ from os import urandom return urandom(number_of_bytes)
def reversetext(contenttoreverse, reconvert=True): """ Reverse any content :type contenttoreverse: string :param contenttoreverse: The content to be reversed :type reeval: boolean :param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True". """ ...
def horizon_error(ground_truth_horizon, detected_horizon, image_dims): """Calculates error in a detected horizon. This measures the max distance between the detected horizon line and the ground truth horizon line, within the image's x-axis, and normalized by image height. Args: ground_trut...
def scale_axis(axis_bounds, lower_scale=None, upper_scale=None): """ Calculates the new bounds to scale the current axis bounds. The new bounds are calculated by multiplying the desired scale factor by the current difference of the upper and lower bounds, and then adding (for upper bound) or subtra...
def upper(s): """ Number of upper case letters in a string. Solution for day 4. >>> upper("UpPer") 2 >>> upper("alllower") 0 """ # Current number of upper case letters found upper = 0 # Loop through all the letters in the string and if it is upper, increase fo...
def remove_nested_parens(input_str): """ Returns a copy of string with any parenthesized (..) [..] text removed. Nested parentheses are handled. It also returns a Boolean asserting if the parenthesis were well balanced (True) or not (False). """ result1 = '' paren_level = 0 for ch in inp...
def get_at(doc, path, create_anyway=False): """Get the value, if any, of the document at the given path, optionally mutating the document to create nested dictionaries as necessary. """ node = doc last = len(path) - 1 if last == 0: return doc.get(path[0]) for index, edge in e...
def longest_target_sentence_length(sentence_aligned_corpus): """ :param sentence_aligned_corpus: Parallel corpus under consideration :type sentence_aligned_corpus: list(AlignedSent) :return: Number of words in the longest target language sentence of ``sentence_aligned_corpus`` """ max_m ...
def make_histogram(s: list) -> dict: """Takes a string or a list, finds its elements frequency and returns a dictionary with element-frequency as key-value pairs. """ d = dict() for char in s: d[char] = 1 + d.get(char, 0) return d
def parse_mygene_src_version(d): """ Parse source information. Make sure they are annotated as releases or with a timestamp d: looks like: {"ensembl" : 84, "cpdb" : 31, "netaffy" : "na35", "ucsc" : "20160620", .. } :return: dict, looks likes: {'ensembl': {'id': 'ensembl', 'release': '87'}, ...
def round_steps(stop, steps): """Return number of round steps from '0' to 'stop'.""" return int(round(stop // steps * steps))
def parse_drive_size(line): """Parses a drive line in the partition information file. """ parts = line.split(":") if len(parts) != 2 or parts[0] != "drive": raise ValueError("Drive size line format is 'drive:<size>'") return parts[1]
def fmt_time(value): """ < 60 seconds -> displayed in seconds (limit the decimal digits to 1 or keep int) < 3600 seconds -> display as X m Y s (if float, trim decimal digits) >= 3600 seconds -> display as X h Y m Z s (if float, trim decimal digits) :param value: seconds or None :return: Formatte...
def storage_format(number: int) -> str: """Format a number representing a bytes of storage according to our convention Uses convention that 1 GB = 1000^3 bytes Parameters ---------- number : int A number of bytes to format Returns ------- str The formatted storage strin...
def process_purchase(purchase): """ # Takes in a list of tuples with two elements. Puts the # elements into dictionary by second element with # values being the first element and returns. >>> process_purchase([('rice', 'mitsuwa'), ('msg', '99ranch'), \ ('eggs', 'costco')]) {'mitsuwa': [...
def trim(txt): """remove empty braces until done""" while True: edited = txt.replace( "{}","").replace( "[]","").replace( "<>","").replace( "()","") if edited == txt: return txt txt = edited
def equal_division(input_string, length_of_division): """ Divide a string up into a list of strings, each string as long as the specified length of division. Discard remainder. """ divisions = [] if len(input_string) < 2: raise ValueError('A single character cannot be divided') while...
def _has_method(obj, method): """ Given an object determine if it supports the method. Args: obj: Object which needs to be inspected. method: Method whose presence needs to be determined. Returns: Boolean depending upon whether the method is available or not. """ return getattr(obj, method, Non...
def decode(current_output: bytes) -> str: """ bytes to str """ encodings = ["sjis", "utf8", "ascii"] decoded_current_output = "" for enc in encodings: try: decoded_current_output = current_output.decode(enc) break except: continue return de...
def isprefix(path1, path2): """Return true is path1 is a prefix of path2. :param path1: An FS path :param path2: An FS path >>> isprefix("foo/bar", "foo/bar/spam.txt") True >>> isprefix("foo/bar/", "foo/bar") True >>> isprefix("foo/barry", "foo/baz/bar") False >>> ispre...
def parse_epic_link(el): """Extract key of epic this issue belongs to (if given), else ''. Example XML: <customfields> <customfield id="customfield_10730" key="com.pyxis.greenhopper.jira:gh-epic-link"> <customfieldname>Epic Link</customfieldname> <customfieldvalues> <customf...
def binary_search_rotated(key, arr, left, right): """ Search in a sorted rotated array. """ if left > right: return False middle = (left + right) / 2 if arr[left] == key or arr[middle] == key or arr[right] == key: return True if arr[middle] <= arr[right]: # Right side is s...
def get_digit(n, i): """ i=0 for units, i=1 for tens, t=2 for hundreds... """ return int(str(n)[::-1][i])
def filter(record): """ Filter for testing. """ return record if record["str"] != "abcdef" else None
def update_inc(initial, key, count): """Update or create a dict of `int` counters, for JSONField.""" initial = initial or {} initial[key] = count + initial.get(key, 0) return initial
def _standardize_and_copy_config(config): """Returns a shallow copy of config with lists turned to tuples. Keras serialization uses nest to listify everything. This causes problems with the NumericColumn shape, which becomes unhashable. We could try to solve this on the Keras side, but that would require lot...
def _parse_date(s): """'31/05/11' --> '2011-05-31'""" day, month, year = [int(x) for x in s.split('/')] if year < 15: year = 2000 + year if (year < 2001 or year > 2015): return None if (month < 1 or month > 12) or (day < 1 or day > 31): return None return '%04d-%02d-%02d'...
def remap(x, oldmin, oldmax, newmin, newmax): """Remap the float x from the range oldmin-oldmax to the range newmin-newmax Does not clamp values that exceed min or max. For example, to make a sine wave that goes between 0 and 256: remap(math.sin(time.time()), -1, 1, 0, 256) """ zero_to_one...
def _modulo_ab(x: float, a: float, b: float) -> float: """Map a real number onto the interval [a, b).""" if a >= b: raise ValueError("Incorrect interval ends.") y = (x - a) % (b - a) return y + b if y < 0 else y + a
def merge_dicts(*dict_args): """ Credits: https://stackoverflow.com/a/26853961 Ref: https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts....
def check_xlsx(b64_data): """check hex signature of b64 file""" return len(b64_data) >= 4 and b64_data[:4].hex() == '504b0304'
def join_year_month(year, month): """Joins year and month for parsing with pd.to_datetime.""" return str(year) + '-' + str(month)
def rec_key_change(key): """ Change recommendation key to numerical values """ if key == 'none': return 0 elif key == 'hold': return 1 elif key == 'buy': return 2 elif key == 'strong_buy': return 3
def calc_term_overlap(termsA, termsB): """ Calculate the reciprocal overlap between two lists of HPO terms """ nA = len(termsA) nB = len(termsB) if nA == 0 or nB == 0: ro = 0 else: nOvr = len(set(termsA).intersection(set(termsB))) oA = nOvr / nA oB = nOvr / ...
def multiFind(string,substring): """Return a list if integers indicating where the substring begins in the string. Substrings are not allowed to overlap themselves: multifind('pppp','pp') = [0,2] If there are no matches, return [] """ start = 0 indices = [] while True: start ...
def replace_char_at_index(org_str, index, replacement): """Replace character at index in string org_str with the given replacement character.""" new_str = org_str if index < len(org_str): new_str = org_str[0:index] + replacement + org_str[index + 1 :] return new_str
def parse_boolean(s): """Parse an environment variable string into a boolean. Considers empty string, '0', 'no', or 'false' (case insensitive) to be ``False``; all other values are ``True``. """ return s.lower() not in {'', '0', 'no', 'false'}
def flatten_component_tree(tree: dict) -> list: """Flattens a component tree into a list of its final leaves. Traverses the tree recursively until it meets terminating nodes, then collects all those terminating nodes into a list. :param tree: A dictionary of dictionaries any number of levels deep as r...
def detect_code_block(lines, index, limit): """ Detects a code block and returns it's last line +1's index, or the source index if not found. Parameters ---------- lines : `list` of `str` The lines of the section. index : `int` The starting index of the code block. limit : `...
def modular_geometric_sum(x, n, mod): """ Compute a_n = (1 + a^1 + ... + a^{n-1}) % mod using that a_{2n} = ((x_n + 1) * a_n) % mod a_{2n+1} = (x^{2n} + a_{2n}) % mod """ if n == 1: return 1 % mod elif n % 2 == 0: return ((pow(x, n // 2, mod) + 1) * modular_geometri...
def dict_of_list__to__list_of_dicts(dict, n_items): """ ``` x = {'foo': [3, 4, 5], 'bar': [1, 2, 3]} ppp.dict_of_list__to__list_of_dicts(x, 3) # Output: # [ # {'foo': 3, 'bar': 1}, # {'foo': 4, 'bar': 2}, # {'foo': 5, 'bar': 3}, # ] ``` :param dict: :param...
def find_workflow_steps(tool_id,steps): """ Finds appropriate steps in workflow given tool id. :param tool_id: The tool id to search. :param steps: Dictionary of steps in workflow. :return: List of matching steps. """ matches=[] for step in steps: if (steps[step]['tool_id'] ==...
def is_pandigital(number, include_zero=False): """Determine if a number (as a string) is pandigital""" number_set = set(number) if include_zero: length = 10 else: length = 9 if '0' in number_set: return False return len(number_set) == len(number) == length
def remove_leading_spaces(data): """ Remove the leading spaces (indentation) of lines of code :param data: input data as a list of files, where each file is a list of strings :return: input data with leading spaces removed """ print('Removing leading spaces ...') for i in range(len(data)): ...
def build_cmd(seq, out_file, query_id, args): """ Builds a command to run blast.py on the command line. :param seq: A fasta sequence to BLAST :param out_file: The name of the file to store the results in :param query_id: The id of the query :param args: A dictionary of arguments need for th...
def words_from_text(s, words_to_ignore=[]): """ Lowercases a string, removes all non-alphanumeric characters, and splits into words. """ words = [] word = '' for c in ' '.join(s.split()): if c.isalpha(): word += c elif word: if word not in words_to_ignore:...
def get_minutes(minutes): """ (number) -> number Return minutes left as after converting it into hh:mm:ss format Precondition: minutes >= 0 >>> get_minutes(3800) 3 """ return (minutes // 60) % 60
def format_bird(ip_version, bird_version, cmd): """Prefixes BIRD command with the appropriate BIRD CLI command. Arguments: ip_version {int} -- IPv4/IPv6 bird_version {int} -- BIRD version cmd {str} -- Unprefixed command Returns: {str} -- Prefixed command """ cmd_pre...
def _default_init(targ_prob: float, acc_max: float, num_inp: int, num_para: int): """Decide the default integrator chain methods and arguments depending on the problem Parameters ---------- targ_prob : float target failure probability acc_max : float target tol...
def shQuote(text): """quote the given text so that it is a single, safe string in sh code. Note that this leaves literal newlines alone (sh and bash are fine with that, but other tools may mess them up and need to do some special handling on the output of this function). """ return "'%s'" % text.replace("'", r"'\'...
def render_operation_progress_summary_stages(stages): """ Renders the provided operation progress stages. :param stages: progress stages to render :return: rendered string """ result = '\n|\t'.join( map( lambda entry: '{}: [{}] step(s) done'.format(entry[0], len(entry[1]['st...
def cover_phone_number(no): """ >>> cover_phone_number('01234 567 890') '01234 *** *** **' """ result = '' for order, digit in enumerate(no): if order < 5: result = result + digit else: if order in (5, 8, 11): result = result + ' ' ...
def merge_two_dicts_shallow(x, y): """ Given two dictionaries, merge them into a new dict as a shallow copy. merging two dict that support Python 2 according https://stackoverflow.com/a/26853961/2212582 unfortunately the fastest `**` unpack method will result in syntax error on Python 2 """ z = ...
def makeRevisionOptionStr(revision): """ :param revision: a revision number, or string('HEAD', 'BASE', 'COMMITTED', 'PREV'), or revision range tuple """ if not revision: return '' # some command(svn log...) support revision range if isinstance(revision, tuple) or isinstance(revisi...
def score_distance(d, ka, coop=1): """ Given some distance d, returns a score on (0,1]. A d of 0 scores 0, and a d of inf scores 1. gamma defines the distance at which the score is 0.5. Modeled off the Hill equation Args: d: The value to score ka: The value at which the score is 0.5 ...
def labeloff(lines, splice_from=5): """strip off the first splice_from characters from each line Warning: without check!""" return [line[splice_from:] for line in lines]
def set_windows_slashes(directory): """ Set all the slashes in a name so they use Windows slashes (\) :param directory: str :return: str """ return directory.replace('/', '\\').replace('//', '\\')
def _suitable_samples(pred_folders, gold_folders): """Returns the path of each sample contained in both prediction and gold standard folders.""" gold_samples = [] pred_samples = [folder.split('/')[-2] for folder in pred_folders] # some folders in Larson's gold standard have a folder named 'Registe...
def split_schema_obj(obj, sch=None): """Return a (schema, object) tuple given a possibly schema-qualified name :param obj: object name or schema.object :param sch: schema name (defaults to 'public') :return: tuple """ qualsch = sch if sch is None: qualsch = 'public' if '.' in ob...
def cmset_and(x,y): """ Usage: >>> cmset_and(x,y) returns the index of the elements of array x which are also present in the array y. This is equivalent to using the IDL command >>> botha=cmset_op(namea, 'AND', nameb, /index) i.e. performs the same thing as the IDL routine `cmset_op <http://cow.physics.wisc.edu/...
def solver_problem2(inputs): """ Count the number of increasement from each sum of 3 number from give list """ num_increased = 0 for i in range(1, len(inputs) - 2): # sum_prev = inputs[i-1] + inputs[i] + inputs[i+1] # sum_curr = inputs[i] + inputs[i+1] + inputs[i+2] # (sum_curr...
def get_caption(attributes, feature, label, group=None): """Construct caption from plotting attributes for (feature, label) pair. Parameters ---------- attributes : dict Plot attributes. feature : str Feature. label : str Label. group : str, optional Group. ...
def row_to_dict(field_names, data, null_to_empty_string=False): """ Converts a tuple result of a cx_Oracle cursor execution to a dict, with the keys being the column names :param field_names: The names of the columns in the result set (list) :param data: The data in this r...
def _validate_other_libs(other_libs): """ Validates the other_libs parameter. Makes it a list, if it isn't already and verifies that all the items in the list are python modules with the required functions. Raises a TypeError, if the other_libs parameter is not valid. :param other_libs: parameter...
def calc_tile_locations(tile_size, image_size): """ Divide an image into tiles to help us cover classes that are spread out. tile_size: size of tile to distribute image_size: original image size return: locations of the tiles """ image_size_y, image_size_x = image_size locations = [] ...
def get_fileid_val(file_identifier, key_value_data, fileid_value): """ Get file identifier value """ file_id_found = False for key in key_value_data: if file_identifier and not file_id_found and file_identifier in key: fileid_value = key[1] file_id_found = True if n...
def get_value(obj, key, default=None): """ Returns dictionary item value by name for dictionary objects or property value by name for other types. Also list of lists obj is supported. :param obj: dict or object :param key: dict item or property name :param default: default value :return: ...
def qual(clazz): """ Return full import path of a class """ return clazz.__module__ + '.' + clazz.__name__
def validate_token(token): """ validate a token agains oauth2.Token object """ if token is not None and not hasattr(token, "key"): raise ValueError("Invalid token.") return token
def _clean_list(id_list): """ return a list where all elements are unique """ id_list.sort() r_list = [] last_element = None for x in id_list: if x != last_element: r_list.append(x) last_element = x return r_list
def get_mu_tilda(x_i, r, n): """Calculates the conditional descendant normal distribution *expectation* for generation-gap n. Latex equation: tilde{\mu}_{i+n} = r^n X_i (See the paper for the derivation.)""" return (r**n) * x_i
def _set_development_risk_icon(risk): """ Function to find the index risk level icon for development environment risk. :param float risk: the Software development environment risk factor. :return: _index :rtype: int """ _index = 0 if risk == 0.5: _index = 1 elif risk =...
def get_test_name( name ): """ This module maps PHPBench benchmark names to the names that are used accross the teams. Args: name (str): Name of the benchmark Returns: The mapped name Raises: KeyError when the name passed in does not match any of the keys """ ...
def _get_location(location_text): """Used to preprocess the input location_text for URL encoding. Doesn't do much right now. But provides a place to add such steps in future. """ return location_text.strip().lower()
def clamp(x, x0, x1): """Clamp the value x to be within x0, x1 (inclusive).""" return max(min(x, x1), x0)
def sum_abs(number_list): """Return the sum of the absolute values of ``number_list``. Parameters ---------- number_list : list of int Returns ------- int """ return sum([abs(x) for x in number_list])