content
stringlengths
42
6.51k
def PVIF(i,n,m=1): """ interest years payments per year """ PVIF = 1 / ((1 + i/m)**(m*n)) return PVIF
def linspace(lower,upper,length): """Basically np.linspace, but without needing to import numpy...""" return [lower + x*(upper-lower)/float(length-1) for x in range(length)]
def map_keys(function, dictionary): """Apply `function` to every key of `dictionary` and return a dictionary of the results. >>> d = {'1': 1, '2': 2} >>> sorted_items(map_keys(lambda key: 'k' + key, d)) [('k1', 1), ('k2', 2)] """ return dict([(function(key), value) for key, value in diction...
def get_guidelines(lang): """Returns a localized url for the download of the user_guidelines. """ elri_guidelines='metashare/ELRI_user_guidelines_'+lang+'.pdf' return elri_guidelines
def reverse(original: str) -> str: """ >>> reverse("abc") 'cba' >>> reverse('1234') '4321' >>> reverse("cba321") '123abc' >>> reverse("") '' """ return original[::-1]
def powset(S): """In : S (set) Out: List of lists representing powerset. Since sets/lists are unhashable, we convert the set to a list,perform the powerset operations, leaving the result as a list (can't convert back to a set). Example: S = {'ab', 'bc'} ...
def surface_margin_deph(A_approx_deph, A_real_deph): """ Calculates the surface margin. Parameters ---------- A_approximate_deph : float The approximate heat ransfer area, [m**2] A_real_deph : float The real heat transfer area, [m**2] Returns ------- surface_margin_de...
def format_pylist_to_mathematica_legend(labelname_syntax, pylabel_list): """ Helper funciton. convert python list to be mathematica list for the legend Parameters ------------- labelname_syntax : str label type syntax in the Wolfram Mathematica . pylabel_list : list the lis...
def __dbName(fromLang, toLang): """Caculate the name for a mapping""" return "%s-%s" % (fromLang, toLang)
def name_version(nvr): """ Split a Debian NVR into "name" and "version". :returns: two-element tuple of "name" and "version" for this package. :raises: ValueError if this does not look like a valid package. """ result = nvr.split('_') if len(result) == 2: return tuple(result) # ...
def sgn(number): """Get unitary sign number.""" return -1 if number < 0 else (1 if number else 0)
def _p_upperbound(b, m): """Compute the upper bound of the p-value according to [3]. Input arguments: b : int Number of permutations yielding a test statistic at least extreme as the observed value. m : int Number of permutations Output arguments: The upper bound of...
def scale_gen_freq_for_run_steps_int(charmm_variable, run_steps): """ Scales the frequency of the output to a a more realistic value, if the output frequency does not make sense based on the total number of simulation run steps. Parameters ---------- charmm_variable : GOMCControl object var...
def flatten_list(unflattened_list): """ Take list of iterables/non-iterables and outputs a list of non-iterables. """ flattened_list = [] for item in unflattened_list: if hasattr(item, '__iter__') and not isinstance(item, str): flattened_list.extend(item) else: ...
def is_subdict(X, Y): """ checks whether X is contained by Y, i.e., whether X is a "sub-dictionary" of Y. returns bool. """ return set(X.items()).issubset(set(Y.items()))
def read_with_check(buf, pos, nbytes): """ Reads and returns n bytes. :param buf: The input buffer :param pos: The current position :param nbytes: number of bytes to open_topography in :return: The bytes and the new position in the buffer """ if len(buf) < nbytes or len(buf) - nbytes < ...
def group_size(fSize): """ Group file sizes into range categories. """ if fSize < 1024: return 1 elif fSize < 16384: return 2 elif fSize < 32768: return 3 elif fSize < 65536: return 4 elif fSize < 131072: return 5 elif fSize < 262144: ...
def vertex_item_cmp(x,y): """ Comparison function for sorting vertex_dict.items() w.r.t. to the vertex indices (values). """ return x[1]-y[1]
def header_blocks(test_count, failures): """ Creates blocks for either success or failure Args: test_count: int - Total test count failures: List[TestFailure] Returns: List[Dict] - Block Kit representation for Slack posting """ blocks = [] if len(failures) > 0: ...
def build_extension(name, parameters): """ Build an extension definition. This is the reverse of :func:`parse_extension`. """ return '; '.join( [name] + [ # Quoted strings aren't necessary because values are always tokens. name if value is None else '{}={}'....
def apply_rule(t_deps, dep_h, rel_rels, overlap_func): """ Checks whether the relations match and the words match according to the specified overlap path. :param t_deps: a list of all dependency triples (tuples) in the text :parm dep_h: the current (i.e. to be checked) dependency triple (tuple) in the ...
def filter_none_from_parameters(params): """Removes parameters whos value is :obj:None Args: params (dict): dictionary of parameters to be passed to the API. Returns: dict: the original parameters with any parameters whos value was :obj:`None` removed. """ return { ...
def to_bool(input): """ >>> to_bool('1') True >>> to_bool('True') True >>> to_bool('true') True >>> to_bool(True) True >>> to_bool(False) False >>> to_bool('False') False >>> to_bool('false') False >>> to_bool('0') False >>> to_bool(None) ...
def _get_single_node(nodes, allow_zero=False): """Helper function for when a particular set of nodes returned from `xpath` should have exactly one node. If null_case is False, """ if len(nodes) == 1: return nodes[0] elif len(nodes) == 0 and allow_zero: return None else: ...
def compare_index(lefti, righti): """Compares to indexes and returns dict with all added, removed and changed records""" setl = set(lefti.keys()) setr = set(righti.keys()) diffl = setl.difference(setr) diffr = setr.difference(setl) inter = setl.intersection(setr) changed = [] for i in in...
def get_capi_file_name(cppname): """ Convert a C++ header file name to a C API header file name. """ return cppname[:-2] + '_capi.h'
def part1(fish): """ Each lanternfish creates a new lanternfish once every 7 days New lanternfish need an extra 2 days for their first cycle 7-day timer is 0-6 How many lanternfish would there be after 80 days? """ for day in range(80): for i in range(len(fish)): if fish...
def offset2line(offset, linestarts): """linestarts is expected to be a *list) of (offset, line number) where both offset and line number are in increasing order. Return the closes line number at or below the offset. If offset is less than the first line number given in linestarts, return line number...
def fib_sequence(n): """ Returns the fibonacci sequence as a list up to the nth fibonacci number Args: n (int): the position of the number in the Fibonacci sequence you want to go up to Returns: list: the nth number in the Fibonacci sequence For example, fib_sequence(5)...
def highlight_text(text): """ Wrap HTML styling around a text to make it red :param text: string :return: string with HTML tags """ return "<span style=\" font-size:8pt; font-weight:600; color:#ff0000;\" >" + text + "</span>"
def get_words_from_tuples(examples): """ You may find this useful for testing on your development data. params: examples - a list of tuples in the format [[(token, label), (token, label)...], ....] return: a list of lists of tokens """ return [[t[0] for t in example] for example in examples]
def spatial_interpolate(start, end, samples): """ Interpolate between two points with a given number of samples Usage: spatial_interpolate([0,0,0],[0,-10,0], 5) spatial_interpolate([24.28, 0.0, 10.72], [26.87, 0.0, -6.72], 5) :param start: list(float, float, float), 3d point ...
def _check_vals(item): """ Check if item is evaluatable and returns the value of it. Example 'False' should return False 'ABC' should return 'ABC' PARAMETERS: String (the value from a key/value pair) RETURNS : type of evaluated string """ import ast try: val = ast...
def efficientnet_params(model_name): """Map EfficientNet model name to parameter coefficients.""" params_dict = { # Coefficients: width,depth,res,dropout "efficientnet-b0": (1.0, 1.0, 224, 0.2), "efficientnet-b1": (1.0, 1.1, 240, 0.2), "efficientnet-b2": (1.1, 1.2, 260, 0.3), ...
def get_next_bb(sn): """ Increment BB_ label numbering :param sn: BB label string :return: incremented label string """ assert('BB_' in sn) return 'BB_' + str(int(sn.strip()[3:]) + 1)
def add_three(one, two, three): """Adds three values together and returns it.""" return one + two + three
def match(p_entities, r_entities, type): """ Match predicted entities with gold entities. """ p_entities = [tuple(entity) for entity in p_entities if entity[-1] == type] r_entities = [tuple(entity) for entity in r_entities if entity[-1] == type] pcount = len(p_entities) rcount = len(r_entiti...
def is_iterable(obj): """Determine if an object is iterable. :param any obj: The object to test :returns bool: Whether it is iterable or not """ try: for _ in obj: break except TypeError: return False else: return True
def _serializeSubIds(subIds): """ Serialize a set of unit subIds, without regard for the playerId. """ val = 0 for i in subIds: val |= (1 << i) return "{:x}".format(val)
def _get(result, field, mandatory=False, default="", transform=lambda x: x): """Retrieve a given field if available, return default or exception otherwise. Result may be manipulated by transformation function""" if field in result: return transform(result[field]) else: if mandatory: raise KeyError("...
def get_int_icode(res_seq): """ Return tuple (int, icode) with integer residue sequence number and single char icode from PDB residue sequence string such as '60A' or '61' etc. Parameters: res_seq - PDB resisue sequence number string, with or without icode Return value: tuple (int...
def get_dataset_years(dataset_year): """ Get the first and second year in a dataset year of the format 2018-19 """ first, second = dataset_year.split('-') second = first[:2] + second return first, second
def _parse_decimal(s): """Parse a floating point with implicit leading dot. >>> _parse_decimal('378') 0.378 """ return float('.' + s)
def ConstantTimeIsEqual(a, b): """Securely compare two strings without leaking timing information.""" if len(a) != len(b): return False acc = 0 for x, y in zip(a, b): acc |= ord(x) ^ ord(y) return acc == 0
def _get_replacements(tokens, data, sec): """Helper function for _read_config. """ replacements = list() for token in tokens: if ':' in token: tsec, tkey = token.split(':') tval = '' if tsec in data: if tkey in data[tsec]: tval ...
def iob2(tags): #{{{ """ Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2. """ for i, tag in enumerate(tags): if tag == 'O': continue split = tag.split('-') if split[0] not in ['I', 'B']: #if len(split) != 2 or split[0] no...
def removeprefix(string: str, prefix: str) -> str: """ Removes the given prefix from a string. Only the first instance of the prefix is removed. The original string is returned if it does not start with the given prefix. This follows the Python 3.9 implementation of ``str.removeprefix``. :param st...
def percentToParam(percent: int, min: int, max: int) -> int: """Convert a percentage to a raw parameter value given the current percentage and the minimum and maximum raw parameter values. @param percent: The current percentage. @type percent: int @param min: The minimum raw parameter value. @type min: int ...
def IF(logical, value1, value2) -> str: """ Creates an IF statement >>> IF("1=1"", 0, 1) 'IF("1=1"", 0, 1)' """ return "IF({}, {}, {})".format(logical, value1, value2)
def get_file_dep_dict(mod_dep_dict, mod_path_dict): """Transform ModuleName in 'mod_dep_dict' with ModuleFileName with given given 'mod_path_dict'. Args: mod_dep_dict (dictionary): output of 'get_moddep_dict' function mod_path_dict (dictionary): output of 'get_modpath_dict' function ...
def climbStairs(n): """ :type n: int :rtype: int """ if n==1: return 1 dp = [0] * (n + 1) dp[1] = 1 dp[2] = 2 for i in range(3, n+1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n]
def recursive_binary_search(array, search_term, p=0, r=None): """ Binary search algorithm for finding an int in an array, using recursion. Returns index of first instance of search_term or None. """ if r == None: r = len(array) - 1 if p > r: return None else: q = (p +...
def common_subset(sets, key_by=None): """ From a list of lists compute set common to all lists. sets -- List or iterator of collections of objects. (Example: [[a,b,c], [b,c,d]]) key_by -- Function that extracts/computes key from object, defaults to identity """ def mk_get(key_by): if key...
def get_neighbors_of(cell): """ Return the neighbors of cell. """ x = cell[0] y = cell[1] neighbors = set() for i in range(x-1, x+2): for j in range(y-1, y+2): if (i, j) != cell: neighbors.add((i, j)) return neighbors
def last_k(tokens, k): """Get the last k elements of a list as a tuple.""" if not (0 <= k <= len(tokens)): raise ValueError('k must be between 0 and len(tokens) = {}, got: {}'.format(len(tokens), k)) return tuple(tokens[len(tokens) - k:])
def find_threshold_crossings(arr, _threshold): """ Find all indices at which a threshold is crossed from above and from below in an array. Used for finding indices to compute ap widths and half widths. """ #print("threshold = {}".format(_threshold)) ups = [] downs = [] for i, _ in enumer...
def is_exist_in_db(db, table, key): """ Check if provided hash already exists in Config DB Args: db: reference to Config DB table: table to search in Config DB key: key to search in Config DB Returns: bool: The return value. True for success, False o...
def camelcase_css_name(css_name): """Convert hyphen-separated-name to UpperCamelCase. E.g., '-foo-bar' becomes 'FooBar'. """ return ''.join(word.capitalize() for word in css_name.split('-'))
def getVariableType(v): """ Replacing bools with ints for Python compatibility """ vType = v['Type'] vType = vType.replace('bool', 'int') vType = vType.replace('std::function<void(korali::Sample&)>', 'std::uint64_t') return vType
def trim(set, height, level): """Trim the given set to the given level and add all nodes of that level. Removes all nodes in the given set that are above the given level, and add all nodes of the given level. In cases where the set contains a lot of duplicate nodes in upper levels, this can reduce the ...
def get_value(parameter, key, default): """Helper function to get value in dictionary.""" return ( default if key not in parameter or (isinstance(parameter[key], list) and not len(parameter[key])) or parameter[key] is None else parameter[key] )
def phantom_bullet_with_body_dict(phantom_request_with_body_dict): """Phantom bullet with body property values as a dictionary.""" bullet_with_body_dict = {'0': '214 tests'} bullet_with_body_dict.update(phantom_request_with_body_dict) return bullet_with_body_dict
def findFilenames(reference_fn_str, target_fn_str, filenames, n): """ Find filenames given a start string for UC Davis data Parameters -------------- reference_fn_str : str - the control antibody (reference antibody) target_fn_str : str - the antibody of interest filenames : list of strs - ...
def str_get_as_list_without_ending_empty_line(content: str) -> list: """The provided string is split into lines """ lines = content.split('\n') while len(lines[-1]) == 0 or lines[-1] == '\n': lines = lines[:-1] return lines
def make_resonance_pattern(num): """ Create a pulse pattern of [1, 1, 0, 1, ...]. Only for the case when the clock frequency is the qubit frequency. """ return [1 for i in range(int(num))]
def choice(m_state, rule): """Takes the rule and the state, and returns a boolean as choice""" return int(rule[-1 - m_state])
def first(predicate, it): """Return the first element in `iterable` that `predicate` Gives a :const:`True` value for. If `predicate` is None it will return the first item that is not None. """ return next( (v for v in it if (predicate(v) if predicate else v is not None)), None, ...
def whether_prefix(coords): """determine whether gene IDs should be prefixed with nucleotide IDs. Parameters ---------- coords : dict Gene coordinates table. Returns ------- bool Whether gene IDs should be prefixed. See Also -------- read_gene_coords Notes...
def bluetoothValidate(address): """ Returns True if the string argument appears to be a Bluetooth address (strictly speaking, a MAC address) arguments: address - string MAC address returns: boolean - True if it appears to be a bluetooth address, otherwise false """ ...
def merge_partial_elements(element_list): """ merges model elements which collectively all define the model component, mostly for multidimensional subscripts Parameters ---------- element_list Returns ------- """ outs = dict() # output data structure for element in element...
def rbgToHex(*clr): """Given a color in rbg, convert it to hexadecimal color""" if len(clr) != 3 or max(clr) > 255 or min(clr) < 0: raise ValueError('invalid color') return '#' + ''.join([ hex(c)[2:].zfill(2) for c in clr ]).upper()
def get_matches_for_completion(text, candidates): """Create matches for readline completion for text. candidates is a sequence of candidates to match. The returned list ends with a None. """ return [w + ' ' for w in candidates if w.startswith(text)] + [None]
def _get_set_env_var_command(name, value): """Return command to set environment variable on device.""" return ['--env={n}={v}'.format(n=name, v=value)]
def format_obj_keys(obj, formatter): """ Take a dictionary with string keys and recursively convert all keys from one form to another using the formatting function. The dictionary may contain lists as values, and any nested dictionaries within those lists will also be converted. :param object ...
def searchkit_sort_options(sort_options, default_sort): """Format sort options to be used in React-SearchKit JS. :param sort_options: A dictionary containing the field name as key and asc/desc as value. :returns: A list of dicts with sorting options for React-SearchKit JS. """ return [ ...
def insertion_sort(lst): """Returns a sorted array. A provided list will be sorted out-of-place. Args: list: a list to be sorted. Returns: list: a new list, sorted from least to greatest. """ for i in range(1, len(lst)): current_idx = i temp_val = lst[i] ...
def if_then(arg, clause): """Factored out ternary for when a filter clause contains a None arg.""" return clause if arg is not None else True
def rstrip_null_bytes(s): """Right-strip any null bytes at the end of the given string.""" return s.rstrip(b'\x00')
def make_options(a, b, g, d, alpha_name, beta_name=None, gamma_name=None, delta_name=None): """Map alpha, beta, gama and delta values into a named arguments dictionary.""" options = {} if a is not None and alpha_name: options[alpha_name] = a if b is not None and beta_name: options[beta_n...
def _tupleize(dct): """Take the dict of options and convert to the 2-tuple format.""" return [(key, val) for key, val in dct.items()]
def cache_filter(item): """help method to filter cache that should be cleaned """ return item.startswith('watchlist')
def humanize_duration(seconds): """Converts seconds into HH:MM:SS""" seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 if hour > 0: return "%d:%02d:%02d" % (hour, minutes, seconds) else: return "%02d:%02d" % (min...
def get_organism_from_read(read): """Assumes a read is named something like chr1_human:344102""" return read.split(":")[0].split("_")[-1]
def get_pickle_file_path(file_name, target, folder): """ Returns a path to a saved file Parameters ---------- file_name: str name of the saved file target: str name of target column folder: str name of the folder file is saved in Returns ------- path to ...
def detokenize(token_rules, words): # Deprecated? """ To align with treebanks, return a list of "chunks", where a chunk is a sequence of tokens that are separated by whitespace in actual strings. Each chunk should be a tuple of token indices, e.g. >>> detokenize(["ca<SEP>n't", '<SEP>!'], ["I", "ca"...
def harvestMethods(cls): """ Obtain the Monte methods of a class. The class must have already been harvested. NOT_RPYTHON """ d = {} # Walk the MRO and harvest Monte methods. The repacker has already placed # them in the correct location. for c in reversed(cls.__mro__): if...
def get_absolute_url(path): """ Generate an absolute URL for a resource on the test server. """ return 'http://testserver/{}'.format(path.lstrip('/'))
def remove_common_elements(package_list, remove_set): """ Remove the common elements between package_list and remove_set. Note that this is *not* an XOR operation: packages that do not exist in remove_set (but exists in remove_set) are not included. Parameters ---------- package_list : lis...
def fast_mod_exp(b, e, n): """ A fast algorithm for modular exponentiation (see square-and-multiply). """ assert b >= 1 and e >= 1 and n >= 1, "b, e and n must all be > 0" result = b if (e & 1) else 1 exp_bit_len = e.bit_length() for x in range(1, exp_bit_len): b = (b ** 2) % n ...
def _ArgSort(a): """Returns the indices that would sort an array. Ties are given indices in ordinal order.""" return sorted(range(len(a)), key=a.__getitem__)
def coding_problem_08(bt): """ A unival tree (which stands for "universal value") is a tree where all nodes have the same value. Given the root to a binary tree, count the number of unival subtrees. Example: >>> btree = (0, (0, (0, None, None), (0, (0, None, None), (0, None, None))), (1, None, None...
def _build_paths(resid) -> str: """Build a API URL from an Azure resource ID.""" res_info = { "subscription_id": resid.split("/")[2], "resource_group": resid.split("/")[4], "workspace_name": resid.split("/")[-1], } url_part1 = ( f"https://management.azure.com/subscriptio...
def get_halo_boundary_key(mdef): """ For the input mass definition, return the string used to access halo table column storing the halo radius. For example, the function will return ``halo_rvir`` if passed the string ``vir``, and will return ``halo_r200m`` if passed ``200m``, each of which correspo...
def candidate_priority(candidate_component, candidate_type, local_pref=65535): """ See RFC 5245 - 4.1.2.1. Recommended Formula """ if candidate_type == 'host': type_pref = 126 elif candidate_type == 'prflx': type_pref = 110 elif candidate_type == 'srflx': type_pref = 100 ...
def extract_lzh (archive, compression, cmd, verbosity, interactive, outdir): """Extract a LZH archive.""" opts = 'x' if verbosity > 1: opts += 'v' opts += "w=%s" % outdir return [cmd, opts, archive]
def showname(keyvalue): """filter koji za neku od prosledjenih kljuceva vraca vrednost""" key_dict ={'P':'Accepted','C': 'Created','Z': 'Closed','O': 'On Wait'} return key_dict[keyvalue]
def recognize_greeting(statement): """Recognizes if string statement starts with Hi or Hey or any other greeting, Args: statement (str): a string from the commandline from the user Returns: bool: True if statement is a greeting. False otherwise. # >>> recognize_greeting('hi'): Tru...
def to_tuple(x): """Converts lists to tuples. For example:: >>> from networkx.utils import to_tuple >>> a_list = [1, 2, [1, 4]] >>> to_tuple(a_list) (1, 2, (1, 4)) """ if not isinstance(x, (tuple, list)): return x return tuple(map(to_tuple, x))
def text_to_number(str_number): """ This function contains dicts used to convert word representation of numbers to the int equivalent. :param str_number: String representing a number :return: int number """ number_words = {} if not number_words: til_nineteen = [ ...
def either(a, b): """ :param a: Uncertain value (might be None). :param b: Default value. :return: Either the uncertain value if it is not None or the default value. """ return b if a is None else a