content
stringlengths
42
6.51k
def object_ndim(x): """Get the number of dimension of an object. Scalars return 0. Numpy arrays return their actual ndim value. Objects that support the buffer protocol return the ndim value of the corresponding memoryview. Nested lists are traversed to compute the effective number of dimensions....
def my_isclose(a, b, rel_tol=1e-09, abs_tol=0.0): """ Test if a and b are close enough to consider equal. This function is essentially the same as the math.isclose function which was added in Python 3.5 but is created here to increase compatibility across all Python 3 versions. """ retu...
def split_params(params): """Returns a list of values from a given string of comma-separated values. .. versionadded:: 1.0.0 """ return params.split(',')
def get_group_gn(planes): """ get number of groups used by GroupNorm, based on number of channels """ dim_per_gp = -1 num_groups = 32 assert dim_per_gp == -1 or num_groups == -1, \ 'GroupNorm: can only specify G or C/G' if dim_per_gp > 0: assert planes % dim_per_gp == 0 ...
def capitalize(value): """ Return a copy of the string with its first character capitalized and the rest lowercased. """ return value.capitalize()
def ex_cmd(COMMAND_LINE): """ Quotes and executes an external command in Python's safest way. Returns exit code, stdout, stderr. """ # secondary imports here to reduce startup time when this function is unused. import shlex from subprocess import Popen, PIPE quoted_command = shlex.split(COMMAND_LI...
def hill(x, baseline, amplitude, tconstant, hillcoef): """ Return the hill equation curve for the x values. """ return baseline+amplitude*(x**hillcoef)/(x**hillcoef+tconstant**hillcoef)
def has_nick_prefixe (nick, prefix): """gives true if nick has a prefix, else false """ return nick[0:len(prefix)] == prefix
def get_valid_pbc(inputpbc): """ Return a list of three booleans for the periodic boundary conditions, in a valid format from a generic input. :raise ValueError: if the format is not valid. """ if isinstance(inputpbc, bool): the_pbc = (inputpbc, inputpbc, inputpbc) elif (hasattr(inp...
def is_prime(number): # noqa: WPS 231 """Generate the rising prime sequence. Create a positive number range at first, and test each number is it a prime. Args: number: the maximal number should be tested. Returns: (List) prime sequence. """ primes = [] numbers = list(...
def modeler_fail(body): """ Callback function which work when modelling failed :param body: MassTransit message """ global MODELER_FAIL_FLAG MODELER_FAIL_FLAG = True return None
def _check_degrees_of_freedom(ddof, bias): """Check denominator degrees of freedom.""" if ddof is None: if bias: ddof = 0 else: ddof = 1 return ddof
def is_lp_fix_again(row): """Cannot be p and lp""" if row['is_pathogenic_final']: return False return row['lp']
def fix(x): """ Replaces spaces with tabs, removes spurious newlines, and lstrip()s each line. Makes it really easy to create BED files on the fly for testing and checking. """ s = "" for i in x.splitlines(): i = i.strip('\n\r') if len(i) == 0: continue #...
def guess_decimals( val, n_max=16, base=10, fp=16): """ Guess the number of decimals in a given float number. Args: val (): n_max (int): Maximum number of guessed decimals. base (int): The base used for the number representation. fp (int): The...
def _named_test_cases_product(dict1, dict2): """Utility for creating parameterized named test cases.""" named_cases = [] for k1, v1 in dict1.items(): for k2, v2 in dict2.items(): named_cases.append(('_'.join([k1, k2]), v1, v2)) return named_cases
def getInfo(brs_dict, key): """Extract the required info from the BRSynth annotation :param brs_dict: The BRSynth dictionary :param key: The key to extract the info from :type brs_dict: dict :type key: str :rtype: str :return: The extracted value """ try: toRet = brs_dict...
def clear(num: int, start: int, end: int) -> int: """ Sets zeros on bits of num from start to end non inclusive """ if start == end: raise ValueError('Start value same as end') # Builds group of 1s the size of the start - end mask: int = (1 << (end - start)) - 1 return num & ~(mask << start)
def find(p, xs): """Returns the first element of the list which matches the predicate, or undefined if no element matches. Dispatches to the find method of the second argument, if present. Acts as a transducer if a transformer is given in list position""" for found in (x for x in xs if p(x)): ...
def to_sentiment(score): """ Decide the sentiment as positive, negative and neutral from a compound score. :param compund_score: A float between -1 and 1 """ if score <= -0.05: return "negative" elif score >= 0.05: return "positive" else: return "neutral"
def compute_average_unit_cell(unit_cell_list): """Compute the weighted average unit cell based on a list of ((unit cell), nref) tuples.""" w_tot = 0.0 a_tot = 0.0 b_tot = 0.0 c_tot = 0.0 alpha_tot = 0.0 beta_tot = 0.0 gamma_tot = 0.0 for cell, n_ref in unit_cell_list: ...
def str2float(str_val, err_val=None): """ Convert a string to a float value, returning an error value if an error occurs. If no error value is provided then an exception is thrown. :param str_val: string variable containing float value. :param err_val: value to be returned if error occurs. If N...
def standard_approximation(mean, std): """Calculate standard approximation of mean and standard deviation. Calculates the standard approximation of mean and standard deviation by assuming that we are dealing with a normal distribution. Parameters ---------- mean : float Mean of the obs...
def is_sequence_of_uint(items): """Verify that the sequence contains only unsigned integers. Parameters ---------- items : sequence The sequence of items. Returns ------- bool """ return all(isinstance(item, int) and item >= 0 for item in items)
def parse_env_boolean(env_var): """ Get a boolean value passed by an environmental variable :param env_var: :return: """ if isinstance(env_var, str): env_var = env_var.strip() if env_var in (0, '0', 'false', 'False', False): return False if env_var in (1, '1', 'true', 'Tr...
def is_triangle(a, b, c): """ Determines if 3 integer values can from a triangle. :param a: an integer value. :param b: an integer value. :param c: an integer value. :return: true if a triangle can be built with the sides of given length and false in any other case. """ return a + b > c ...
def dms2ddd(hour, minute, second): """ from sexagesimal to decimal """ return hour+minute/60.0+second/3600.0
def mod10_to_mod2(dec, length=0): """ Converts decimal number to binary number, represented as list with MSB first, padded if necessary to ensure list size is equal to length parameter. """ # Convert dec to a binary string, with <length> leading zeros bin_str = format(dec, '0{}b'.format(length))...
def to_set(list_of_list): """ Transforms a list of list into a set [[0,1],[2]] -> {0,1,2} """ _set = set() for list_ in list_of_list: for element in list_: _set.add(element) return _set
def ListTrueOnly(adict): """Returns a list of strings for which their values were True in the dict. Args: adict: The original dictionary, with string keys and boolean values. Returns: A list of strings for which the boolean values were True in the dictionary. """ return [x for x in adict if adict[x]...
def unpack_list(a_list): """ ================================================================================================= unpack_list(a_list) This is a recursive function which takes a list of lists of... and returns a single list containing all elements of the input lists. ======...
def check_have_space(data, _): """An attacker has space if there is no defender in the same grid square""" for opponent in data["opposition"]: if opponent["coordinates"] == data["attacker"]["coordinates"]: print(f"{opponent['name']} is closing down {data['attacker']['name']}.") r...
def temp_commentary(current_temp): """Gives temperature advice to the end user.""" temperature = int(current_temp) temperature_level = { 0: "It's scorching hot right now. Stay inside and be cool!", 1: "It's hot and sunny right now. Don't forget that sunscreen!", 2: "It's nice and war...
def flatten(list_, ltypes=(list, tuple)): """Flatten nested list into a simple list.""" # Iterate `list_' from the beginning. i = 0 while i < len(list_): # While the list_'s i-th element is of a list-like type, while isinstance(list_[i], ltypes): # If the list-like element is...
def translate_tag(a_tag): """Convert string tag to an integer. @param a_tag - tag to convert @return int representation of the tag """ a_tag = a_tag.lower() if a_tag == "positive": return 1 elif a_tag == "negative": return 0 return int(a_tag)
def canonicalize_url(url, domain, full_url=None, protocol="https"): """ Return a canonical URL for the given URL. :param url: The URL to canonicalize. :type url: str :param domain: The domain to use for the canonical URL. :type domain: str :param full_url: Optional full URL to use for the c...
def fib_from_pascal(m): """Return the mth fibonacci number using Pascal's triangle.""" def fib_pascal(n, fib_pos): if n == 1: line = [1] fib_sum = 1 if fib_pos == 0 else 0 else: line = [1] prev, fib_sum = fib_pascal(n - 1, fib_pos + 1) ...
def round_scalar(scalar): """Rounds a scalar to the nearest integer Args: scalar (float): scalar to round Returns: int: input rounded to the nearest int """ return int(round(scalar))
def _entities_years_list_to_dict(l): """ Create a dict of entites by year :param l: list which each element is a size two tuple (year, entity_id :return: a dict in which each key is a year and each value is a list of entities :rtype: dict<int,list> """ d = {} for y, eid in l: y =...
def area_triangle(b, h): """ Returns the area of a triangle given its base and its height """ area = b * h / 2 return area
def is_in_domain2(i, j, m, n): """ Checks if i,j inside m,n """ return (i > 0) and (i < m) and (j > 0) and (j < n)
def naked(val): """ Given a string strip off all white space & quotes """ return val.strip(' "\'\t')
def _convert_line(line): """ Parameters ---------- line: str Returns ------- list """ line = line.upper().split() tmp = [] for i in line: if '.' in i: try: tmp.append(float(i)) except: tmp.append(i) el...
def get_tablename(string_identifier): """ Irrespective of the type of naming convetion used i.e. 3 part "schema.table.columnname" or 4 part "db.schema.table.columnname" this method expects the second part from the right to always be table name """ processed = string_identifier.split(".") ...
def make_optimal(sol): """Returns the optimal solution of a solvable pirellone given a first solution.""" switches_row = sol[0] switches_col = sol[1] m = len(switches_row) n = len(switches_col) if sum(switches_col) + sum(switches_row) > ((m + n) // 2): switches_row = [ 1-val for val in s...
def esc(*x): """Create escaped code from format code""" return '\033[' + ';'.join(x) + 'm'
def count_triangles(p): """ Returns the number of integer right triangles with perimeter p """ count = 0 for a in range(1, p//4 + 1): c = (a**2 + (p - a)**2)//(2*(p - a)) remainder = (a**2 + (p - a)**2) % (2*(p - a)) b = p - a - c if (remainder == 0) and (a <= b < c):...
def get_mapped_reads(fq_dict, mapped_reads): """Sort mapped reads from dictionary of fastq reads Args: fq_dict(dict) dictionary with read names as keys, seq and quality as values in a list mapped_reads(list) list of mapped reads Returns: fqd(dict) dictionary with read names a...
def _get_error_code_name(error_code): """ Get the Python exception name given an error code. If the error code doesn't end in "Error", the word "Error" will be appended. """ if error_code.endswith("Error"): return error_code else: return error_code + "Error"
def Luminosity(abs_mag): """ Converts AB magnitudes to luminosities in :math:`L_{sun}` :param abs_mag: AB magnitude of the object :type abs_mag: float or ndarray :return: luminosity :rtype: float or ndarray """ return 10.0 ** ((4.85 - abs_mag) / 2.5)
def get_index(elements, name): """Return index of a glTF element by a given name.""" if elements is None or name is None: return -1 index = 0 for element in elements: if isinstance(element, dict): if element.get('name') == name: return index else: ...
def ratioAlpha(clair): """Renvoi le coefficient de lettre min/maj et espace du message (entre 0 et 1).""" retour = 0 for i in clair: if ord(i) == 32 or 65<=ord(i)<=90 or 97<=ord(i)<=122: retour += 1 return float(retour)/len(clair)
def get_hostname_file(hostname): """ Update hostname on system """ return '# Automatically generated, do not edit\nHOSTNAME="%s"\n' % hostname
def zero_padding(num, length): """ Zero padding :param num: :param length: :return: """ return f'0000000000{num}'[-length:]
def count_inversion(sequence): """ Count inversions in a sequence of numbers """ s = list(sequence) a = 0 b = True while b: b = False for i in range(1, len(s)): if s[i-1] > s[i]: s[i], s[i-1] = s[i-1], s[i] a += 1 ...
def _stringify_maze(grid): """ Converts a grid back into its string form Args: grid: the 2D grid maze representation Returns: The string version of the maze as it is in a file """ return "\n".join(["".join(line) for line in grid])
def roman_to_arabic(roman): """Convert Roman numerals to Arabic numerals :param roman: :type roman: str :return: :rtype: int """ roman = roman.upper() invalid = ['IIII', 'VV', 'XXXX', 'LL', 'CCCC', 'DD', 'MMMM'] if any(sub in roman for sub in invalid): return None to_ara...
def jstree_item_to_dict(item, array): """ Return a jstree of the folder structure. :param item: :param array: :return: """ if item: for child_item in item.get_children(): array.append(dict( id=child_item.id, parent=item.id, ...
def evlmap(accdfid): """Return ``evlmap`` argument for ``.IterStatsConfig`` initialiser. """ if accdfid: evl = {'ObjFun': 'ObjFun', 'DFid': 'DFid', 'RegL1': 'RegL1'} else: evl = {} return evl
def dicts_to_dict(dictionaries, key_subfieldname): """Convert a list of dictionaries into a dictionary of dictionaries. key_subfieldname must exist in each Record's subfields and have a value, which will be used as the key for the new dictionary. If a key is duplicated, the earlier value will be overwr...
def check_permutation_sort(str1, str2): """Complexity: O(nlogn) time, O(1) space""" str1 = sorted(str1) str2 = sorted(str2) if len(str1) != len(str2): return False for i in range(len(str1)): if str1[i] != str2[i]: return False return True
def is_hr_between(time: int, time_range: tuple) -> bool: """ Calculate if hour is within a range of hours Example: is_hr_between(4, (24, 5)) will match hours from 24:00:00 to 04:59:59 """ if time_range[1] < time_range[0]: return time >= time_range[0] or time <= time_range[1] return time_...
def get_filter_arg_integer(f, arg): """Convert integer value to decimal string representation.""" return '%d' % arg
def strip_suffix(s: str, suffix: str): """Remove a suffix from a string. :param s: string :param suffix: suffix to remove from ``s`` """ if s is not None and s.endswith(suffix): return s[: -len(suffix)] return s
def trigger_measure_label(mode_val): """update the measure button upon choosing single or sweep""" if mode_val == 'single': return 'Single measure' else: return 'Start sweep'
def _start_end_step(arr): """ Return start, end, step if the array is a progression. """ if len(arr) == 1: return (arr[0], arr[0], 1) elif len(arr) == 2: return (arr[0], arr[1], arr[1] - arr[0]) elif list(range(arr[0], arr[-1] + 1, arr[2] - arr[1])) == arr: return (arr[0]...
def Win(CurrentStatus,word): """check if player win""" if CurrentStatus == word: return True else: return False
def force_str(s, encoding='utf-8', errors='strict'): """ Force string or bytes s to text string. """ if issubclass(type(s), str): return s try: if isinstance(s, bytes): s = str(s, encoding, errors) else: s = str(s) except UnicodeDecodeError as e: ...
def swap(state, src_index, dst_index): """ Swaps the numbers at the two given indexes. """ s = list(state) s[src_index], s[dst_index] = s[dst_index], s[src_index] return tuple(s)
def convolution_dict(D1, D2, op = lambda x,y:x*y,\ op_key = lambda x,y: x + y, \ commutative = True, op_twice = lambda x,y: x + y): """Convolution of two dictionaries :param D1: First dictionary :param D2: Second dictionary :param op: Operation of perform in value :param commutative...
def compute_multiples(origin_shape, broadcast_shape): """Compute multiples between origin shape with broadcast shape.""" len_gap = len(broadcast_shape) - len(origin_shape) return broadcast_shape[0:len_gap] + tuple(map(lambda x, y: x // y, broadcast_shape[len_gap:], origin_shape))
def __io_addr_reg(op): """ Return the i/o port address 'A' and register Rr/Rd from a 2-byte IN or OUT opcode sequence """ AVR_IO_IN_ADDR_MASK = 0x060F # mask for 'A' address for opcode `IN Rd,A`. nb non-contiguous addr_part = op & AVR_IO_IN_ADDR_MASK addr = ((addr_part >> 5) & 0x0030) | (addr_p...
def sqrt(c,err=1e-6): """ Returns: the square root of c to with the given margin of error. We use Newton's Method to find the root of the polynomial f(x) = x^2-c Newton's Method produces a sequence where x_(n+1) = x_n - f(x_n)/f'(x_n) = x_n - (x_n*x_n-c)/(2x_n) which we s...
def create_triangle_numbers(limit): """Return set of triangle numbers below limit.""" triangles = {0} increment = 1 value = 0 while True: value += increment increment += 1 if value > limit: break triangles.add(value) return triangles
def data_blobxfer_extra_options(conf): # type: (dict) -> str """Retrieve input data blobxfer extra options :param dict conf: configuration object :rtype: str :return: blobxfer extra options """ try: eo = conf['blobxfer_extra_options'] if eo is None: eo = '' ex...
def _fill_missing_fields(data_keys): """This is a stop-gap until all describe() methods are complete.""" result = {} for key, value in data_keys.items(): result[key] = {} # required keys result[key]['source'] = value.get('source') result[key]['dtype'] = value.get('dtype', 'nu...
def format_money_delta(x): """Formats input (money delta) into a string. For example, if x=-23.249m the output is '-$23.25'. Args: x: Float (postive or negative) representating dollars. """ return '{}${:,.2f}'.format('-' if x < 0 else '+', abs(x))
def take_closest(num,collection): """ Thanks for the advice stack overflow: http://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value """ return min(collection,key=lambda x:abs(x-num))
def v2_matrix_from_string(matrix_string): """Convert string-based rows of numbers to list of lists. Turning inner - row - for loop into a list comprehension. """ matrix = [] for row_string in matrix_string.splitlines(): matrix.append([float(n) for n in row_string.split()]) return matrix
def is_number(s): """ Small function to check if a value is numeric """ try: float(s) # for int, long and float - not complex as complex also allows 'J' as number or unit except ValueError: return False return True
def avg(x1, x2): """"Take average of 2 numbers.""" sum = x1 + x2 return sum / 2
def iterative_topological_sort(graph, start): """ Get Depth-first topology. :param graph: dependency dict (like a dask) {'a':['b','c'], 'c':['b'], 'b':[]} :param start: str the node you want to search from. This is equivalent to the node you want to compute. ...
def beautifulDays(i, j, k): """ Computes the i j - th element i. Args: i: (array): write your description j: (array): write your description k: (array): write your description """ count = 0; mylist=[] for i in range(i,j+1): mylist.append(str(i)); reverse...
def is_a_table(key): """ Used to ignore all dictionary entries that don't start with T_ """ return key.upper().startswith('T_')
def total_completion_time(schedule): """ Computes the total completion time for a given schedule. Args: schedule (list): a list of jobs (node object) listed according to the schedule. Returns: sum_Cj (float): the total completion time of all jobs in schedule. """ Cj = ...
def preprocess_Y(Y_vector): """Preprocessing the Y vector for the ML prediction. Args: Y_vector (list of SVariant): List with structural variants. Returns: list of int: List with coordinates of the structural variants (pos and end). """ Y_prepr = list() for sv in Y_vector: ...
def merge_dict(d1, d2): """ Merge 2 dictionaries together, keeping every element with unique key sequence. Relies on recursion. :param d1: Primary dictionary. :param d2: Secondary dictionary. If element is already present in d1, conflicting element from d1 will be replaced. :return: Combined dic...
def lower_first_letter(name): """Return name with first letter lowercased.""" if not name: return '' return name[0].lower() + name[1:]
def filter_plof(genes, records, db_info, lof_index): """Apply loss-of-function filters. Args: genes: list of Gene objects records: list of records as Variant objects db_info: database configuration as Config object lof_index: index of loss-of-function indicator in header """...
def is_list_or_tuple(x): """Return True if list or tuple.""" return isinstance(x, tuple) or isinstance(x, list)
def binary_search(c,b): """ Returns index of first occurrence of c in b; -1 if not found. Parameter b: The sequence to search Precondition: b is a SORTED sequence Parameter c: The value to search for Precondition: NONE (c can be any value) """ # Quick way to check if a sequence; CA...
def volume_type_get(volume_type_id, **kwargs): """ Returns id of the specified volume type name """ url = "/types/{volume_type_id}".format(volume_type_id=volume_type_id) return url, {}
def scale_down(src_size, size): """Scale down crop size if it's bigger than image size""" w, h = size sw, sh = src_size if sh < h: w, h = float(w*sh)/h, sh if sw < w: w, h = sw, float(h*sw)/w return int(w), int(h)
def find_reflexive_relation(matrix): """ Return a matrix of reflexive closure of the relation. >>> find_reflexive_relation([[1, 1, 1], [0, 0, 0], [1, 0, 0]]) [[1, 1, 1], [0, 1, 0], [1, 0, 1]] """ for index in range(len(matrix)): if matrix[index][index] != 1: matrix[in...
def is_number(s): """Returns True if string is a number.""" return s.replace(".", "", 1).isdigit()
def calcProgress(low, high, percent): """ utility function to calculate the progress between [low-high] @param - low - int begining of progress range @param - high - int end of progress range @param - percent - float progress percent of this range [0-100%] @return - int - new progress """ i...
def _uniq(seq): """Return the list of unique integers in a sequence, by keeping the order.""" seen = set() seen_add = seen.add return [int(x) for x in seq if not (x in seen or seen_add(x))]
def encode_chromosome(in_num): """ Encodes chromosome to same cn """ convert_dict = {23: "X", 24: "Y", 25: "MT"} return convert_dict[in_num] if in_num in convert_dict else str(in_num)
def x_min(iterable, amount=1, key=None): """ Returns the smallest items in the input :param iterable: An iterable :param amount: The amount of results :param key: The key with which to compare items :return: An iterable containing the 'amount' smallest items in the 'iterable' """ return...
def deep_merge(a, b, level=0, max_depth=9): """Deep merge 2 dicts a and b Dict b is merged into dict a. If a and b have the same key on the same level, b's value override a's. The maximum recusive depth is 9 by default. """ if level >= max_depth: return b else: level += 1 ...