content
stringlengths
42
6.51k
def _to_flat_dict_key(keys): """Converts a list of nested keys to flat keys used in state.as_dict(). Args: keys: List of keys from outmost to innermost. Returns: Corresponding flat dictionary for the given list of keys. """ return '/' + '/'.join(keys)
def linear_range(start_value, end_value, step_count): """ linear range from x0 to x1 in n steps. """ arr = [] step_size = (end_value - start_value) / (step_count - 1) value = 1.0 * start_value while value <= end_value: arr.append(round(value, 6)) value += step_size return arr
def _map_access_string(access_string): """Map an access string to a value Blogger will understand. In this case, Blogger only cares about "is draft" so 'public' gets mapped to False, everything else to True. Returns: Boolean indicating True (is a draft) or False (is not a draft). """ if not access_str...
def sortedDictValues(adict): """ Sort a dictionary by its keys and return the items in sorted key order. """ keys = list(adict.keys()) keys.sort() return list(map(adict.get, keys))
def lighten_color(r, g, b, factor): """ Make a given RGB color lighter (closer to white). """ return [ int(255 - (255 - r) * (1.0 - factor)), int(255 - (255 - g) * (1.0 - factor)), int(255 - (255 - b) * (1.0 - factor)), ]
def is_pds4_identifier(identifier): """ Determines if the provided identifier corresponds to the PDS4 LIDVID format or not. Parameters ---------- identifier : str The identifier to check. Returns ------- True if the identifier is a valid PDS4 identifier, False otherwise. ...
def round_up(number: int, multiple: int) -> int: """Round a number up to a multiple of another number. Only works for positive numbers. Example: >>> round_up(57, 100) 100 >>> round_up(102, 100) 200 >>> round_up(43, 50) 50 >>> round_up(77, 50) 100 """ assert multiple...
def sub(x, y): """Subtracts two vectors x and y. Args: x: The minuend. y: The subtrahend. Returns: The result is the vector z for which z_i = x_i - y_i holds. """ result = [] for i, x_i in enumerate(x): result.append(x_i - y[i]) return result
def is_cased(s): """Return True if string s contains some cased characters; otherwise false.""" return s.lower() != s.upper()
def parse_codec_list(line, codec_type='video'): """ Parse through ffmpegs codec lists :param line: string to parse :param codecType: string of which codec type to look for. :returns: string of codec name """ query = "V" if codec_type == 'video' else "A" testOne = "E" in line[1:7] and que...
def getPdbLink(pdb_code): """Returns the html path to the pdb file on the ebi server """ file_name = 'pdb' + pdb_code + '.ent' pdb_loc = 'https://www.ebi.ac.uk/pdbe/entry-files/download/' + file_name return file_name, pdb_loc
def make_markdown_url(line_string, s): """ Turns an URL starting with s into a markdown link """ new_line = [] old_line = line_string.split(' ') for token in old_line: if not token.startswith(s): new_line.append(token) else: new_line.append('[%s](%s)' ...
def info(iterable): """ ESSENTIAL FUNCTION returns the flattened union of an iterable info([[1,2], [1,3],[2]]) --> {1,2,3} """ buf = set() for el in iterable: buf = buf.union(set(el)) return buf
def safe_cast_to_list(string): """ this is used to cast a string object to a length-one list, which is needed for some pandas operations. it also detects if something is already a list, and then does nothing (as to avoid a double list) :param string: string :return: either the string itself...
def _parseProperties (projectObj): """ Parse maven properties """ properties = {} allProperties = projectObj.get ('properties', {}) if allProperties is None: allProperties = {} for k, v in allProperties.items(): # when v is a list means that the same property is specified more # than once, o...
def frame_has_key(frame, key: str): """Returns whether `frame` contains `key`.""" try: frame[key] return True except: return False
def mse(original_data, degradated_data): """ This calculates the Mean Squared Error (MSE) :param original_data: As Pillow gives it with getdata :param degradated_data: As Pillow gives it with getdata :return: List containing the MSE in Y, U, V and average of those 3 """ error_y = 0 error...
def find_object_with_matching_attr(iterable, attr_name, value): """ Finds the first item in an iterable that has an attribute with the given name and value. Returns None otherwise. Returns: Matching item or None """ for item in iterable: try: if getattr(item, attr_na...
def merge_two_dicts(config, base, path=None): """Merges two configs, overwriting properties in the base.""" assert config is not None assert base is not None final = {} keys = set() keys.update(config.keys()) keys.update(base.keys()) for key in keys: # key only in config ...
def str2bool(value): """ Type to convert strings to Boolean (returns input if not boolean) """ if not isinstance(value, str): return value if value.lower() in ('yes', 'true', 'y', '1'): return True elif value.lower() in ('no', 'false', 'n', '0'): return False else: re...
def toggle_modal(n_open, n_close, n_load, is_open): """ Toggles open/closed the form modal for DigitalRF playback requests""" if n_open or n_close or n_load[0]: return not is_open return is_open
def nth_line(src: str, lineno: int) -> int: """ Compute the starting index of the n-th line (where n is 1-indexed) >>> nth_line("aaa\\nbb\\nc", 2) 4 """ assert lineno >= 1 pos = 0 for _ in range(lineno - 1): pos = src.find('\n', pos) + 1 return pos
def rotation(s1, s2): """Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring.""" if len(s1) != len(s2): return False s1 *= 2 return s1.find(s2) != -1
def make_divisible(v, divisor=8, min_value=None): """make_divisible""" min_value = min_value or divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
def get_data_type(param): """ Convert WhiteboxTools data types to ArcGIS data types """ data_type = '"GPString"' # default data type data_filter = "[]" # https://goo.gl/EaVNzg filter_type = '""' multi_value = False dependency_field = "" # ArcGIS data types: https://goo.gl/95JtFu ...
def settings_value(value): """Returns the evaluated string.""" try: return eval(value, {}, {}) except (NameError, SyntaxError): return value
def maybe_route_func(func, count): """ Routes the given `func` `count` times if applicable. Parameters ---------- Parameters ---------- func : `callable` The respective callable to ass count : `int` The expected amount of functions to return. Returns ---...
def validate_bool_kwarg(value, arg_name): """Ensures that argument passed in arg_name is of type bool. """ if not (isinstance(value, bool) or value is None): raise ValueError( f'For argument "{arg_name}" expected type bool, received ' f"type {type(value).__name__}." )...
def resolve_continuation(l, char='\\'): """Concatenates elements of the given string list with the following one, if they end with the continuation character.""" result = [] temp = '' for line in l: if not line.endswith(char): result.append(temp + line if len(temp) else line) ...
def num_deriv(r, func, h = 0.1e-5): """Returns numerical derivative of the callable `func` :param r: Value at which derivative of `func` should be evaluated. :param func: Function whose gradient is to be evaluated. :param h: Step size used when performing numerical differentiation. :return: Numerical derivat...
def tree_consistent(b): """FIXME: move this to the bracketing package. """ def crosses(xxx_todo_changeme, xxx_todo_changeme1): (a, b) = xxx_todo_changeme (c, d) = xxx_todo_changeme1 return (a < c and c < b and b < d) or (c < a and a < d and d < b) for i in range(len(b)): ...
def process_related_id(plan): """Add plan records and other references as references """ rids = [] relationship = {'geonetwork': 'isReferencedBy', 'rda': 'isAlternateIdentifier', 'related': 'describes'} for k in ['geonetwork','rda']: if any(x in plan[k] for x in ['http:...
def convert_letters(Letter): """ Description ----------- Input_Letters are convert to their ord-Number minus 64 Parameters ---------- Letter : String "A", "B" etc. Context ---------- is called in wrapp_ProcessUnits and wrapp_SystemData Returns ------- ...
def get_icon_info(family_name, icons, host, asset_url_pattern): """Returns a list containing tuples of icon names and their URLs""" icon_info = [] for icon in icons: if family_name not in icon['unsupported_families']: name = icon['name'] url_params = { 'family...
def reverse_bits(n, bit_count): """ reversed the order of the bits in the passed number :param n: number of which the bits are reversed :param bit_count: the number of bits that are used for the passed number :return: """ rev = 0 # traversing bits of 'n' from the righ...
def gcd(a, b): """Calculate the greatest common divisor between integers 'a' and 'b'.""" if b == 0: return a else: return gcd(b, a % b)
def get_unique_lines(text_hashes): """Get the unique lines out of a list of text-hashes Args: text_hashes (list): A list of (hashes of) strings Returns: unique_indices (List): List (of the same length as text_hashes) indicating, for each element of text_hash,...
def percentage(part, whole): """ This function calculates the percentage of a given set """ return float(part)*float(whole)/100
def element(elem): """Element symbols""" data = ["H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "...
def _leading_zero(l1): """ Add leading 0 if necessary """ return l1 if len(l1) == 2 else '0' + l1
def NoCaseCmp(x, y): """Case insensitive sort method""" if x.lower() < y.lower(): return -1 elif x.lower() > y.lower(): return 1 else: return 0
def bool_to_str(value: bool) -> str: """Converts boolean to 'ON' or 'OFF' string.""" if type(value) is bool: return 'ON' if value is True else 'OFF' else: raise Exception(f"bool_to_str: unsupported variable type '{type(value)}', value '{value}'. Only boolean values are supported.")
def get_recursive_content_as_str(doc): """ THIS METHOD IS DEPRECATED! """ text = '' if isinstance(doc, str): return doc.strip() + '\n' elif isinstance(doc, dict): for key in doc: text += get_recursive_content_as_str(doc[key]) elif isinstance(doc, list): fo...
def interpolate(errors1, prob1, errors2, prob2, alpha): """ Perform a linear interpolation in the errors distribution to return the number of errors that has an accumulated probability of 1 - alpha. """ result = errors1 + ((errors2 - errors1) * ((1 - alpha) - prob1) / (prob2 - prob1)) if result...
def overlap(a, b): """Check if a overlaps b. This is typically used to check if ANY of a list of sentences is in the ngrams returned by an lf_helper. :param a: A collection of items :param b: A collection of items :rtype: boolean """ return not set(a).isdisjoint(b)
def _interp_evaluate(coefficients, t0, t1, t): """Evaluate polynomial interpolation at the given time point. Args: coefficients: list of Tensor coefficients as created by `interp_fit`. t0: scalar float64 Tensor giving the start of the interval. t1: scalar float64 Tensor giving the end of...
def find_anagrams_of(word): """Find all anagrams. Params ------ word: str Sequence of characters for which all combinaisons of anagram have to be found. Returns ------- list A list of all anagrams. """ outputs = [] if len(word) == 1: return word ...
def unindent_text(text, pad): """ Removes padding at the beginning of each text's line @type text: str @type pad: str """ lines = text.splitlines() for i,line in enumerate(lines): if line.startswith(pad): lines[i] = line[len(pad):] return '\n'.join(lines)
def letters_no_answer(word, answers, indices_non_letters): """ If the get_words function returns more than one world, then this does not automatically decrypts any of the letters in the word. However, if every word has the same letter in the same location, then that letter can be decrypted. ...
def get_res_string(res): """Converts resolution in bp to string (e.g. 10kb)""" res_kb = res//1000 if res_kb < 1000: return str(res_kb) + "kb" else: return str(int(res_kb/1000)) + "mb"
def str_denumify(string, pattern): """ Formats `string` according to `pattern`, where the letter X gets replaced by characters from `string`. >>> str_denumify("8005551212", "(XXX) XXX-XXXX") '(800) 555-1212' """ out = [] for c in pattern: if c == "X":...
def omni_tether_script(amount): """ :param amount: (display amount) * (10 ** 8) :return omni tether script in hex format """ prefix = "6a146f6d6e69000000000000001f" amount_hex = format(amount, 'x') amount_format = amount_hex.zfill(16) return prefix + amount_format
def get_node(fasta_dic): """Get nodes with base and path name from multiple sequences""" def get_coordinate_info(fasta_dic): """Divide the sequences into one base units""" coordinate_info_list = [] for seqid, seq in fasta_dic.items(): tmp_list = [(seqid, base) for base in seq...
def close(session_attributes, fulfillment_state, message): """ Defines a close slot type response. """ response = { "sessionAttributes": session_attributes, "dialogAction": { "type": "Close", "fulfillmentState": fulfillment_state, "message": message, ...
def GetPartitionName(dev, index): """Get partition name from device name and index. Returns: Partition name, add `p` between device name and index if the device is not a sata device. """ return f'{dev}{index}' if dev.startswith('sd') else f'{dev}p{index}'
def find_holder(card, hands): """returns the holder of a given cards""" holder = -1 for player_num, hand in enumerate(hands): if card in hand: holder = player_num return holder
def all_pairs(elements): """ Generate all possible pairs from the list of given elements. Pairs have no order: (a, b) is the same as (b, a) :param elements: an array of elements :return: a list of pairs, for example [('a', 'b)] """ if len(elements) < 2: return [] elif len(eleme...
def reducer(s): """Return wrapped string and linecount where +/- items are concatenated with blank and others with newline""" ss = [s[0]] try: for i in range(1, len(s)): if s[i] == "+" or s[i] == "-": ss[-1] = ss[-1] + " " + (s[i+1]) s[i+1] = Non...
def midi2hz(note_number): """Convert a (fractional) MIDI note number to its frequency in Hz. Parameters ---------- note_number : float MIDI note number, can be fractional. Returns ------- note_frequency : float Frequency of the note in Hz. """ # MIDI note numbers are ...
def splitConsecutive(collection, length): """ Split the elements of the list @collection into consecutive disjoint lists of length @length. If @length is greater than the no. of elements in the collection, the collection is returned as is. """ # Insufficient collection size for grouping if len(collection) < length...
def are_broadcastable( *shapes ): """ Check whether an arbitrary list of array shapes are broadcastable. :Parameters: *shapes: tuple or list A set of array shapes. :Returns: broadcastable: bool True if all the shapes are broadcastable. False if they are not broadcastabl...
def spikesFromVm(t, vm, **kwargs) : """ Extract the spike times from a voltage trace. Parameters ---------- t : array or list of int or float time points (in ms) vm : array or list of int or float voltage points threshold : int or float, optional voltage at which we con...
def add_globals(env): """ Adds built-in procedures and variables to env. """ import operator env.update({ '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, '>': operator.gt, '<': operator.lt, '>=': operator.ge, '<=...
def proc(config: dict) -> int: """"The number of processes to use for multiprocess operations.""" return config["proc"]
def expand_feed_dict(feed_dict): """If the key is a tuple of placeholders, split the input data then feed them into these placeholders. """ new_feed_dict = {} for k, v in feed_dict.items(): if type(k) is not tuple: new_feed_dict[k] = v else: # Split v along th...
def middle(shape): """ Given the 2D vertices of a shape, return the coordinates of the middle of the shape. """ return (sum(p[0] for p in shape) / len(shape), sum(p[1] for p in shape) / len(shape))
def merge_string_without_overlap(string1, string2): """ Merge two Strings that doesn't have any common substring. """ return string1 + "\n" + string2
def oget(optional, default=None): """Get optional value or default value""" return default if optional is None else optional
def dragLossUpToAltitude(altitude): """gives the drag loss up to the given altitude""" if 0 <= altitude and altitude <= 20000: return 150 - 0.0075*altitude # m/s else: raise Exception("Invalid at given altitude: {0}".format(altitude))
def intOrNone(val): """ Returns None if val is None and cast it into int otherwise. """ if val is None: return None else: return int(val)
def vec2num(vec): """Convert list to number""" num = 0 for node in vec: num = num * 10 + node return num
def make_wkt_point(x_centre, y_centre): """Creates a well known text (WKT) point geometry for insertion into database""" return f"POINT({x_centre} {y_centre})"
def _flatten(t: list) -> list: """ Flatten nested list """ return [item for sublist in t for item in sublist]
def get_port_ether(port_name): """ Get Host port Ethernet Address. Input: - The name of the port (e.g, as shown in ifconfig) """ return "ifconfig {} | grep \"ether \" | xargs | cut -d \' \' -f 2".format(port_name)
def present_value(value, year, discount_rate, compounding_rate=1): """ Calculates the present value of a future value similar to numpy.pv, except numpy.pv gave weird negative values :param value: The future value to get the present value of :param year: How many years away is it? :param discount_rate: The discoun...
def flip(dictionary): """ Flips a dictionary with unique values. :param dictionary: a mapping that is assumed to have unique values. :returns: a dict whose keys are the mapping's values and whose values are the mapping's keys. """ return { value: key for key, value in dictio...
def map_range(value, from_lower, from_upper, to_lower, to_upper): """Map a value in one range to another.""" mapped = (value - from_lower) * (to_upper - to_lower) / ( from_upper - from_lower ) + to_lower return round(min(max(mapped, to_lower), to_upper))
def reselect_truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each...
def move_angle_to_angle(theta1, theta2, p): """ Move a number towards another number (here, the numbers were angles). args: theta1: The first number theta2: The second number p: The extent of movement. 1 means full movement. """ return theta1 + (theta2-theta1) * p
def percent(values, p=0.5): """Return a value a faction of the way between the min and max values in a list.""" m = min(values) interval = max(values) - m return m + p*interval
def fromSpectralType(spectralType): """Gets info from spectral type.""" group = None if spectralType.startswith("sd"): group = "main sequence" color = spectralType[2:] return group, color elif spectralType.startswith("D"): group = "white dwarf" return group, "whit...
def scaleND(v, s): """Scales an nD vector by a factor s.""" return [s * vv for vv in v]
def is_msc_dep(dep): """ Given dep str, check if it's one of the Msc dep offered by IIT KGP. Return bool """ msc_dep_list = ["GG", "EX", "MA", "CY", "HS", "PH"] if dep in msc_dep_list: return True return False
def get_training_image_size(original_size, multiple=32): """ Our inputs to the network must by multiples of 32. We'll find the closest size that both a multiple of 32 and greater than the image size """ new_sizes = [] for dimension_size in original_size: for j in range(20): ...
def pretty_repr(obj, linebreaks=True): """Pretty repr for an Output Parameters ---------- obj : any type linebreaks : bool If True, split attributes with linebreaks """ class_name = obj.__class__.__name__ try: obj = obj._asdict() # convert namedtuple to dict except...
def create_type_map(cls, type_map=None): """ Helper function for creating type maps """ _type_map = None if type_map: if callable(type_map): _type_map = type_map(cls) else: _type_map = type_map.copy() else: _type_map = {} return _type_map
def revers_str2method(input_string): """ Input: input_string is str() type sequence Output: reversed input_string by str() type """ lstr = list(input_string) lstr.reverse() return "".join(lstr)
def filt_last_arg(list_, func): """Like filt_last but return index (arg) instead of value. Inefficiently traverses whole list""" last_arg = None for i, x in enumerate(list_): if func(x): last_arg = i return last_arg
def expand_axes_in_transpose(transpose, num_new_axes): """increases axis by the number of new axes""" return tuple(list(range(num_new_axes)) + [axis + num_new_axes for axis in transpose])
def is_anagram(s, t): """ # Find if strings are anagram. t anagram of s # @param {string, string} input strings # @return bool if strings are anagram of each other or not """ s = list(s) # Sort a string and then compare with each other s.sort() # Quick sort O(n*log(n)) ret...
def gather_flex_fields(row, flex_data): """ Getting the flex data, formatted for the error and warning report, for a row. Args: row: the dataframe row to get the flex data for flex_data: the dataframe containing flex fields for the file Returns: The concatenated...
def try_enum(cls, val): """A function that tries to turn the value into enum ``cls``. If it fails it returns the value instead. """ try: return cls._enum_value_map_[val] except (KeyError, TypeError, AttributeError): return val
def fibo(iterations): """ This function calculate the fibonacci serie, calling itself many times iterations says """ if (iterations == 0 or iterations == 1): return 1 else: print(f"iteration = {iterations} -> {iterations - 1} + {iterations - 2} = {(iterations-1)+(iterations-2)}")...
def print_scientific_8(value: float) -> str: """ Prints a value in 8-character scientific notation. This is a sub-method and shouldnt typically be called Notes ----- print_float_8 : a better float printing method """ if value == 0.0: return '%8s' % '0.' python_value = '%8....
def get_eligible_craters(crater_list): """Create eligible crater list from crater_list""" checker=True eligible_crater_list=[] for crater_tuple in crater_list: crater_good=True if crater_tuple[2]< -40: crater_good=False if crater_tuple[2]> 50: crater_good=...
def parse_field_ref(field_ref): """Split a field reference into a model label and a field name. Args: field_ref (str): a label for the model field to clean, following the convention `app_name.ModelName.field_name` Return: 2-tuple of str """ app_name, model_name, field_n...
def kgtk_null_to_empty(x): """If 'x' is NULL map it onto the empty string, otherwise return 'x' unmodified. """ if x is None: return '' else: return x
def isnormaldataitem(dataitem): """ Detects if the data item is in standard form """ return 'Table' in dataitem and 'Action' in dataitem and 'Data' in dataitem
def delimit(delimiters, content): """ Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") [foo] >>> delimit('""', "foo") '"foo"' """ if len(delimiters) != 2: raise ValueError( "`delimiters` must be of length 2. Got %r" % de...
def _short_string(data, length=800): """ Truncate a string if it exceeds a max length """ data_short = str(data)[:length] if len(str(data)) > len(str(data_short)): data_short += "!!SHORTENED STRING!!" return data_short