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 inva...
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 :mat...
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...
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: ...
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: ...
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. """ expres...
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) ...
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 = (expecte...
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 ...
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"] ret...
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: in...
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 ...
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...
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') ...
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 ret...
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 ...
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: ...
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 ...
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']) ...
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...
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...
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 ...
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 result...
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] = {'a...
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 =...
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) ...
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=201...
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...
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 ...
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_...
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 ...
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 h...
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"][...
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 compo...
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', # 'a...
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 ...
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 whi...
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: ...
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 += "+" ...
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) ...
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 ...
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...
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_m...
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 ...
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: ...
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) 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 spl...
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.o...
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 c...
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...
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 ...
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...
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_...
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,...
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: ...
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