content
stringlengths
42
6.51k
def allowed_file(filename, extensions={'csv'}): """ Checks if a filename contains an allowable extension. Parameters ---------- filename : str The filename to check. extensions : set The set of allowable file extensions. Returns ------- allowed : bool True i...
def add_zeros(x, n): """Private function for multiplications""" x_digits = str(x) for degree in range(n): x_digits += '0' return int(x_digits)
def sum_min_edge_weight(acc, w1, w2): """Sums up edge weights by adding the minum of w1 and w2. This results in lower weighted edges for margin figures. """ return acc + min(w1, w2)
def format_string(input_): """Formats the input depending on if it is a string or a list of strings. Determines the type of the input. If it is a string then strips leading spaces and lowercases all letters. If it is a list, then the aforementioned process is applied to each of the list elements. Arg:...
def get_coach_data(filename): """ :param filename: eg: 'james.txt' :return: list which has removed null and ',' """ try: with open(filename) as f: data = f.readline() return data.strip().split(',') except IOError as ioerr: print('File error: ' + str(ioerr)) ...
def filter_messages_keep(frame_ids_to_keep, array_of_msgs): """Given an array of can msgs, remove the messages that have ids NOT in frame_ids_to_keep and return. If the data field is in bytearray format it will be changed to str. """ filtered_arr = [] for msg in array_of_msgs: frame_id,...
def mul(a,b): """ component-wise 3 vector multiplication""" return [a[0]*b[0],a[1]*b[1],a[2]*b[2],1.0]
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. (Pre-Python 3.5) (http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression) """ result = {} ...
def clip(val, lower=0, upper=100): """Limit value to be between lower and upper limits""" return max(lower, min(val, upper))
def parse_host(hostname, default_port): """Translate something like 'foobar:123' -> ('foobar', 123).""" port = default_port num_cols = hostname.count(":") if num_cols: index = hostname.rindex(":") if num_cols > 1: for i in range(len(hostname) - 1, index, -1): ...
def exp_out(t): """Exponential out. :math:`f(t) = 2^t`""" return 1 - pow(2, -10 * t)
def build_logfile_path(logname, logType, threadId, log_num=1): """ Helper to create a logfile path incorporating the thread ID in the filename before the file type suffix. @param logname: The valid base path without the thread Id. @type logname: Str @param logType: The type of log (e.g. fuzzing) @...
def convert_to_object(obj_dict): """ Function that takes in a dict and returns a custom object associated with the dict. This function makes use of the "__module__" and "__class__" metadata in the dictionary to know which object type to create. """ if "__class__" in obj_dict: # Pop ensur...
def isYes(string): """Returns True if the string represents a yes, False, if it represents no, and another string if it represents something else""" value = string.strip().lower() if value in ['yes', 'always', 'on', 'true']: return True if value in ['no', 'never', 'off', 'false', 'null']: ...
def _threshold_calc(random_edge, max_edge, vertex_degree): """ Calculate threshold for branch_gen function. :param random_edge: number of vertex edges :type random_edge: int :param max_edge : maximum edge number :type max_edge : int :param vertex_degree: vertex degree :type vertex_degre...
def find_cavities(grid): """ :type grid: list[list[str]] :rtype: list[list[str]] """ for i in range(1, len(grid) - 1): for j in range(1, len(grid[i]) - 1): if ( (grid[i - 1][j] != 'X' and int(grid[i][j]) > int(grid[i - 1][j])) and ...
def shell_quote(var): """ Escape single quotes and add double quotes around a given variable. Args: _str (str): string to add quotes to Returns: str: string wrapped in quotes .. warning:: This is not safe for untrusted input and only valid in this context (``os.environ``). ...
def get_color(color_dict, colors): """ retrive the absolute number corresponding a color set by color_dict""" for i, color in enumerate(colors): for data in color: equal = True for k, v in data.items(): if k not in color_dict or v != color_dict[k]: ...
def rigidity_bending_plate(height, e_modulus, poisson): """ Calculates the bending rigidity of a plate. """ return e_modulus * (height ** 3) / (12 * (1 - poisson ** 2))
def implies(x, y): """ Returns "x implies y" / "x => y" """ return not(x) or y
def merge_schemas(schema, old_schema): """ Merges two JSON schemas on a column. """ if old_schema is None: return schema elif schema['type'] != old_schema['type']: return old_schema elif 'enum' in schema and 'enum' in old_schema: merged_enum = list(old_schema['enum']) ...
def filter_dict_keys(orig_dict, keys_to_keep, *, optional=False): """ Returns a copy of a dictionary filtered by a collection of keys to keep Args: orig_dict (dict): A dictionary keys_to_keep (iterable): Keys to filter on optional (bool): If True, ignore keys that don't exist in the...
def find_range(iterable, predicate): """Find the indices of the first range of consecutive items which satisfy the given predicate. Returns (-1, -1) if it there is no such ranges. find_range([0, 0, 1, 1, 0], lambda e: e > 0) => (2, 4) """ iterator = enumerate(iterable) start_index = next((i for...
def euclidean_distance(point_a, point_b): """ Returns the euclidean distance between two points with (i, j) coordinates. """ return (point_a[0] - point_b[0]) ** 2 + (point_a[1] - point_b[1]) ** 2
def max_lt(seq, val): """ Return greatest item in seq for which item < val applies. None is returned if seq was empty or all items in seq were >= val. """ max = 0 idx = len(seq) - 1 while idx >= 0: if seq[idx] < val and seq[idx] >= 0 and seq[idx] > max: max = seq[idx] ...
def validate_rng_seed(seed, min_length): """ Validate random hexadecimal seed. returns => <boolean> seed: <string> hex string to be validated min_length: <int> number of characters required. > 0 """ if len(seed) < min_length: print("Error: Computer entropy must be at least {0} cha...
def convert_to_bq_string(mapping_list): """ Converts list of lists to bq INSERT friendly string :param mapping_list: list of lists where the inner lists have two items :return: bq INSERT formatted string """ bq_insert_list = [] for hpo_rdr_item in mapping_list: bq_insert_list.append(...
def find(word,letter): """ find letter in word , return first occurence """ index=0 while index < len(word): if word[index]==letter: #print word,' ',word[index],' ',letter,' ',index,' waht' return index index = index + 1 return -1
def _simplify_device_name(device): """/job:localhost/replica:0/task:0/device:CPU:0 -> /cpu:0""" prefix = '/job:localhost/replica:0/task:0/device:' if device.startswith(prefix): device = '/'+device[len(prefix):] return device.lower()
def transpose_2d(a): """ Transpose a given matrix using Zip. A 1x4 matrix becomes a 4x1 matrix :param a: (list) 2D Matrix to transpose :return: (list) Transposed 2d matrix of a """ # check if given matrix is list if type(a) != list: raise TypeError('Error xm10: Incorrect type, mat...
def get_book_tag(tool_name, category): """ Get User Manual HTML tag """ prefix = "https://www.whiteboxgeo.com/manual/wbt_book/available_tools" url = "{}/{}.html#{}".format(prefix, category, tool_name) html_tag = "<a href='{}' target='_blank'>WhiteboxTools User Manual</a>".format( url) ...
def compile_output_errors(filepath, is_filename_error, filename_error_output, is_error, forecast_error_output, is_date_error, forecast_date_output): """ purpose: update locally_validated_files.csv and remove deleted files params: * filepath: Full filepath of the forecast *...
def parse_feats(feats): """ Helper function for dealing with the feature values that Stanza returns. They look like "Case=Nom|Gender=Fem|Number=Sing" and we convert it to a dictionary with keys "Case" (e.g. "NOM"), "Gender" (e.g. "FEM"), "Number" (e.g. "SIN"). We capitalize the values and make them 3 charac...
def quote(lst: list) -> list: """Put quotation marks around every list element, which is assumed to be a str.""" return [f"\"{element}\"" for element in lst]
def getManifestName(manifest): """ returns name of manifest""" return manifest["manifest"]["name"]
def compute_occurrence_indices(lst): """ Returns a 0-based list of integers specifying which occurrence, i.e. enumerated duplicate, each list item is. For example, if `lst` = [ 'A','B','C','C','A'] then the returned list will be [ 0 , 0 , 0 , 1 , 1 ]. This is useful when working with `DataS...
def strip_prefixes(s, prefixes=()): """ Return the `s` string with any of the string in the `prefixes` set striped. Normalize and strip spacing. """ s = s.split() # strip prefixes. # NOTE: prefixes are hard to catch otherwise, unless we split the # author vs copyright grammar in two ...
def to_be_archived(row): """Condition function to designate if issue should be archived. Args: row (dict): Row to be checked. Returns: bool: True if issue should archived, False otherwise. """ return row["Priority"] == "Done"
def _make_pr(source_repo, source_branch, base_ref, base_url=''): """Create a PR JSON object.""" return { 'head': { 'repo': { 'full_name': source_repo, }, 'ref': source_branch, }, 'base': { 'ref': base_ref, 'repo'...
def make_id(letter_code, id_number): """ Make the standard-format id (3- or 5-letter alpha code, followed by 7-digit number). Parameters ---------- letter_code : str 3-character code (e.g. USA, BRA, CHN) or 5-character source code. id_number : int Number less than 10-million. Returns ------- idnr : unico...
def get_minimum_set_cover(nodelist, listofsubsets): """ Implements the minimum set cover algorithm to find non-overlapping sets out of the 80 ribosomal sampled regions Parameters ---------- nodelist: list listofsubsets: list Returns ------- cover: list list of sets of s...
def munsell_value_moon1943(Y): """ Returns the *Munsell* value :math:`V` of given *luminance* :math:`Y` using *Moon and Spencer (1943)* method. Parameters ---------- Y : numeric *luminance* :math:`Y`. Returns ------- numeric *Munsell* value :math:`V`. Notes ...
def get_category_id(k): """ :param: class id which corresponding coco.names :return: category id is used in instances_val2014.json """ kk = k if 12 <= k <= 24: kk = k + 1 elif 25 <= k <= 26: kk = k + 2 elif 27 <= k <= 40: kk = k + 4 elif 41 <= k <= 60: ...
def pad(data, pad_id): """ Pad all lists in data to the same length. """ width = max(len(d) for d in data) return [d + [pad_id] * (width - len(d)) for d in data]
def camel_case(name): """Convert words into CamelCase.""" return ''.join(name.capitalize().split())
def find_first_list_element_above(list, value): """ Simple method to return the index of the first element of a list that is greater than a specified value. Args: list: List of floats value: The value that the element must be greater than """ return next(x[0] for x in enumerate(list...
def subtract_dict(bigger, smaller, prefix = ''): """Subtract a dict from another""" ret = bigger.copy() for key, val in smaller.items(): if key not in ret: continue if isinstance(ret[key], dict) and isinstance(val, dict) and ret[key] != val: ret[key] = subtract_dict(ret[key], val, prefix + ' ') elif ret...
def get(id): """ Returns a user by ID. :param id: Id of the user. :return: Dictionary containing the user. 200 if user found. 404 if the user does not exist. """ result = { "id": id, "first_name": "John", "last_name": "Smith", "profile_image_url": "IM...
def tags_from_context(context): """Helper to extract meta values from a Celery Context""" tag_keys = ( 'compression', 'correlation_id', 'countdown', 'delivery_info', 'eta', 'exchange', 'expires', 'hostname', 'id', 'priority', 'queue', 'reply_to', 'retries', 'routing_key', 'serializer', '...
def word_counter(words, text): """Vectorized string search""" total = [0]*len(text) # Empty list for i, txt in enumerate(text): for word in words: if word in txt: total[i] = total[i] + 1 return total
def is_turkish_id(x): """ checks if given id is valid TC ID """ if len(str(x)) != 11: return False str_id = str(x) # first 10 digit sum mod 10 equals 11th digit control lst_id = [int(n) for n in str_id if n.isdigit()] if lst_id[0] == 0: return False # first 10 digit...
def render_app_label(context, app, fallback=""): """ Render the application label. """ try: text = app['app_label'] except KeyError: text = fallback except TypeError: text = app return text
def _get_name(f): """Gets the name of underlying objects.""" if hasattr(f, '__name__'): return f.__name__ # Next clause handles functools.partial objects. if hasattr(f, 'func') and hasattr(f.func, '__name__'): return f.func.__name__ return repr(f)
def sorter(a, b): """Option sorter""" if 'priority' not in a[1] and 'priority' not in b[1]: return 0 elif 'priority' in a[1] and 'priority' not in b[1]: return -1 elif 'priority' in b[1] and 'priority' not in a[1]: return +1 elif a[1]['priority'] > b[1]['priority']: r...
def tkcolour_from_rgb(rgb): """ Translates an rgb tuple of ints to a tkinter friendly color code """ return "#%02x%02x%02x" % rgb
def snake_case_split(identifier): """Split snake_case funtion names to tokens. Args: identifier (str): Identifier to split Returns: (list): lower case split tokens. ex: ['snake', 'case'] """ return [token.lower() for token in identifier.split('_')]
def bubbleSort2(nums): """ Improved version, stop when no swap occur :type nums: List[int] :rtype: List[int] """ res = list(nums) # I don't want to change the input list flag = True while flag: flag = False for j in range(1, len(res)): if res[j - 1] > res[j]:...
def partition(arr, low, high): """Take the last element as the pivot, and place that element in the correct sorted position by moving all smaller items to the left of the pivot and all larger items to the right of the pivot""" # Set i to be index of smaller element i = low - 1 # Assume last e...
def find_message(text): """Find a secret message""" import re patten = re.compile(r'[A-Z]') res = patten.findall(text) resi ='' for each in res: resi = resi + each return resi
def get_B0(dataset): """Get the trait value at the minimum temperature.""" # Initialize the temperature variable at a very high number. min_temp = 9999 # Get the minimum temperature value. for row in dataset: min_temp = min(min_temp, float(row[4])) # Initialize the trait variable at a...
def get_sex(sex): """Return a consistent sex notation (male, female).""" if sex.lower() == 'm': return 'male' if sex.lower() == 'f': return 'female' return sex.lower()
def para_filtering(turn, sentences, K): """filter paraphrase""" missing_values = [] for domain_slot, value in turn["turn_label"]: if (value in turn["system_transcript"]) and (value not in turn["transcript"]): missing_values.append(value) value_list = [] best_sent = "" for d...
def resolve_data_sink_option(args, pipeline): """ This Function takes in... :param args: :param pipeline: :return: """ if ( args["--rewrite-datasinks"] or pipeline["ds_overwrite"] ): # GLOBAL_DATA_SINK_REWRITE return True return False
def calc_ar_neff(phi, n=1): """Calculate number of effective, i.e. independent samples for a given lag-one autocorrelation Parameters ---------- phi : float Lag-one autocorrelation parameter n : Number of datapoints in the time series Returns ------- neff : float ...
def _maybe_parenthesise(x, convert=str): """ convert an object to string and surround in parenthesis if it contains an operator """ warrenters = '+*/\\-^' ret = convert(x) if any((w in ret) for w in warrenters): return "(" + ret + ")" return ret
def ltrimboth (l,proportiontocut): """ Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., co...
def update_lambda_value(config, n_iter): """ Update a lambda value according to its schedule configuration. """ ranges = [i for i in range(len(config) - 1) if config[i][0] <= n_iter < config[i + 1][0]] if len(ranges) == 0: assert n_iter >= config[-1][0] return config[-1][1] asser...
def join_path_segments(*args): """ Join multiple lists of path segments together, intelligently handling path segments borders to preserve intended slashes of the final constructed path. This function is not encoding aware. It doesn't test for, or change, the encoding of path segments it is pas...
def remove_suffix(x, suffix=" "): """ Remove a specific suffix from the end of a string. """ if x.endswith(suffix): x = x[: -len(suffix)] return x
def five_uneven_peak_trap(x=None): """ F1: Five-Uneven-Peak Trap Variable ranges: x in [0, 30 No. of global peaks: 2 No. of local peaks: 3. """ if x is None: return None result = None if 0 <= x < 2.50: result = 80*(2.5-x) elif 2.50 <= x < 5: ...
def where_math(condition, x, y): """ scalar version of numpy.where """ if condition: return x else: return y
def is_duckument_type(obj): """Internal mapping type checker Instead of using `isinstance(obj, MutableMapping)`, duck type checking is much cheaper and work on most common use cases. If an object has these attritubes, is a document: `__len__`, `keys`, `values` """ doc_attrs = ("__len_...
def is_contained(a, b): """ Check if segment b is fully contained within segment a """ return b[0] >= a[0] and b[1] <= a[1]
def absolute_value(x): """Compute the absolute value. Parameters ---------- x : float Returns ------- float The absolute value. """ if x > 0: return x else: return -x
def aoec_colon_concepts2labels(report_concepts): """ Convert the concepts extracted from colon reports to the set of pre-defined labels used for classification Params: report_concepts (dict(list)): the dict containing for each colon report the extracted concepts Returns: a dict containing for each col...
def rgb_to_int(r, g, b): """ Convert color from RGB to 24-bit integer """ return b*65536 + g*256 + r
def _validate_tag_sets(tag_sets): """Validate tag sets for a MongoReplicaSetClient. """ if tag_sets is None: return tag_sets if not isinstance(tag_sets, list): raise TypeError(( "Tag sets %r invalid, must be a list") % (tag_sets,)) if len(tag_sets) == 0: raise Va...
def string_to_number(s): """ :param s: word user input :return number: transfer the word into int """ number = '' n = 0 number += str(n) for i in range(len(s)-1): n += 1 number += str(n) return number
def find_intterupts(envelope, high_theshold_ratio=.5, low_threshold_ratio=.35): """ Returns a list of times when the signal goes high using a software schmitt trigger. Input: evelope: the envelope of the signal to process high_theshold_ratio: ratio of the max of the signal to trigger a high_thes...
def get_resource_id(resource): """ Get a resource's ID. Args: resource (obj): a Python object. Returns: str: the resource's ID or None. """ if hasattr(resource, 'resource_id'): attr = resource.resource_id if callable(attr): return attr() retu...
def efficency_vol_poly(cappa): """Calculate volumetric efficency for a given pump's typical number. The polynomial has been calculated applaying the curve fitting at nodes cappa .2 .3 .4 .5 .6 .7 .8 .9 1.0 1.1 1.2 eta_hyd .940 .948 .953 .956 .957 .958 .959 .960 .961 .962 .963 weights ...
def do_overrides(data, overrides): """ Form is: { "foo.bar.0.star": "value", "top_level_item": "value2", "foo.bar.append": "value3", } >>> do_overrides({}, {"foo": "bar"}) {"foo": "bar"} >>> do_overrides({"foo": {"bar": []}}, {"foo.bar.append": 5}) {"foo": {"bar"...
def blend_average(*args): """ Blends images by averaging pixels. """ s = 0 for i in args: s+=i return s/len(args)
def _get_index_list_of_values(d, k, def_value=None): """Like _index_list_of_values, but uses get to access and returns an empty list if the key is absent. Returns d[k] or [d[k]] if the value is not a list""" v = d.get(k, def_value) if v is None: return [] if isinstance(v, list): ...
def arrays_to_strings(measure_json): """To facilitate readability via newlines, we express some JSON strings as arrays, but store them as strings. Returns the json with such fields converted to strings. """ fields_to_convert = [ 'title', 'description', 'why_it_matters', 'numerator_columns'...
def format_dollars(amount): """Input float, Returns formatted dollars($x,xxx.xx)""" balance = '{:.2f}'.format(amount) balance = balance.split('.') bit = balance[0][::-1] new_thing = '' for i in range(1, len(bit) + 1): if (i-1) % 3 == 0 and i != 1: new_thing += ',' new...
def normalize_attributes(d): """ Sort returned attribute values. """ if d is None: return None r = {} for key, value in d.items(): if isinstance(value, list): r[key] = sorted(value) else: r[key] = value return r
def _version(name): """Return the version component of a package name.""" return name.rpartition("-")[2]
def _singularity_image_name_on_disk(name: str) -> str: """Convert a singularity URI to an on disk sif name :param str name: Singularity image name :rtype: str :return: singularity image name on disk """ docker = False if name.startswith('shub://'): name = name[7:] elif name.start...
def policy_v2_1(probability=0.7, magnitude=5): """Randomly select one transformation from {color} transformations, and then randomly select two transformations from {shape} transformations.""" policy = { # color augment 0: [[('Mixup', probability, magnitude)], [('Gaussian_noise', probabi...
def pad_number(num): """ If given number has only one digit, a new string with two spaces in the left is returned. Otherwise, a string without spaces is returned. :param num: integer :return: padded string """ pad = ' ' if num < 10 else '' return '%s%s' % (pad, num)
def unindent(text, skip1=False): """Remove leading spaces that are present in all lines of ``text``. Parameters ---------- test : str The text from which leading spaces should be removed. skip1 : bool Ignore the first line when determining number of spaces to unindent, and r...
def complement(l, universe=None): """ Return the complement of a list of integers, as compared to a given "universe" set. If no universe is specified, consider the universe to be all integers between the minimum and maximum values of the given list. """ if universe is not None: universe = set(universe) else: ...
def decrypt (lst: list): """ Decodes html encoded emails Pass a list of emails Decodes email if starting characters are '&#' Returns list of unencoded emails """ while True: unencoded_emails = [] for string in lst: if string[0:2] == '&#': slices = int(len(string)...
def cauchy_cooling_sequence(initial_t, it): """ Calculates the new temperature per iteration using a cauchy progression. Parameters ---------- initial_t : float initial temperature it: int actual iteration Returns -------- tt: float new temperature """ tt = initial_t/(1+it) return tt
def n_max_iter_heuristics(n_data, n_query, low_bound=5, up_bound=20): """ Helper method to define maximum number of iterations for a given campaign. This is based on the empirical evidence in various systems >90% of stable materials are identified when 25% of candidates are tested. We also enforce ...
def formatAbilities(abilities): """ same as formatTypes but for abilities """ res = "" for i in range (len(abilities) - 1, -1, -1): res += abilities[i]["ability"]["name"] + ";" return res
def save_txt(str_file_path, str_txt): """ .. _save_txt : This funciton saves the given string into the given file. Parameters ---------- str_file_path : str The text file full path. str_txt : str The string to be write into the text file. ...
def human_time(time_s): """ Converts a time in seconds to a string using days, hours, minutes and seconds. """ time_s = int(time_s) # Ensure int out = [] days = time_s // 86400 if days == 1: out.append("%i day" % days) time_s -= days * 86400 elif days >= 1: out...
def save_a_vocab_file(vocab_file, vocab_list): """Save a Vocab file for test.""" with open(vocab_file, "w", encoding='utf-8') as out_f: for vocab in vocab_list: out_f.write(vocab) out_f.write('\n') return vocab_file