content
stringlengths
42
6.51k
def _guess_format_from_name(path): """Get file format by name. Parameters ---------- path : str Path to file. Returns ------- str File format as a string. """ import os fname = os.path.basename(path) if fname.endswith('.nc'): return 'netcdf' el...
def CeilLog10Pow2(e): """Returns ceil(log_10(2^e))""" assert e >= -1650 assert e <= 1650 return (int(e) * 78913 + (2**18 - 1)) // 2**18
def l2o(path): """ Formats a list (['bla',0,'bla']) into an ODS path format ('bla.0.bla') :param path: list of strings and integers :return: ODS path format """ return '.'.join(filter(None, map(str, path)))
def aggregate_scores_max(scores: list): """ Aggregate the given scores by choosing the highest one """ if not scores: return "N/A" end_score = -1 for score in scores: try: score = float(score) except ValueError: continue if score > end_sco...
def sum_non_red(obj: object) -> int: """The sum of all numbers except from maps with a \"red\" property.""" if isinstance(obj, int): return obj if isinstance(obj, str): return 0 if isinstance(obj, list): return sum(map(sum_non_red, obj)) if isinstance(obj, dict): if '...
def set_cover(X, subsets): """ This algorithm finds an approximate solution to finding a minimum collection of subsets that cover the set X. It is shown in lecture that this is a (1 + log(n))-approximation algorithm. """ cover = set() subsets_copy = list(subsets) while True: S = max(subsets_co...
def validate(compression): """ Validate the compression string. Parameters ---------- compression : str, bytes or None Returns ------- compression : str or None In canonical form. Raises ------ ValueError """ if not compression or compression == b'\0\0\0\0'...
def ensure_safe_url(url): """Ensure the GenePattern URL ends with /gp""" if url.endswith('/'): url = url[:-1] if not url.endswith('/gp'): url += '/gp' return url
def _clean_archive_file_format(fmt: str) -> str: """Cleans the given file format string""" return fmt.lower().strip('.').strip(':')
def generate_pod_numbers(n_users, n_per_group): """ Generate pod numbers in sequence """ groups = [] for i in range(1, int(n_users / n_per_group) + 2): groups.extend([i] * n_per_group) groups = groups[:n_users] return groups
def str_to_int(string_list): """ convert list of hex strings into list of ints """ int_list = [int(x, 16) for x in string_list] return int_list
def replace_gll_link(py, simulation_directory, new_gll_directory): """ replace all gll links. """ script = f"{py} -m seisflow.scripts.structure_inversion.replace_gll_link --simulation_directory {simulation_directory} --new_gll_directory {new_gll_directory}; \n" return script
def min_count1(lst): """ Get minimal value of list, version 1 :param lst: Numbers list :return: Minimal value and its count on the list """ if len(lst) == 0: return [] count = 0 min_value = lst[0] for num in lst: if num == min_value: count += 1 el...
def find_startswith_endswith(arg_list, key, value): """Checks '--<key>anything<value>' is in arg_list.""" for i in range(len(arg_list)): if arg_list[i].startswith(key) and arg_list[i].endswith(value): return True return False
def get_features_name(npcs): """ Create the list of feature names depending on the number of principal components. Parameters ---------- npcs : int number of principal components to use Returns ------- list name of the features. """ names_root = [ 'coef...
def single_byte_to_hex(single_char): """ Read a single, decimal byte from the user and return a string of its hexidecimal value. This string should use lowercase and should always be exactly two characters long. Make sure you pad the beginning with a 0 if necessary, and make sure the string does NOT start with '0x'...
def anagram_lst(str1, str2): """ This function takes two strings and compares if they are Anagram using Lists.""" return sorted(list(str1.lower())) == sorted(list(str2.lower()))
def escape_for_bash(str_to_escape): """ This function takes any string and escapes it in a way that bash will interpret it as a single string. Explanation: At the end, in the return statement, the string is put within single quotes. Therefore, the only thing that I have to escape in bash is th...
def name_2_id(str_name_id): """Returns the number of a numbered object. For example: "Frame 3", "Frame3", "Fram3 3" returns 3.""" import re numbers = re.findall(r'[0-9]+', str_name_id) if len(numbers) > 0: return float(numbers[-1]) return -1
def txx(x): # pylint: disable=no-else-return """Converts tempint integer to flag. Returns: Temporal interpolation flag for smooth HDF5 filename """ if x: if int(x) == 5: return 'p' elif int(x) == 10: return 'd' else: return 'c' ...
def _isnumber(obj): """ Function copied from putil.misc module to avoid import loops """ return ( (((obj is not None) and (not isinstance(obj, bool)) and (isinstance(obj, int) or isinstance(obj, float) or isinstance(obj, complex)))) )
def align_addr(addr: int, to_bytes: int = 8) -> int: """ align an address to `to_bytes` (meaning addr & to_bytes = 0) """ return addr + (-addr % to_bytes)
def massage(depender, components, packages): """ @param depender: A DependerData object @param components: Component names, in either package/component format, or just "naked" (hopefully unique) components. @param packages: Package names, which expand into their constituent components. @return A set of al...
def convert_to_seconds(time): """list -> number Given a list of four numbers: days, hours, minutes, and seconds, write the function convert_to_seconds that computes the total number of seconds that is equivalent to them. >>> convert_to_seconds([0, 0, 2, 3]) 123 >>> convert_to_seconds([0, 1, 0, 0]) ...
def HSW_offset(r, rs, alpha, Rv, beta, deltac, offset): """ HSW (Hamaus-Sutter-Wendelt) function for the universal void density profile See: Hamaus et al. (2014) """ numerator = 1-(r/rs)**alpha denominator = 1+(r/Rv)**beta return deltac*numerator/denominator +offset
def unique2(s): """Implement an algorithm to determine if a string has all unique characters.""" # O(n) time, O(n) space return len(set(s)) == len(s)
def is_cutg_label(x): """Checks if x looks like a CUTG label line.""" return x.startswith('>')
def as_list(arg): """Convenience function used to make sure that a sequence is always represented by a list of symbols. Sometimes a single-symbol sequence is passed in the form of a string representing the symbol. This has to be converted to a one-item list for consistency, as a list of symbols is w...
def replace_at(span, string, pattern): """Return a copy of `string` where the `span` range is replaced by `pattern`. """ start, end = span return string[:start] + pattern + string[end:]
def utrue(x,y): """ Return true solution for a test case where this is known. This function should satisfy u_{xx} + u_{yy} = 0. """ utrue = x**2 - y**2 return utrue
def num_to_alpha(num): """ Convert a number > 0 and < 24 into it's Alphabetic equivalent """ num = int(num) # Ensure num is an int if num < 0: raise ValueError("wtf? num_to_alpha doesn't like numbers less than 0...") if num > 24: raise ValueError("seriously? there's no way you hav...
def _conv_general_param_type_converter(window_strides, lhs_dilation, rhs_dilation, dim): """Convert strides, lhs_dilation, rhs_dilation to match TF convention. For example, in the 3D case, if lhs_dilation = 2, then convert it to [2, 2, 2] if lhs_dilation...
def Block_f(name, text): """ :param name: The "name" of this Block :param text: The "text" of this Block """ return '\\begin{block}{' + name + '}\n' + text + '\n\\end{block}\n'
def _generate_layer_name(name, branch_idx=None, prefix=None): """Utility function for generating layer names. If `prefix` is `None`, returns `None` to use default automatic layer names. Otherwise, the returned layer name is: - PREFIX_NAME if `branch_idx` is not given. - PREFIX_Branch_0_NAME ...
def word2wid(word, word2id_dict, OOV="<oov>"): """ Transform single word to word index. :param word: a word :param word2id_dict: a dict map words to indexes :param OOV: a token that represents Out-of-Vocabulary words :return: int index of the word """ for each in (word, word.lower(), wor...
def _ternary_search_float(f, left, right, tol): """Trinary search: minimize f(x) over [left, right], to within +/-tol in x. Works assuming f is quasiconvex. """ while right - left > tol: left_third = (2 * left + right) / 3 right_third = (left + 2 * right) / 3 if f(left_third) <...
def htmlize(value): """ Turn any object into a html viewable entity. """ return str(value).replace('<', '&lt;').replace('>', '&gt;')
def remove_all(original_list:list, object_to_be_removed): """ Removes object_to_be_removed in list if it exists and returns list with removed items """ return [i for i in original_list if i != object_to_be_removed]
def get_signal_annotations(func): """Attempt pulling python 3 function annotations off of 'func' for use as a signals type information. Returns an ordered nested tuple of (return_type, (arg_type1, arg_type2, ...)). If the given function does not have annotations then (None, tuple()) is returned. """...
def plus_replacement(random, population, parents, offspring, args): """Performs "plus" replacement. This function performs "plus" replacement, which means that the entire existing population is replaced by the best population-many elements from the combined set of parents and offspring. ...
def bool_or_empty(string): """Function to convert boolean string to bool (or None if string is empty)""" if string: return bool(strtobool(string)) else: return None
def add_zero(s: str, i: int) -> str: """ Adds "0" as a suffix or prefix if it needs it. """ if "." in s and len(s.split(".")[1]) == 1: return s + "0" if i != 0 and len(s) == 4: return "0" + s return s
def get_dim_names_for_variables(variables): """ Analyses variables to gather a list of dimension (coordinate) names. These are returned as a set of dimension names. """ return {dim for v in variables for dim in v.dims}
def get_unicode_dicts(iterable): """ Iterates iterable and returns a list of dictionaries with keys and values converted to Unicode >>> gen = ({'0': None, 2: 'two', u'3': 0xc0ffee} for i in range(3)) >>> get_unicode_dicts(gen) [{u'2': u'two', u'0': None, u'3': u'12648430'}, {u'2': u'two', u'0'...
def classify_type(type): """ Reclassify the museums using Iain's classification """ type = type[:5].upper() # because they can be a bit inconsistent on wikipedia if type == 'AGRIC': classifed_type = 'Local' elif type == 'AMUSE': classifed_type = 'Other' elif type == 'ARCHA': classifed_type = 'Histor...
def new_func(message): """ new func :param message: :return: """ def get_message(message): """ get message :param message: :return: """ print('Got a message:{}'.format(message)) return get_message(message)
def is_triangular_matrix(matrix, expected_dim): """ Checks that matrix is actually triangular and well-encoded. :param matrix: the checked matrix :type matrix: list of list :param expected_dim: the expected length of the matrix == number of rows == diagonal size :type expected_dim: """ ...
def get_errno(e): """ Return the errno of an exception, or the first argument if errno is not available. :param Exception e: the exception object """ try: return e.errno except AttributeError: return e.args[0]
def my_round_even(number): """ Simplified version from future """ from decimal import Decimal, ROUND_HALF_EVEN d = Decimal.from_float(number).quantize(1, rounding=ROUND_HALF_EVEN) return int(d)
def ckstr(checksum): """Return a value as e.g. 'FC8E', i.e. an uppercase hex string with no leading '0x' or trailing 'L'. """ return hex(checksum)[2:].rstrip('L').upper()
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_uniquen...
def decodeServiceStatusFrame(ba, frameLength, reserved_2_24, isDetailed): """Decode a Service Status frame. Args: ba (byte array): Contains all the bytes of the frame. frameLength (int): Holds the current length of this frame. reserved_2_24 (byte): Reserved bits in frame header. ...
def trim_taxon(taxon: str, int_level: int) -> str: """ taxon_hierarchy: '1|2|3|4|5|6|7' level: 5 output: '1|2|3|4|5' """ return '|'.join(taxon.split('|')[:int_level])
def _set_single_element_or_all_in_list(obj, key, value): """mutates obj, list of dict or dict""" if isinstance(obj, list): for element in obj: element[key] = value else: obj[key] = value return obj
def _M_b_fi_t_Rd(chi_LT_fi, W_y, k_y_theta_com, f_y, gamma_M_fi): """ [Eq. 5.61] :param chi_LT_fi: Reduction factor for lateral-torsion buckling in the fire design situation :param W_y: Sectional modulus (plastic for class 1 steel) :param k_y_theta_com: Reduction factor for yield strength at elevate...
def get_view_scope_by_dicom_dict(dicom_dict): """ If you set View Scope, the computing time of algorithm will be reduced. But the side effect is that maybe you don't know what the best view scope for each patient's case. There is some patient's case that is not scanned in middle position. So finally, I ...
def example_allow(actuator, *extra_args, **extra_kwargs): """ Example target function for example-allow Any parameter of an OpenC2-Command message can be used as an argument [action, actuator, args, id as cmd_id, target] Target will be the contents of the target object :param actuator: the instance ...
def add_chr_prefix(band): """ Return the band string with chr prefixed """ return ''.join(['chr', band])
def augmented_matrix(A, b): """returns the augmented matrix, assuming A is a square matrix""" aug, n = [], len(A) for i in range(n): t = A[i] t.append(b[i]) aug.append(t) return aug
def hoop_pressure_thin(t, D_o, P_o, sig): """Return the internal pressure [Pa] that induces a stress, sig, in a thin wall pipe of thickness t - PD8010-2 Equation (3). :param float t: Wall thickness [m] :param float D_o: Outside diamter [m] :param float P_o: External pressure [Pa] :param float s...
def perm0db(ind, beta=10.): """Perm function 0, D, BETA defined as: $$ f(x) = \sum_{i=1}^n (\sum_{j=1}^n (j+\beta) (x_j^i - \frac{1}{j^i}) )^2$$ with a search domain of $-n < x_i < n, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(1, 2, ..., n) = 0. """ return sum(( \ (...
def space_indentation(s): """The number of leading spaces in a string :param str s: input string :rtype: int :return: number of leading spaces """ return len(s) - len(s.lstrip(" "))
def move_right(board, row): """Move the given row to one position right""" board[row] = board[row][-1:] + board[row][:-1] return board
def uses_all(word, letters): """return True if the word use all the letters""" for letter in letters: if letter not in word: return False return True
def epsilonEffective(epsilon1=0.9, epsilon2=0.9): """ This function simply calculates the epsilon effective if you don't give the value for epsiln one or two it will consider it to be 0.9 by default""" result=1/(1/epsilon1+1/epsilon2-1) return result
def filter_dict(kv, p): """Given a dictionary, returns a new one retaining only pairs satisfying the predicate.""" return { k:v for k,v in kv.items() if p(k,v) }
def from_file(path): """Returns content of file as 'bytes'. """ with open(path, 'rb') as f: content = f.read() return content
def __checkInitdbParams(param): """ function : Check parameter for initdb -D, --pgdata : this has been specified in configuration file -W, --pwprompt: this will block the script --pwfile: it is not safe to read password from file -A, --auth,--auth-local,--auth-host: They will be ...
def _lz_complexity(binary_string): """Internal Numba implementation of the Lempel-Ziv (LZ) complexity. https://github.com/Naereen/Lempel-Ziv_Complexity/blob/master/src/lziv_complexity.py - Updated with strict integer typing instead of strings - Slight restructuring based on Yacine Mahdid's notebook: ...
def det_new_group(i, base=0): """Determine if new_group should be added to pipetting operation. Helper to determine if new_group should be added. Returns true when i matches the base, which defaults to 0. Parameters ---------- i : int The iteration you are on base : int, optional ...
def next(aList, index): """ Return the index to the next element (compared to the element with index "index") in aList, or 0 if it already is the last one. Useful to make a list of loop. """ return (index+1) % len(aList)
def validate_environment_state(environment_state): """Validate response type :param environment_state: State of the environment :return: The provided value if valid Property: ComputeEnvironment.State """ valid_states = ["ENABLED", "DISABLED"] if environment_state not in valid_states: ...
def get_odd_flags(odd_flags, blocks, flag_input=False): """Reverse the odd_flag list from the encoder""" odd_list = [flag_input] for odd_block in odd_flags: odd_list += odd_block # reverse odd_list.reverse() odd_de = blocks.copy() i = 0 for m, odd_block in enumerate(odd_de): ...
def get_relevant_lines(makeoutput): """ Remove everything from make output, that is not a makefile annotation and shell debug output, but leaves the + sign in front of them """ return [line for line in makeoutput.splitlines() if line.startswith("make") or line.startswith("+")]
def binary_to_decimal(binary): """Convert Binary to Decimal. Args: binary (str): Binary. Returns: int: Return decimal value. """ return int(binary, 2)
def intersect(list1, list2) -> bool: """Do list1 and list2 intersect""" if len(set(list1).intersection(set(list2))) == 0: return False return True
def modes(nums): """Returns the most frequently occurring items in the given list, nums""" if len(nums) == 0: return [] # Create a dictionary of numbers to how many times they occur in the list frequencies = {} for num in nums: frequencies[num] = 1 + frequencies.get(num, 0) # How...
def geometric_to_geopotential(z, r0): """Converts from given geometric altitude to geopotential one. Parameters ---------- z: float Geometric altitude. r0: float Planet/Natural satellite radius. Returns ------- h: float Geopotential altitude. """ h = r0...
def _compute_x_crossing( x1: float, y1: float, x2: float, y2: float, y_star: float) -> float: """Approximates the x value at which f(x) == y*. Args: x1: An x value. y1: f(x1). x2: An x value, where x2 > x1. y2: f(x2). y_star: The search value in [y1, y2]. Returns: The x value that gi...
def _instance_tags(hostname, role): """Create list of AWS tags from manifest.""" tags = [{'Key': 'Name', 'Value': hostname.lower()}, {'Key': 'Role', 'Value': role.lower()}] return [{'ResourceType': 'instance', 'Tags': tags}]
def calc_bmi(mass, height): """Calculates BMI from specified height and mass BMI(kg/m2) = mass(kg) / height(m)2 Arguments: mass {float} -- mass of the person in KG height {float} -- height of the person in meters Returns: bmi {float} -- Body Mass Index of the person from speci...
def fibonacci_loop(n): """ :param n: F(n) :return: val """ if n == 0: return 0 cache = [0,1] for i in range(n-2): cache[0],cache[1] =cache[1], cache[0] + cache[1] return cache[0] + cache[1]
def non_strict_impl(a, b): """Non-strict implication Arguments: - `a`: a boolean - `b`: a boolean """ if a == False: return True elif a == True: return b elif b == True: return True else: return None
def _parse_to_key_and_indices(key_strings): """given an arg string list, parse out into a dict assumes a format of: key=indices NOTE: this is for smart indexing into tensor dicts (mostly label sets) Returns: list of tuples, where tuple is (dataset_key, indices_list) """ ordered_keys ...
def get_shingles(sentence, n): """ Function to reveal hidden similarity edges between tweet-nodes based on SimHash, an LSH approximation on TF-IDF vectors and a cosine similarity threshold. Args: sentence (str): The sentence (preprocessed text from a tweet-node), from which the ...
def station_name_udf(name): """Replaces '/' with '&'.""" return name.replace("/", "&") if name else None
def copy_phrase_target(phrase: str, current_text: str, backspace='<'): """Determine the target for the current CopyPhrase sequence. >>> copy_phrase_target("HELLO_WORLD", "") 'H' >>> copy_phrase_target("HELLO_WORLD", "HE") 'L' >>> copy_phrase_target("HELLO_WORLD", "HELLO_WORL") 'D' >>> c...
def format_configuration(name, value, nearest, path, item_type): """Helper function for formating configuration output :param str name: name of the section being set, eg. paging or log :param str value: new value of the section :param str nearest: value of the nearest set section :param str path: pa...
def add_file_to_tree(tree, file_path, file_contents, is_executable=False): """Add a file to a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The path of the new file in the tree. file_contents The (UTF-8 encod...
def readonly_safe_field_as_twoline_table_row(field_label, field_value): """See readonly_field_as_table_row(). """ return {'field_label': field_label, 'field_value': field_value}
def convert_result(result, img_metas): """convert the result""" if result is None: return result bboxes = result.get("MxpiObject") for bbox in bboxes: bbox['x0'] = max(min(bbox['x0']/img_metas[3], img_metas[1]-1), 0) bbox['x1'] = max(min(bbox['x1']/img_metas[3], img_metas[1]-1), ...
def scale(c, s): """ Scales a cube coord. :param c: A cube coord x, z, y. :param s: The amount to scale the cube coord. :return: The scaled cube coord. """ cx, cz, cy = c return s * cx, s * cz, s * cy
def is_functioncall(reg): """Returns whether a Pozyx register is a Pozyx function.""" if (0xB0 <= reg <= 0xBC) or (0xC0 <= reg < 0xC9): return True return False
def mania_key_fix(objs_each_key, mode=0): """ Remove the 1/4 spaced adjacent notes to make the map perfectly playable. It's a lazy hack for the obvious loophole in the note pattern algorithm. Should set to inactive for low key counts. mode 0: inactive mode 1: remove latter note mode 2: remo...
def verify_dlg_sdk_proj_env_directory(path): """ Drive letter is not allowed to be project environment. Script checks in parent of 'path': a drive letter like C: doesn't have a parent. """ if(path.find(":\\")+2 >= len(path)): # If no more characters after drive letter (f.e. "C:\\"). return False else: return ...
def find_all_children(parent_class): """ Returns list of references to all loaded classes that inherit from parent_class """ import sys, inspect subclasses = [] callers_module = sys._getframe(1).f_globals['__name__'] classes = inspect.getmembers(sys.modules[callers_module], inspect.iscla...
def constraints_to_pretty_strings(constraint_tuples): """ Convert a sequence of constraint tuples as used in PackageMetadata to a list of pretty constraint strings. Parameters ---------- constraint_tuples : tuple of constraint Sequence of constraint tuples, e.g. (("MKL", (("< 11", ">= 10.1"...
def _get_full_name(code_name: str, proj=None) -> str: """ Return the label of an object retrieved by name If a :class:`Project` has been provided, code names can be converted into labels for plotting. This function is different to `framework.get_label()` though, because it supports converting popul...
def _create_example(product_id, question, answer): """Create an example dictionary.""" return { 'product_id': product_id, 'context': question, 'response': answer, }
def xml_value_from_key(xml,match,matchNumber=1): """ Given a huge string of XML, find the first match of a given a string, then go to the next value="THIS" and return the THIS as a string. if the match ends in ~2~, return the second value. """ for i in range(1,10): if match.endswith...