content
stringlengths
42
6.51k
def unflatten(dictionary): """ Unflattens a dictionary by splitting keys at '.'s. This function unflattens a hierarchical dictionary by splitting its keys at '.'s. It is used internally for converting the configuration dictionary to more convenient formats. Implementation was inspired by `this Stac...
def levenshtein(source: str, target: str) -> int: """Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using th...
def asbool(value): """ >>> all([asbool(True), asbool('trUE'), asbool('ON'), asbool(1)]) True >>> any([asbool(False), asbool('false'), asbool('foo'), asbool(None)]) False """ value = str(value).lower() return value in ('1', 'true', 'yes', 'on')
def interleave_value(t0,series,begin=False,end=False): """Add t0 between every element of *series*""" T = [] if begin: T += [t0] if len(series) > 0: T += [series[0]] for t in series[1:]: T += [t0,t] if end: T += [t0] return T
def compare_webapps(list1, list2): """ Return list of matching dictionaries from two lists of dictionaries. """ check = set([(d['name'], d['id']) for d in list2]) return [d for d in list1 if (d['name'], d['id']) in check]
def disk_to_mountname(disk_name): """ /dev/sdb --> /dev/sdb1 :param disk_name: :return: """ return disk_name + '1'
def create_hash_table(distances: list): """ :param distances: list of Distance objects :return: dict with _ids as key and distance as value """ result = {} for dist in distances: result[dist._id] = dist.value return result
def to_bool(str): """ Converts a given string to a boolean value. Leading and trailing whitespace is ignored, so strings of whitespace are evaluated as ``False``. """ if str: return bool(str.strip()) return False
def winner(rows: list) -> bool: """ Check the board to see if it is a winner """ # By default, the board is already a list or rows. We also want to check # columns, so get a list of columns as well columns = [list(column) for column in list(zip(*rows))] # combine the rows and columns into o...
def get_url(usr): """ Returns Anime List URL """ return 'https://myanimelist.net/animelist/{}'.format(usr)
def anchor_scales_from_str(anchor_scales_str): """ Parses a command line argument string for the anchor scales. :param anchor_scales_str: comma-separated integers, e.g. "128,256,512". :return: list of integers. """ return [int(dim) for dim in anchor_scales_str.split(',')]
def safe_cast(x, type, default = 0): """ Safely casts a variable to another type. If the cast fails, the default value is returned. Parameters ---------- x : [type] The variable that will be casted type : [type] The type the variable will be casted to default : [type], optio...
def flipBit(n, offset): """ Flips the bit at position offset in the integer n. """ mask = 1 << offset return(n ^ mask)
def ewma(current, previous, weight): """Exponentially weighted moving average: z = w*z + (1-w)*z_1""" return weight * current + ((1.0 - weight) * previous)
def one_away(s1, s2): """ > Description: check if s1 and s2 is 1 edit away from each other. The edits can be insert, remove or replace. > Input: String > Output: Boolean """ #if it is an empty string with a string with only 1 character or 2 string are the same, return true if len(s1) and len...
def is_build_at_least(current_version, other_version): """Returns whether or not |current_version| is at least as new as |other_version|.""" if current_version is None: return False # Special-cases for master builds. if current_version == 'MASTER': # If the current build is master, we consider it at ...
def part1(maze): """ Parameters ---------- maze : list A mutable sequence of integers that defines the maze to be escaped for part 1 of the test Returns ------- int The number of steps required to escape the maze """ ptr = 0 step = 0 while 0 <= ptr ...
def bubble_sort(collection): """Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5] ...
def get_filters(filters): """Return the rsync options for the given filters.""" arguments = [] for filter_ in filters: if len(filter_) > 1: raise Exception( "Filter must contain only one entry: {}".format(filter_)) if "exclude" in filter_: argumen...
def rlen(x): """ Alias para range(len(x)) """ return range(len(x))
def segments_from_time_to_frame_idx(segments, hop_length_seconds): """ Converts a sequence of segments (start, end) in time to their values in frame indexes. Parameters ---------- segements : list of tuple The list of segments, as tuple (start, end), to convert. hop_length_seconds : flo...
def removeAnchor(url): """ "http://www.website.com#my-anchor" -> "http://www.website.com" """ if url.find('#') > 0: return url[:url.find('#')] return url
def sign(x): """ Returns the sign of x. :param x: :return: """ if x > 0: return +1 elif x < 0: return -1 elif x == 0: return 0
def get_pow2(x): """Hacky version to get the greatest power of two smaller than x.""" return len(bin(x)) - 3
def extract_info(spec): """Extract information from the instance SPEC.""" info = {} info['name'] = spec.get('InstanceTypeId') info['cpu'] = spec.get('CpuCoreCount') info['memory'] = spec.get('MemorySize') info['nic_count'] = spec.get('EniQuantity') info['disk_quantity'] = spec.get('DiskQuan...
def diff_proportions(p_test, p_control): """ Calculate difference of proportions of positive results in test, control groups :param p_test: Proportion of positive outcome under test :param p_control: Proportion of positive outcome under control :return dop: Difference of proportions of p_test and p_...
def format_duration(seconds): """ Format a duration into a human-readable string. """ mins, secs = divmod(seconds, 60) fmt = "{:.0f}" if mins: return "{} minutes {} seconds".format(fmt, fmt).format(mins, secs) else: return "{} seconds".format(fmt).format(secs)
def func(x): """ :rtype: object """ print(x) return 1
def compute_score(triples1, triples2): """ Compute precision, recall, and f-score. Variable names must be identical. """ t1 = set(triples1) t2 = set(triples2) prec = len(t1.intersection(t2)) / float(len(t2)) rec = len(t1.intersection(t2)) / float(len(t1)) if prec == 0.0 and rec == 0.0: ...
def break_up_group(metadata, field, val, row): """Break up a array in 'field' into a single element with number 'val'""" if field in metadata: if len(metadata[field]) > val: row.append(metadata[field][val]) else: # This many values are not present, add blank cell ...
def fib_list(n): """[summary] This algorithm computes the n-th fibbonacci number very quick. approximate O(n) The algorithm use dynamic programming. Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n m...
def is_new_format(source): """ Checks if node/edge data already contains new format """ return source.find('/projects/') != -1 or source.find('doi') != 1
def count_player(board, player): """ Return el number of move by player """ count = 0 count = [count + f.count(player) for f in board] return sum(count)
def mk_list_of_str(x): """ Make sure the input is a list of strings :param str | list[str] | falsy x: input to covert :return list[str]: converted input :raise TypeError: if the argument cannot be converted """ if not x or isinstance(x, list): return x if isinstance(x, str): ...
def flatten_lists(a): """ Flatten a list of lists. Note: a must be an array of arrays (list of lists). See get_different_solution for examples. """ return [item for sublist in a for item in sublist]
def getStepPair(step): """ p -> p/(p-1) -p -> (p-1)/p """ return step > 0 and (step, step-1) or (-step-1, -step)
def itoa(num, base=10): """ Convert a decimal number to its equivalent in another base. This is essentially the inverse of int(num, base). """ negative = num < 0 if negative: num = -num digits = [] while num > 0: num, last_digit = divmod(num, base) digits.append('0123...
def filter_tuples(l): """Return only the tuples in a list. In a tupletree, tuples correspond to XML elements. Useful for stripping out whitespace data in a child list. """ if l is None: return [] else: return [x for x in l if type(x) == tuple]
def get_max_overlap(cur_country, dates_available): """ Function to calculate the dates that could accommondate most countries if the number is more than the original date, replace it with new date :param cur_country: current country for consideration :param dates_available: the preproce...
def show_notice(notice): """Shows a notice given by the string 'notice'""" return { 'notice': notice }
def str2bool(v): """ Convert a string to a boolean :return boolean: Returns True if string is a true-type string. """ return v.lower() in ('true', 't', '1', 'yes', 'y')
def test_xbm(h, f): """X bitmap (X10 or X11)""" s = '#define ' if h[:len(s)] == s: return 'xbm'
def get_address_type(ip_type): """ Return the address type to reserve. """ if ip_type in ['GLOBAL', 'REGIONAL']: return 'EXTERNAL' return 'INTERNAL'
def split(text, sep=" ", glue="'", removeEmpty=False): """ split - a variant of split with glue characters """ res = [] word = "" dontsplit = False for j in range(0, len(text)): c = text[j] if c in glue: dontsplit = not dontsplit if c in sep and not dontsp...
def str2bool(string): """Converts a string to a boolean Parameters: ----------- string : string """ return string.lower() in ("yes", "y", "true", "t", "1")
def chunks(items, size): """ Split list into chunks of the given size. Original order is preserved. Example: > chunks([1,2,3,4,5,6,7,8,9], 2) [[1, 2], [3, 4], [5, 6], [7, 8], [9]] """ return [items[i:i+size] for i in range(0, len(items), size)]
def InnerCupSize(x): """ Each inner cup is defined as XYY, where X is a char representing the size of the outer cup, and YY is an int from 0 to 10, representing the size of the inner cup. Hence we need a dictionary to associate the char (a letter) to a size Parameters ---------- ...
def _split_version_components(s): """Split version string into individual tokens. pkg_resources does this using a regexp: (\d+ | [a-z]+ | \.| -) Unfortunately the 're' module isn't in the bootstrap, so we have to do an equivalent parse by hand. Forunately, that's pretty easy. """ comps = [] ...
def sign(a): """Sign function Args: a (float): input Returns: int: sign of the input """ if a > 0: return 1 else: return -1
def handle_path(path): """ Stripping the '\\' and '/' characters from a given path. Examples: \\Shared\\123.txt\\ ---> Shared\\123.txt /Shared/123.txt/ ---> Shared/123.txt \\Shared\\123.txt/\\ ---> Shared\\123.txt """ return path.strip('\\/')
def isHTML(fileS): """If the last file ends with HTML""" if fileS.endswith("htm") or fileS.endswith("html"): return 1 return 0
def _bit_count(value): """Returns number of bits set.""" count = 0 while value: value &= value - 1 count += 1 return count
def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= e...
def is_integer(text: str) -> bool: """Fantastic findings.""" try: int(text) return True except ValueError: return False
def is_ancestor(cls, subclass): """ @type: cls: type @type: subclass: type @rtype: bool """ try: return cls in subclass.__mro__ except AttributeError: # raise same exception as issubclass(instance, klass) raise TypeError(str.format( "argument 1 must be a c...
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if not ints: print("Enter valid inputs") return None min = max = ints[0] for input in ints: if min > i...
def check_unordered_list(line): """ Check whether the line is unordered list, if it is, change it into html format :param line: str, a line in markdown file :return: boolean, whether a line is unordered list str, the line in html format """ count_space = 0 for char in line: ...
def is_recovered(alleles_in_probands, alleles_in_pool): """True if all the variants found in the proband(s) are also found in the pool. This tends to result in multi-alleleic sites not getting filtered in many cases. alleles_in_probands, alleles_in_pool: iterable consisting of items that can be compared in...
def get_common_substring_from_beginning(code1, code2): """ Method to get common substring of 2 given strings parameters ----------- :param code1: str String1 to compare :param code2: str String2 to compare :return: str Common substring in code1 and code2 """ ...
def merge_configs(*configs): """ Merge multiple dicts into one. """ z = {} for config in configs: z.update(config) return z
def get_combination_action(combination): """ Prepares the action for a keyboard combination, also filters another "strange" actions declared by the user. """ accepted_actions = ('link', 'js') for action in accepted_actions: if action in combination: return {action: combinatio...
def getAdded(before, after): """ Find any items in 'after' that are not in 'before' """ #message("before:" + str(before)) #message("after:" + str(after)) # Any items in 'before' are removed from 'after' # The remaining list is of the newly added items for b in before: try: i = after.index(b...
def filter_row(row_index, row): """ Ignore empty rows when parsing xlsx files. """ result = [element for element in row if element != ''] return len(result) == 0
def files_diff(list1, list2): """returns a list of files that are missing or added.""" if list1 and list2: for i in ["mlperf_log_trace.json", "results.json"]: try: list1.remove(i) except: pass if len(list1) > len(list2): return ...
def _convert_to_integer(bytes_to_convert): """Use bitwise operators to convert the bytes into integers.""" integer = None for chunk in bytes_to_convert: if not integer: integer = chunk else: integer = integer << 8 integer = integer | chunk return integ...
def make_keywords_message(keywords): """Colorize keywords and string them together.""" keywords_message = ('[ ' + (f'<span class=\'hottest\'>{keywords[0]}</span>' if 0 < len(keywords) else '') + (f', <span class=\'hotter\'>{keywords[1]}</span>' if 1 < len(ke...
def has_numbers(input_string): """Function to handle digits in inputs""" return any(char.isdigit() for char in input_string)
def write_entities_to_dict( compartments, species, parameters, reactions, assignments=None, parameter_rules=None, rate_rules=None, splines=None, events=None, ): """ Transforms inputs to dictionaries with the entities as keys and the objects as containing all the informati...
def revsplit(rev): """Parse a revision string and return (uuid, path, revnum). >>> revsplit('svn:a2147622-4a9f-4db4-a8d3-13562ff547b2' ... '/proj%20B/mytrunk/mytrunk@1') ('a2147622-4a9f-4db4-a8d3-13562ff547b2', '/proj%20B/mytrunk/mytrunk', 1) >>> revsplit('svn:8af66a51-67f5-4354-b62c-98d67c...
def get_block(page, start, end): """ Returns a block as described by start and end markers. If start marker not in page - returns none If end marker is not in page - returns all after the start marker """ if page is None: return None if start in page: return page.split(sta...
def copy_board(board): """ Deep-copies the input board (sudoku or domain) """ new_board = [] # Copy sudoku if type(board[0][0]) == int: for row in board: new_board.append(row[:]) # Copy domain else: for grid in board: new_grid = [] ...
def is_missing(obj): """Check if an object is missing""" return getattr(obj, "moya_missing", False)
def make_scene_list(metadata, fout='scenes.txt'): """ Create a scene list from metadata """ # assume keys are same in all the metadata keys = sorted(metadata[0].keys()) with open(fout, 'w') as f: f.write(','.join(keys) + '\n') for md in metadata: items = [str(md[k]) for k in ...
def nindex(str_in, substr, nth): """ From and string get nth ocurrence of substr """ m_slice = str_in n = 0 m_return = None while nth: try: n += m_slice.index(substr) + len(substr) m_slice = str_in[n:] nth -= 1 except ValueError: ...
def e_gamma(eta1, eta0): """ :param eta1: :param eta0: :return: eloggamma : """ egamma = eta1/eta0 return egamma
def list_to_string(l): """take a python and return as string with all values in double quotes for column headers """ start = '' for x in l: start += f"\"{str(x)}\"," start = start.rstrip(',') return start
def sets_diff(self: list, other: list, name: str, loc: str) -> list: """ Function to compare the sets of two lists. Returns a list of diff strings containing name and location. :param self: list :param other: list :param name: str :param loc: str :return: list[str] """ diffs = []...
def strip_str(s): """Strips newlines and whitespace from the given string.""" return ' '.join([w.strip() for w in s.strip().split('\n')])
def smart_mean_per_minute( maximum, minimum, per_minute, charge_interval, connection=0): """Returns the mean charge for a minute. Args: maximum (seconds): maximum length of call to average (the minimum is 1) minimum (seconds): calls are effectively at least this long per_minute:...
def distance(P1, P2): """ distance between two points """ return ((P1[0] - P2[0])**2 + (P1[1] - P2[1])**2)**0.5
def can_parse_body(headers, buffer): """ Checks whether a request's headers signal a body to parse. :param headers: A dict of header: value pairs. :param buffer: a bytes object. :return: Boolean. """ content_length = int(headers.get('content-length', '0')) return 'content-length' in hea...
def gen7CipherList(birthYear): """Takes an integer birthyear and returns a sorted list of possible 7th CPR digit Input: birthYear, int, an integer indicating year of birth Output: poss7Cipher, list of str[1], ordered list of possible 7th cipher. Empty list if birthYear...
def callable_or_value(val, msg): """ Return `val(msg)` if value is a callable else `val`. """ if callable(val): name = val(msg) else: name = val return name
def format_labels(labels): """Convert a dictionary of labels into a comma separated string""" if labels: return ",".join(["{}={}".format(k, v) for k, v in labels.items()]) else: return ""
def _patchlines2cache(patchlines, left): """Helper that converts return value of ParsePatchToLines for caching. Each line in patchlines is (old_line_no, new_line_no, line). When comment is on the left we store the old_line_no, otherwise new_line_no. """ if left: it = ((old, line) for old, _, line in p...
def chunk(l, n): """ Creates n-sized chunks from l. """ return [l[pos:pos + n] for pos in range(0, len(l), n)]
def ensure_list(obj): """ This function ensures that *obj* is a list. Typically used to convert a string to a list, for instance ensuring the *fields* as an argument is a list. """ if obj is None: return [obj] if not isinstance(obj, list): return [obj] return obj
def truncate_db(db,depth): """ Truncated database according to the given depth. Dictionary is truncated as None, while string is not truncated. E.g. db: {"CO":{"COL100":"foo"},"HU":"bar"} depth: 1 result: {"CO":None,"HU":"bar"} """ depth = int(dept...
def get_share_range(level: int): """Returns the share range for a specific level The returned value is a list with the lower limit and the upper limit in that order.""" return int(round(level * 2 / 3, 0)), int(round(level * 3 / 2, 0))
def parse_to_slug(words, maxlen=24): """ Parse a string into a slug format suitable for use in URLs and other character restricted applications. Only utf-8 strings are supported at this time. :param str words: The words to parse. :param int maxlen: The maximum length of the slug. :return: The parsed words as a ...
def human_readable_label_term(term, label_names=None, mul="*", pow="^", bracket=False): """ Return a human-readable form of a single term in the label vector. :param term: A structured term. :param label_names: [optional] The names for each label in the label vector. :param mu...
def pathjoin(*args): """Join a /-delimited path. """ return b"/".join([p for p in args if p])
def encode(name, value): """Return the encoded header line.""" return '{}: {}\r\n'.format(name, value).encode('ascii')
def sec_to_time(sec): """Print time in a correct format.""" dt = list() days = int(sec // 86400) if days > 0: sec -= 86400*days dt.append(str(days) + " d") hrs = int(sec // 3600) if hrs > 0: sec -= 3600*hrs dt.append(str(hrs) + " h") mins = int(sec // 60) ...
def ascii6_to_bin(data) -> str: """ Convert ASCII into 6 bit binary. :param data: ASCII text :return: a binary string of 0's and 1's, e.g. 011100 011111 100001 """ binary_string = '' for c in data: if c < 0x30 or c > 0x77 or 0x57 < c < 0x60: print("Invalid char") ...
def __convert_string_to_numeric_array(string): """ Converts a numeric string to an array of integers. """ return [int(char) for char in string]
def length_of_vlint (value): """ :param value: Any non-negative integral value :returns: Determine the number of octets required to express *value* as by :func:`pack_vlint`. :rtype: :class:`int` """ octets = 1 while (1 << (8 * octets)) <= value: octets += 1 return octets
def calculate_desired_noise_rms(clean_rms: float, snr: float) -> float: """ Given the Root Mean Square (RMS) of a clean sound and a desired signal-to-noise ratio (SNR), calculate the desired RMS of a noise sound to be mixed in. Source: https://github.com/iver56/audioment...
def _possible_scalar_to_1D(scalar,Nrows): """If the input value is not indexable (and not a string), extend it to a list of Nrows values. If it is indexable, leave it as is (unless it's a string). Should also pass 2D arrays through without changes (may fail for 2D arrays of strings, have not tested). ...
def generateAcceptHeader(*elements): """Generate an accept header value [str or (str, float)] -> str """ parts = [] for element in elements: if type(element) is str: qs = "1.0" mtype = element else: mtype, q = element q = float(q) ...