content
stringlengths
42
6.51k
def decompose_number_on_base(number, base): """ Returns a number's decomposition on a defined base :param number: The number to decompose :param base: list representing the base. It must be sorted and each element must be a multiple of its predecessor. First element must be 1. :raises TypeError: if base is invalid """ _base = list(base) try: assert(_base[0] == 1) for i in range(1, len(_base)): assert(_base[i] > _base[i-1]) ratio = float(_base[i]) / float(_base[i-1]) assert(ratio == int(ratio)) except AssertionError: raise TypeError("Base (%s) is invalid"%_base) _base.reverse() output = [0]*len(_base) for base_index in range(len(_base)): r = number % _base[base_index] output[base_index] = int((number-r)/_base[base_index]) number = r output.reverse() return output
def impedance_delany_and_bazley(frequency, flow_resistivity): """ Normalised specific acoustic impedance according to the empirical one-parameter model by Delany and Bazley. :param frequency: Frequency :math:`f`. :param flow_resistivity: Flow resistivity :math:`\\sigma`. The impedance :math:`Z` is given by .. math:: Z = 1 + 9.08 \\left( \\frac{1000f}{\\sigma}\\right)^{-0.75} - 11.9 j \\left( \\frac{1000f}{\\sigma}\\right)^{-0.73} """ return 1.0 + 9.08 * (1000.0*frequency/flow_resistivity)**(-0.75) - 1j * 11.9 * (1000.0*frequency/flow_resistivity)**(-0.73)
def recursive_apply(obj, fn, *args, **kwargs): """Recursively applies a function to an obj Parameters ---------- obj : string, tuple, list, or dict Object (leaves must be strings, regardless of type) fn : function function to be applied to the leaves (strings) Returns ------- string, tuple, list, or dict Object of the same type as obj, with fn applied to leaves """ if type(obj) in [str, bytes]: return fn(obj, *args, **kwargs)#obj.format(**(mapping)) elif type(obj) == tuple: return tuple(recursive_apply(list(obj), fn, *args, **kwargs)) elif type(obj) == list: return [recursive_apply(o, fn, *args, **kwargs) for o in obj] elif type(obj) == dict: return {k: recursive_apply(v, fn, *args, **kwargs) for k, v in obj.items()} else: return fn(obj, *args, **kwargs) # return obj
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resnet_size: The number of convolutional layers needed in the model. Returns: A list of block sizes to use in building the model. Raises: KeyError: if invalid resnet_size is received. """ choices = { 9: [2, 2], 18: [2, 2, 2, 2], 34: [3, 4, 6, 3], 50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3], 200: [3, 24, 36, 3] } try: return choices[resnet_size] except KeyError: err = ( 'Could not find layers for selected Resnet size.\n' 'Size received: {}; sizes allowed: {}.'.format(resnet_size, choices.keys()) ) raise ValueError(err)
def scanforfiles(fname): """ return list of iteration numbers for which metafiles with base fname exist """ import glob allfiles = glob.glob(fname + '.' + 10*'[0-9]' + '.001.001.meta') if len(allfiles) == 0: allfiles = glob.glob(fname + '.' + 10*'[0-9]' + '.meta') off = -5 else: off = -13 itrs = [ int(s[off-10:off]) for s in allfiles ] itrs.sort() return itrs
def get_neighbor_expression_vector(neighbors, gene_expression_dict): """Get an expression vector of neighboring genes. Attribute: neighbors (list): List of gene identifiers of neighboring genes. gene_expression_dict (dict): (Gene identifier)-(gene expression) dictionary. """ expressions = [] # Expression vector. for gene in neighbors: try: expression = gene_expression_dict[gene] except KeyError: continue expressions.append(expression) return expressions
def colorscale(hexstr, scalefactor): """ Scales a hex string by ``scalefactor``. Returns scaled hex string. To darken the color, use a float value between 0 and 1. To brighten the color, use a float value greater than 1. >>> colorscale("DF3C3C", .5) 6F1E1E >>> colorscale("52D24F", 1.6) 83FF7E >>> colorscale("4F75D2", 1) 4F75D2 """ def clamp(val, minimum=0, maximum=255): if val < minimum: return minimum if val > maximum: return maximum return val if scalefactor < 0 or len(hexstr) != 6: return hexstr r, g, b = int(hexstr[:2], 16), int(hexstr[2:4], 16), int(hexstr[4:], 16) r = int(clamp(r * scalefactor)) g = int(clamp(g * scalefactor)) b = int(clamp(b * scalefactor)) return "%02x%02x%02x" % (r, g, b)
def computeblocksize(expectedrows, compoundsize, lowercompoundsize): """Calculate the optimum number of superblocks made from compounds blocks. This is useful for computing the sizes of both blocks and superblocks (using the PyTables terminology for blocks in indexes). """ nlowerblocks = (expectedrows // lowercompoundsize) + 1 if nlowerblocks > 2**20: # Protection against too large number of compound blocks nlowerblocks = 2**20 size = int(lowercompoundsize * nlowerblocks) # We *need* superblocksize to be an exact multiple of the actual # compoundblock size (a ceil must be performed here!) size = ((size // compoundsize) + 1) * compoundsize return size
def _get_info_path(path): """Returns path (`str`) of INFO file associated with resource at path.""" return '%s.INFO' % path
def _search(forward, source, target, start=0, end=None): """Naive search for target in source.""" m = len(source) n = len(target) if end is None: end = m else: end = min(end, m) if n == 0 or (end-start) < n: # target is empty, or longer than source, so obviously can't be found. return None if forward: x = range(start, end-n+1) else: x = range(end-n, start-1, -1) for i in x: if source[i:i+n] == target: return i return None
def ceildiv(dividend, divisor): """ceiling-division for two integers """ return -(-dividend // divisor)
def one_semitone_up(freq, amount=1): """ Returns the key, one semitone up :param freq: the frequency in hz :param amount: the amount of semitones up :return: the frequency one tone up in hz """ return freq * 2 ** (amount / 12)
def create_structure_values(type: str) -> dict: """Create a dict with example field values for all common structure attributes.""" return dict( id="structure_id", name="structure_name", type=type, branchid="branch_id", chainage="1.23", )
def string_index_type_compatibility(string_index_type): """Language API changed this string_index_type option to plural. Convert singular to plural for language API """ if string_index_type == "TextElement_v8": return "TextElements_v8" return string_index_type
def get_default_from_fields(form_fields): """ Takes a dictionary of field name and UnboundField instance and returns their default values as dict of field name and value """ defaults = {} for field_name, field in form_fields.items(): defaults[field_name] = field.kwargs["default"] return defaults
def get_group(items, group_count, group_id): """Get the items from the passed in group based on group count.""" if not (1 <= group_id <= group_count): raise ValueError("Invalid test-group argument") start = group_id - 1 return items[start:len(items):group_count]
def int_str_to_int(int_str: str) -> int: """ example formats: 1234 0xabcd 0b0101 (so they always start with a digit) """ if int_str.startswith('0x'): int_value = int(int_str[2:], 16) elif int_str.startswith('0b'): int_value = int(int_str[2:], 2) else: int_value = int(int_str) return int_value
def _GetApiNameFromCollection(collection): """Converts a collection to an api: 'compute.disks' -> 'compute'.""" return collection.split('.', 1)[0]
def shift(n: int, add: int, mod: int) -> int: """Shift n of add modulo mod.""" return (n + add) % mod
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight): """ Crops a rectangle by the specified number of pixels on each side. The input rectangle and return value are both a tuple of (x,y,w,h). """ # Unpack the rectangle x, y, w, h = rect # Crop by the specified value x += cropLeft y += cropTop w -= cropLeft + cropRight h -= cropTop + cropBottom # Re-pack the padded rect return (x, y, w, h)
def get_tweet_rating(tweet): """ Function that count tweet rating based on favourites and retweets """ return (tweet['retweet_count'] * 2) + tweet['favourites_count']
def trap(height): """ :type height: List[int] :rtype: int """ if height == []: return 0 left = 0 right = len(height)-1 max_left = height[left] max_right = height[right] vol = 0 while left < right: if height[left] <= height[right]: max_left = height[left] if height[left] > max_left else max_left vol += max_left - height[left] left += 1 else: max_right = height[right] if height[right] > max_right else max_right vol += max_right - height[right] right -= 1 return vol
def diff_date(truth_date, computed_date): """Compare two dates. Returns (match?, reason for mismatch).""" if computed_date == truth_date: return (True, '') if computed_date is None: return (False, 'Missing date') if truth_date is None: return (False, 'Should be missing date') return (False, 'complex')
def email_address_str(name, email): """ Create an email address from a name and email. """ return "%s <%s>" % (name, email)
def pow_mod(a: int, b: int, p: int) -> int: """ Computes a^b mod p using repeated squaring. param a: int param b: int param p: int return: int a^b mod p """ result = 1 while b > 0: if b & 1: result = (result * a) % p a = (a * a) % p b >>= 1 return result
def clean(iterator) -> list: """ Takes an iterator of strings and removes those that consist that str.strip considers to consist entirely of whitespace. """ iterator = map(str.strip, iterator) return list(filter(bool, iterator))
def scale(kernel): """ Scales a 2D array to [0, 255] """ minimum = min(min(k) for k in kernel) maximum = max(max(k) for k in kernel) return [[int(255 * (k - minimum) / (maximum - minimum)) for k in row] for row in kernel]
def pkg_version_cmp(left: str, right: str) -> int: """Naive implementation of version comparison (which trims suffixes).""" left_clean, _, _ = left.partition("-") right_clean, _, _ = right.partition("-") if left_clean < right_clean: return -1 if left_clean == right_clean: return 0 return 1
def dX_dt(x, r, t=0): """ Return parabolic growth rate of x with param r""" return r*x + x**3 - x**5
def getGeneCount(person, geneSetDictionary): """ determines how many genes a person is assumed to have based upon the query information provided """ if person in geneSetDictionary["no_genes"]: gene_count = 0 elif person in geneSetDictionary["one_gene"]: gene_count = 1 else: gene_count = 2 return gene_count
def in_array(needle, haystack): """ Checks if a value exists in an array """ return (needle in haystack)
def escape_line_delimited_text(text: str) -> str: """ Convert a single text possibly containing newlines and other troublesome whitespace into a string suitable for writing and reading to a file where newlines will divide up the texts. Args: text: The text to convert. Returns: The text with newlines and whitespace taken care of. """ return text.replace("\n", " ").strip()
def _describe_method(method: dict) -> str: """Make a human readable description of a method. :arg method: Method object. :returns: Method data in readable form. """ description = method['name'] for parameter in method['parameters']: description += ' {}'.format(parameter['name']) if method['doc']: description += '\n {}'.format(method['doc']) if method['parameters']: description += '\n' for parameter in method['parameters']: description += '\n {} {}'.format( parameter['typename'], parameter['name']) if parameter['doc']: description += ': {}'.format(parameter['doc']) if method['return']['fmt']: description += '\n\n returns {}'.format( method['return']['typename']) if method['return']['doc']: description += ': {}'.format(method['return']['doc']) return description
def follow_person(name): """Move the robot so that it constantly follows a person, this is a combined usage of recognizeFace() and move() function. Not implemented. Parameters: name (string): name of the person that the robot should be following. Returns: (bool): True if successfully moved. False otherwise. """ success = True return success
def get_groups_starting_with(user_input, groups): """Return list of group names that start with the characters provided """ return [group for group in groups if group.lower().startswith(user_input.lower())]
def def_key(key): """Compute a definition ref from a key. Returns: str: The computed relative reference """ return f"#/definitions/{key}"
def fraction_of_paths(paths_dict, fraction=1.): """Get fraction of strongest paths whose probability sum to a certain fraction. Parameters ---------- paths_dict : dict. Dictionary of paths (tuple) and probabilities (float). Should be normalized, otherwise fraction might not actually get the fraction. fraction : float/int (default=1.). Find most likely paths which have a summed probability of at least 'fraction'. Returns ------- new_dict : dict. Dictionary of most likely paths which have a summed probability of at least 'fraction'. """ # Sort paths and probababilties from highest to lowest probability. sorted_probs, sorted_paths = zip(*sorted(zip(paths_dict.values(), paths_dict.keys()), reverse=True)) probsum = 0 for i, prob in enumerate(sorted_probs): probsum += prob # Enough paths to reach fraction? if probsum >= fraction: new_dict = dict(zip(sorted_paths[:i+1], sorted_probs[:i+1])) return new_dict # Not enough paths in whole dictionary to reach fraction. new_dict = paths_dict return new_dict
def wrap(val, cols, ind=0, indent_first_line=True): """ wrap the string in 'val' to use a maximum of 'cols' columns. Lines are indented by 'ind'. """ if val is None: return "" wrapped = [] for s in val.split("\n"): while len(s) > cols: last_good_wrap_point = -1 for i, c in enumerate(s): if c in ' ': last_good_wrap_point = i if i >= cols and last_good_wrap_point != -1: break if last_good_wrap_point != -1: wrapped.append(s[:last_good_wrap_point]) s = s[last_good_wrap_point+1:] else: break if s: wrapped.append(s) a_str = ("\n" + " "*ind).join(w for w in wrapped) if indent_first_line: return " "*ind + a_str return a_str
def end_of_quarter_month(month): """ method to return last month of quarter :param int month: :return: int """ while month % 3: month += 1 return month
def optimal_tilt(lat): """ Returns an optimal tilt angle for the given ``lat``, assuming that the panel is facing towards the equator, using a simple method from [1]. This method only works for latitudes between 0 and 50. For higher latitudes, a static 40 degree angle is returned. These results should be used with caution, but there is some evidence that tilt angle may not be that important [2]. [1] http://www.solarpaneltilt.com/#fixed [2] http://dx.doi.org/10.1016/j.solener.2010.12.014 Parameters ---------- lat : float Latitude in degrees. Returns ------- angle : float Optimal tilt angle in degrees. """ lat = abs(lat) if lat <= 25: return lat * 0.87 elif lat <= 50: return (lat * 0.76) + 3.1 else: # lat > 50 # raise NotImplementedError('Not implemented for latitudes beyond 50.') return 40
def missingNumber(nums): """ :type nums: List[int] :rtype: int """ total=sum(range(len(nums)+1)) return total-sum(nums)
def insensitive_compare1(s1: str, s2: str) -> bool: """ - Time Complexity: O(len(s1)) # len(s1) = len(s2) - Space Complexity: O(len(s)) # strings are immutable """ return s1.upper() == s2.upper()
def m2ft(meters: float) -> float: """ Convert meters to feet. :param float meters: meters :return: feet :rtype: float """ if not isinstance(meters, (float, int)): return 0 return meters * 3.28084
def is_int(value): """Check whether the `value` is integer. Args: value: arbitrary type value """ try: if int(f"{value}") == int(value): return True except ValueError as e: pass return False
def get_molecules(topology): """Group atoms into molecules.""" if 'atoms' not in topology: return None molecules = {} for atom in topology['atoms']: idx, mol_id, atom_type, charge = atom[0], atom[1], atom[2], atom[3] if mol_id not in molecules: molecules[mol_id] = {'atoms': [], 'types': [], 'charge': []} molecules[mol_id]['atoms'].append(idx) molecules[mol_id]['types'].append(atom_type) molecules[mol_id]['charge'].append(charge) return molecules
def dydt(y,t): """ This function returns the differential equation """ return y*(t**3)-1.5*y
def alias_map(col_config): """ aliases map Expand all the aliases into a map This maps from the alias name to the proper column name """ aliases = dict() for col, rules in col_config.items(): col_aliases = rules.get('aliases', []) col_aliases.append(col) col_aliases = list(set(col_aliases)) transformations = rules.get('transformations') if not transformations: aliases[col] = col_aliases else: first_trans = transformations[0] parameters = first_trans.get('parameters', [col]) sample_meta_name = parameters[0] aliases[sample_meta_name] = col_aliases return aliases
def build_day_numbers(starting_point): """ Create our range of day_numbers that will be used to calculate returns Looking from -starting_point to +starting_point to create timeframe band """ return [i for i in range(-starting_point, starting_point+1)]
def if_else(condition, a, b): """Provides Excel-like if/else statements""" if condition : return a else : return b
def lst_depth(lst): """Check max depth of nested list.""" if isinstance(lst, list): return 1 + max(lst_depth(item) for item in lst) return 0
def check_name_in_file(name_to_check, data): """checks if name is in file and returns True if it is""" if name_to_check in data: return True return False
def sec2str(t): """Returns a human-readable time str from a duration in s. Arguments --------- t: float Duration in seconds. Returns ------- str Human-readable time str. Example ------- >>> from inpystem.tools.sec2str import sec2str >>> sec2str(5.2056) 5.21s >>> sec2str(3905) '1h 5m 5s' """ # Decompose into hour, minute and seconds. h = int(t // 3600) m = int((t - 3600 * h) // 60) s = t - 3600 * h - 60 * m # Print digits if non-int seconds if isinstance(s, int): s_str = '{:d}'.format(s) else: s_str = '{:.2f}'.format(float(s)) # Display info depending on available elements. if h == 0 and m == 0: return "{}s".format(s_str) elif h == 0 and m != 0: return "{:d}m {}s".format(m, s_str) else: return "{:d}h {:d}m {}s".format(h, m, s_str)
def make_query_url(word): """Quickly turn a word into the appropriate Google Books url Args: word (str): Any word Returns: str: Google Books url for the word's popularity from 1970 to 2019 """ return f"https://books.google.com/ngrams/json?content={word}&year_start=1970&year_end=2019&corpus=26&smoothing=0&case_insensitive=true#"
def infer_relationship(coeff: float, ibs0: float, ibs2: float) -> str: """ Inferres relashionship labels based on the kin coefficient and ibs0 and ibs2 values. """ result = 'ambiguous' if coeff < 0.1: result = 'unrelated' elif 0.1 <= coeff < 0.38: result = 'below_first_degree' elif 0.38 <= coeff <= 0.62: if ibs0 / ibs2 < 0.005: result = 'parent-child' elif 0.015 < ibs0 / ibs2 < 0.052: result = 'siblings' else: result = 'first_degree' elif coeff > 0.8: result = 'duplicate_or_twins' return result
def group_list(lst, size=100): """ Generate batches of 100 ids in each Returns list of strings with , seperated ids """ new_list =[] idx = 0 while idx < len(lst): new_list.append( ','.join([str(item) for item in lst[idx:idx+size]]) ) idx += size return new_list
def sample_rate_str(wav_sample_rate_hz: float) -> str: """ Generate the sample rate string for the exported sound file :param wav_sample_rate_hz: target wav sample rate :return: string with sample rate in kHz """ wav_fs_str = '_' + str(int(wav_sample_rate_hz / 1000)) + 'khz.wav' return wav_fs_str
def returnAstar(current_node, energy, stars, fin): """ generates the path from start to the current node returns the path through the maze, energy left, stars collected * 2 and if it finished or not @param current_node: position of current node @param energy: energy left @param stars: collected stars @param fin: if the Algorithm could finish @return: Path taken, energy left, stars collected times 2, if function finished """ path = [] current = current_node while current is not None: path.append(current.position) current = current.parent return path[::-1], energy, stars, fin
def get_tip_cost(meal_cost: float, tip_percentage: int) -> float: """Calculate the tip cost from the meal cost and tip percentage.""" PERCENT = 100 return meal_cost * tip_percentage / PERCENT
def hand_rank(hand): """ Computes the rank of a hand, a number between 1 and 9, where lower numbers indicate better hands. Assumes the hand is given in ascending order of number. :param hand: a tuple with 5 tuples, each inner tuple representing a card from a standard deck. :return: the rank of the hand, a number between 1 and 9, where lower numbers indicate better hands. """ # A hand must consist of 5 cards. assert len(hand) == 5 # Straight flush. if all(hand[0][0] == card[0] for card in hand) and all( hand[i + 1][1] - hand[i][1] == 1 for i in [0, 1, 2, 3] ): return 1 # Four of a kind. elif all(hand[0][1] == hand[i][1] for i in [1, 2, 3]) or all( hand[1][1] == hand[i][1] for i in [2, 3, 4] ): return 2 # Full house. elif ( all(hand[0][1] == hand[i][1] for i in [1, 2]) and hand[3][1] == hand[4][1] ) or (all(hand[2][1] == hand[i][1] for i in [3, 4]) and hand[0][1] == hand[1][1]): return 3 # Flush. elif all(hand[0][0] == card[0] for card in hand): return 4 # Straight. elif all(hand[i + 1][1] - hand[i][1] == 1 for i in [0, 1, 2, 3]): return 5 # Three of a king elif ( all(hand[0][1] == hand[i][1] for i in [1, 2]) or all(hand[1][1] == hand[i][1] for i in [2, 3]) or all(hand[2][1] == hand[i][1] for i in [3, 4]) ): return 6 # Tow pair elif ( (hand[0][1] == hand[1][1] and hand[2][1] == hand[3][1]) or (hand[1][1] == hand[2][1] and hand[3][1] == hand[4][1]) or (hand[0][1] == hand[1][1] and hand[3][1] == hand[4][1]) ): return 7 # One pair elif any(hand[i][1] == hand[i + 1][1] for i in range(0, 4)): return 8 # High card return 9
def is_deletable_code(cell): """Returns whether or not cell is deletable""" # check if the "include" tag is in metadata if "tags" in cell["metadata"] and "include" in cell["metadata"]["tags"]: return False # check if the "ignore" tag is in metadata if "tags" in cell["metadata"] and "ignore" in cell["metadata"]["tags"]: return True # check if there is an image in the output elif len(cell["outputs"]) > 0: for output in cell["outputs"]: if "data" in output and "image/png" in output["data"]: return False # if neither of above is True, then cell is deletable return True
def create_block_option_from_template(text: str, value: str): """Helper function which generates the option block for modals / views""" return {"text": {"type": "plain_text", "text": str(text), "emoji": True}, "value": str(value)}
def amortization(loan, r, c, n): """Amortization Returns: The amount of money that needs to be paid at the end of each period to get rid of the total loan. Input values: loan : Total loan amount r : annual interest rate c : number of compounding periods a year n : total number of compounding periods """ ipp = r / c amt = (loan * ipp) / (1 - ((1 + ipp) ** (-n))) return amt
def map_SWAS_var2GEOS_var(var, invert=False): """ Map variables names from SWAS to GEOS variable names """ d = { # '1_3_butadiene':, # '1_butene':, # '2_3_methylpentane':, # '224_tmp':, 'acetaldehyde': 'ALD2', 'acetone': 'ACET', # 'acetylene':, 'benzene': 'BENZ', # GEOSChem, but not GEOS-CF output # 'benzenechb':, 'cis_2_butene': 'PRPE', # NOTE: lumped tracer for >= C3 alkenes 'cyclo_pentane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'dms': 'DMS', # GEOSChem, but not GEOS-CF output # 'dmschb':, 'ethane': 'C2H6', # 'ethene':, # 'ethylbenzene':, # 'extra_1':, # 'extra_2':, # 'extra_3':, # 'extra_4':, # 'extra_5':, # 'extra_l2':, 'iso_butane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'iso_butene': 'PRPE', # NOTE: lumped tracer for >= C3 alkenes 'iso_pentane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'isoprene': 'PRPE', # NOTE: lumped tracer for >= C3 alkenes 'methanol': 'MOH', 'mp_xylene': 'XYLE', 'n_butane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'n_heptane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'n_hexane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'n_octane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'n_pentane': 'ALK4', # NOTE: lumped tracer for >= C4 Alkanes 'o_xylene': 'XYLE', 'pent_1_ene': 'PRPE', # NOTE: lumped tracer for >= C3 alkenes 'propane': 'C3H8', 'propene': 'PRPE', # NOTE: lumped tracer for >= C3 alkenes 'toluene': 'TOLU', # 'toluenechb':, 'trans_2_butene': 'PRPE', # NOTE: lumped tracer for >= C3 alkenes 'trans_2_pentene': 'PRPE', # NOTE: lumped tracer for >= C3 alkenes } # Invert the dictionary? if invert: d = {v: k for k, v in list(d.items())} return d[var]
def getBoundary(x, r, n): """returns in the form [lower, upper)""" lower = x - r upper = x + r + 1 if lower < 0: lower = 0 if upper > n: upper = n return (lower, upper)
def index_of_position_in_1d_array(coordinate_ordering, system_side_length, position): """Return the index of an n-dimensional position embedded in a 1-dimensional array. The index is computed using the given ordering of coordinate weights as well as the side length of the system from which the n-dimensional position is taken. Args: coordinate_ordering (list of ints): The order of coordinates by which to increment the index. system_side_length (int): The number of points along a side of the system. position (list of ints): The vector indicating the position within the n-dimensional system. Returns: The integer index of the position in a 1D array. Examples: index_of_position_in_1d_array((2, 1, 0), 4, (1, 2, 3)) -> 27 (16 + 4 * 2 + 1 * 3). This is standard lexicographic ordering for 3D positions. index_of_position_in_1d_array((0, 1, 2), 2, (0, 1, 1)) -> 6 (2 * 1 + 4 * 1) index_of_position_in_1d_array((2, 0, 1), 3, (2, 1, 0)) -> 19 (9 * 2 + 1 + 3 * 0) """ return sum(position[i] * system_side_length ** coordinate_ordering[i] for i in range(len(coordinate_ordering)))
def is_circular(node): """ vstup: 'node' prvni uzel seznamu, ktery je linearni, nebo kruhovy vystup: True, pokud je seznam z uzlu 'node' kruhovy False, jinak casova slozitost: O(n), kde 'n' je pocet prvku seznamu """ if node is None: return False first_node = node while node.next: node = node.next if first_node is node: return True return False
def replace_git_in_str(text: str) -> str: """ so the suggested commmands make sense """ return text.replace('git', 'config')
def linear_map(x, a, b, A=0, B=1): """ .. warning:: ``x`` *MUST* be a scalar for truth values to make sense. This function takes scalar ``x`` in range [a,b] and linearly maps it to the range [A,B]. Note that ``x`` is truncated to lie in possible boundaries. """ if a == b: res = B else: res = (x - a) / (1.0 * (b - a)) * (B - A) + A if res < A: res = A if res > B: res = B return res
def string_for_link(string): """ :param string: a string :return: the inputted string with " " replacing by "+" and the "+" replacing by "%2b" it will be useful to use wget to download data """ final_str = "" for char in string: if char == " ": final_str += "+" elif char == "+": final_str += "%2b" else: final_str += char return final_str
def median_of_three(arr: list, left: int, mid: int, right: int) -> int: """Finds the corresponding index to the median of three numbers, O(1)""" a, b, c = arr[left], arr[mid], arr[right] if (a-b)*(b-c) > 0: return mid if (a-b)*(a-c) > 0: return right return left
def _get_read_region(read_name): """Extract region from read name (PRIVATE).""" return int(read_name[8])
def postprocess_predictions(predictions): """Splits data to binary numbers.""" result = [] for prediction in predictions: bits = [0 if x < 0.5 else 1 for x in prediction] bits_str = ''.join([str(x) for x in bits]) number = int(f'0b{bits_str}', 2) result.append(number) return result
def read(f): """Open a file""" return open(f, encoding='utf-8').read()
def pod_name(name): """ strip pre/suffices from app name to get pod name """ # for app deploy "https://github.com/openshift/hello-openshift:latest", pod name is hello-openshift if 'http' in name: name = name.rsplit('/')[-1] if 'git' in name: name = name.replace('.git', '') if '/' in name: name = name.split('/')[1] if ':' in name: name = name.split(':')[0] return name
def get_router_timeout_value(mantissa, exponent): """ Get the timeout value of a router in ticks, given the mantissa and\ exponent of the value :param mantissa: The mantissa of the value, between 0 and 15 :type mantissa: int :param exponent: The exponent of the value, between 0 and 15 :type exponent: int """ if exponent <= 4: return ((mantissa + 16) - (2 ** (4 - exponent))) * (2 ** exponent) return (mantissa + 16) * (2 ** exponent)
def initialize_ans(target): """ :param target: str, the answer defined by randomized function """ word = str() for i in range(len(target)): word = word + "-" return word
def constrain(x, x_max, x_min=None): """ Constrans a given number between a min and max value. Parameters ---------- x : scalar The number to constrain. x_max : scalar The upper bound for the constrain. x_min : scalar, default=None The lower bound for the constrain. If None, defaults to -`x_max`. Returns ------- scalar The constrained number. """ if x_min is None: x_min = -x_max return min(max(x, x_min), x_max)
def iterable(item): """ Predicate function to determine whether a object is an iterable or not. >>> iterable([1, 2, 3]) True >>> iterable(1) False """ try: iter(item) return True except TypeError: return False
def _vec_vec_scalar(vector_a, vector_b, scalar): """Linear combination of two vectors and a scalar.""" return [a * scalar + b for a, b in zip(vector_a, vector_b)]
def es_primo(num): """ Determina, a partir de un numero dado, si es primo o no :param num: Numero de entrada :return: Es primo o no >>> es_primo(8) 'No es primo' >>> es_primo(3) 'Es primo' >>> es_primo(1) Traceback (most recent call last): .. TypeError: No es valido >>> es_primo(9) Traceback (most recent call last): .. TypeError: No es valido """ if num < 2: raise TypeError('No es valido') elif num >= 9: raise TypeError('No es valido') elif num == 2: return 'Es primo' elif num >= 2 and num%num == 0 and num%1 == 0 and num%2 != 0: return 'Es primo' else: return 'No es primo'
def find_highest_multiple_of_three_ints(int_list): """Takes in a list of integers and finds the highest multiple of three of them""" if type(int_list) != list: raise TypeError( "The argument for find_highest_multiple_of_three_ints must be of type list.") elif len(int_list) == 3: one, two, three = int_list return one * two * three highest_product_of_3 = int_list[0] * int_list[1] * int_list[2] highest_product_of_2 = int_list[0] * int_list[1] lowest_product_of_2 = int_list[0] * int_list[1] highest = max(int_list[0], int_list[1]) lowest = min(int_list[0], int_list[1]) for i in range(2, len(int_list)): current = int_list[i] highest_product_of_3 = max( highest_product_of_3, highest_product_of_2 * current, lowest_product_of_2 * current) highest_product_of_2 = max( highest_product_of_2, current * lowest, current * highest) lowest_product_of_2 = min( lowest_product_of_2, current * highest, current * lowest) highest = max(highest, current) lowest = min(lowest, current) return highest_product_of_3
def first(c): """ Method to return the first element of collections, for a list this is equivalent to c[0], but this also work for things that are views @ In, c, collection, the collection @ Out, response, item, the next item in the collection """ return next(iter(c))
def strip_elements(elements, element_filters): """ Ex.: If stripped on elments [' '], ['a', ' b', 'c'] becomes ['a', 'b', 'c'] """ ret = [] for element in elements: for element_filter in element_filters: element = element.strip(element_filter) ret.append(element) return ret
def mps_to_kmh(velocity): """Meters per second to kilometers per hour""" return velocity * (3600.0 / 1000.0)
def sol1(limit) -> int: """ Simple solution with for, C-stylish """ total = 0 for x in range(limit): if x % 3 == 0 or x % 5 == 0: total += x return total
def convert_dot_notation(key, val): """ Take provided key/value pair and convert it into dict if it is required. """ split_list = key.split('.') if len(split_list) == 1: # no dot notation found return key, val split_list.reverse() newval = val item = None for item in split_list: if item == split_list[-1]: return item, newval newval = {item:newval} return item, newval
def cut_inv(n, deck_len, x): """Where is the card at position x before this cut?""" return (x + n) % deck_len
def _match_layernorm_pattern(gf, entry_node): """ Return the nodes that form the subgraph of a LayerNormalization layer """ def _axes_in_range(axes, rank): return all([x in range(-rank, rank) for x in axes]) try: params = {} mean_1, sqdiff_2, mul_3 = [gf[x] for x in entry_node.outputs] if not (mean_1.op == 'Mean' and sqdiff_2.op == 'SquaredDifference' and mul_3.op == 'Mul'): return None const_4 = gf[mean_1.inputs[1]] mean_1_rank = len(mean_1.datatype.get_shape()) if not (const_4.op == 'Const' and len(const_4.value.val) == 1 and _axes_in_range(const_4.value.val, mean_1_rank)): return None axes = const_4.value.val mean_5 = gf[sqdiff_2.outputs[0]] if not (mean_5.op == 'Mean'): return None const_6 = gf[mean_5.inputs[1]] mean_5_rank = len(mean_5.datatype.get_shape()) if not (const_6.op == 'Const' and len(const_6.value.val) == 1 and axes == const_6.value.val): return None axes = sorted([x if x > 0 else mean_1_rank - x for x in const_4.value.val]) ref_axes = list(range(mean_1_rank-len(axes), mean_1_rank)) if not all([x == y for (x,y) in zip(axes, ref_axes)]): return None params['axes'] = axes add_7 = gf[mean_5.outputs[0]] const_8 = gf[add_7.inputs[1]] # epsilon params['epsilon'] = const_8.value.val rsqrt_9 = gf[add_7.outputs[0]] mul_10 = gf[rsqrt_9.outputs[0]] if not (add_7.op == 'Add' and const_8.op == 'Const' and rsqrt_9.op == 'Rsqrt' and mul_10.op == 'Mul'): return None const_11 = gf[mul_10.inputs[1]] params['gamma'] = const_11.value.val if not (gf[mul_10.outputs[0]] == mul_3 and len(mul_10.outputs) == 2): return None mul_12 = gf[mul_10.outputs[1]] sub_13 = gf[mul_12.outputs[0]] if not (mul_12.op == 'Mul' and sub_13.op == 'Sub'): return None const_14 = gf[sub_13.inputs[0]] if not const_14.op == 'Const': return None params['beta'] = const_14.value.val add_15 = gf[sub_13.outputs[0]] if not (gf[add_15.inputs[0]] == mul_3 and add_15.op == 'Add'): return None layernorm_nodes = [mean_1, sqdiff_2, mul_3, const_4, mean_5, const_6, add_7, const_8, rsqrt_9, mul_10, const_11, mul_12, sub_13, const_14, add_15] return (layernorm_nodes, params) except: return None
def _trim_columns(columns, max_columns): """Prints a warning and returns trimmed columns if necessary.""" if len(columns) <= max_columns: return columns print(('Warning: Total number of columns (%d) exceeds max_columns (%d)' ' limiting to first max_columns ') % (len(columns), max_columns)) return columns[:max_columns]
def findStreams(media, streamtype): """Find streams. Args: media (Show, Movie, Episode): A item where find streams streamtype (str): Possible options [movie, show, episode] # is this correct? Returns: list: of streams """ streams = [] for mediaitem in media: for part in mediaitem.parts: for stream in part.streams: if stream.TYPE == streamtype: streams.append(stream) return streams
def string_from_source(source) : """Returns string like 'CxiDs2.0:Cspad.0' from 'DetInfo(CxiDs2.0:Cspad.0)' or 'DsaCsPad' from 'Source('DsaCsPad')' form input string or psana.Source object """ str_src = str(source) if '"' in str_src : return str_src.split('"')[1] # case of psana.String object str_split = str_src.rsplit('(',1) return str_split[1].split(')',1)[0] if len(str_split)>1 else str_src
def group_from_iterable(iterable, pivots): """ Group items from the iterable with a pivot >>> group_from_iterable([{'people': 'Alice', 'value':'7'}, {'people': 'Josh', 'value':'6'}, {'people': 'Alice', 'value': '10'}], ["people"]) {'Josh': [{'value': '6', 'people': 'Josh'}], 'Alice': [{'value': '7', 'people': 'Alice'}, {'value': '10', 'people': 'Alice'}]} """ group = {} for item in iterable: pivot_value = '\t'.join(map(lambda pivot_name: item[pivot_name], pivots)) group[pivot_value] = group.get(pivot_value, []) + [item] return group
def get_prices_of_discounted_products(order, discounted_products): """Get prices of variants belonging to the discounted products.""" line_prices = [] if discounted_products: for line in order: if line.variant.product in discounted_products: line_prices.extend([line.unit_price_gross] * line.quantity) return line_prices
def state_str(state): """Return a string describing an instance via its InstanceState.""" if state is None: return "None" else: return '<%s at 0x%x>' % (state.class_.__name__, id(state.obj()))
def find_min(nums): """ :type nums: List[int] :rtype: int """ l, r = 0, len(nums) - 1 while nums[l] > nums[r]: m = (l + r) // 2 if nums[m] > nums[r]: l = m + 1 elif nums[m] < nums[r]: r = m return nums[l]
def convert_temperature(val): """ Convert temperature from Kelvin (unit of 1/16th K) to Celsius """ return val * 0.0625 - 273.15
def sec2time(secs): #return strftime("%H:%M:%S",time.gmtime(secs)) # doesnt support millisecs """ >>> strftime("%H:%M:%S",time.gmtime(24232.4242)) '06:43:52' >>> sec2time(24232.4242) '06:43:52.424200' >>> """ m,s = divmod(secs,60) #print m,s h,m = divmod(m,60) if(s >= 10.0): return "%02d:%02d:%.3f"%(h,m,s) else: return "%02d:%02d:0%.3f"%(h,m,s)
def getStringsFromFile(list_file): """"Return list from file ignoring blanks and comments""" l = [] with open(list_file) as f: for line in f: line = line.strip() if len(line) > 0 and not line.startswith("#"): l.append(line) return l
def _parse_settings_args(args: list): """ Parse settings command args and get settings option and signal. """ if not args: return 'common', [] # 'common' is the option, when user does not use any option. else: try: option, signal, *_ = args except ValueError: return args[0], '' return option, signal
def as_integer(value): """Return the given value as an integer if possible.""" try: int_value = int(value) if value == int_value: return int_value except Exception: # The value wasn't even numeric. pass return value