content
stringlengths
42
6.51k
def get_dict_recursive(dct, key): """ Helper function to get the value corresponding to path/to/key from a nested dict. """ if '/' in key: base, newkey = key.split('/', maxsplit=1) return get_dict_recursive(dct[base], newkey) else: try: ret = dct[key] ...
def is_valid_response(resp): """ Validates a Discovery response Fail if a failure response was received """ return resp.get("result") != "failure"
def hamming(correct, observed): """ Calculates hamming distance between correct code and observed code with possible errors Args: correct: the correct code as list (binary values) observed: the given code as list (binary values) Returns: distance: the hamming distance between cor...
def is_self_referencing(dep): """ Self-referencing dependencies have an ' as the last character. """ return dep["root"][-1] == "'" or dep["dep"][-1] == "'"
def create_dictionary_of_words(full_string): """Creates a dictionary of words and number of their occurrences in a string""" list_of_words = full_string.split() # Creating list of all words. list_of_words = list(dict.fromkeys(list_of_words)) # Deleting duplicates from the list of all words. # Creat...
def columnise(rows, padding=2): """Print rows of entries in aligned columns.""" strs = [] maxwidths = {} for row in rows: for i, e in enumerate(row): se = str(e) nse = len(se) w = maxwidths.get(i, -1) if nse > w: maxwidths[i] = nse...
def last_index_in_list(li: list, element): """ Thanks to https://stackoverflow.com/questions/6890170/how-to-find-the-last-occurrence-of-an-item-in-a-python-list """ return len(li) - next(i for i, v in enumerate(reversed(li), 1) if v == element)
def generate_onehot_dict(word_list): """ Takes a list of the words in a text file, returning a dictionary mapping words to their index in a one-hot-encoded representation of the words. """ word_to_index = {} i = 0 for word in word_list: if word not in word_to_index: word_...
def instantiate_steady_state_mutable_kwargs(dissolve, block_kwargs, solver_kwargs, constrained_kwargs): """Instantiate mutable types from `None` default values in the steady_state function""" if dissolve is None: dissolve = [] if block_kwargs is None: block_kwargs = {} if solver_kwargs i...
def _ge_from_le(self, other): """Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).""" op_result = self.__le__(other) if op_result is NotImplemented: return NotImplemented return not op_result or self == other
def rename_group(str_group2=None): """ Rename OFF food group (pnns_group_2) to a standard name Args: str_group2 (str): OFF food group name Returns: conv_group (str): standard food group name """ #convert_group1 = {'Beverage':['Beverages'], # 'Cereals':['Cerea...
def _has_i(word): """ Determine if a word is "I" or a contraction with "I". """ return word == 'i' or word.startswith('i\'')
def countwhile(predicate, iterable): """ return count of leading characters that satisfy the predicate """ count = 0 for character in iterable: if predicate(character): count += 1 else: break return count
def impl_key_dict(value, priority=1): """to reduce duplicate code in configs.py and handcar_configs.py""" return { 'syntax': 'STRING', 'displayName': 'Implementation Key', 'description': 'Implementation key used by Runtime for class loading', 'values': [ {'value': val...
def unsupLossBSchedule(iteration): """ Schedule for weighting loss between forward and backward loss """ if iteration > 400000: return 0.5 elif iteration > 300000: return 0.5 elif iteration > 200000: return 0.5 elif iteration > 190000: return 0.5 elif iteration > 180000: return 0.4 elif iteration > 1...
def extract_nested_dict(dict, key_list): """ Given a list of kwargs, extracts the information requested from a nested dictionary """ x = dict if isinstance(key_list, str) or isinstance(key_list, tuple): x = x[key_list] elif isinstance(key_list, list): for k in key_list: ...
def disperse_and_redundancy_count(disperse, data, redundancy): """ Any two counts available out of three, return only normalized disperse and redundancy count. """ if data > 0 and redundancy > 0: return (data + redundancy, redundancy) if data > 0 and disperse > 0: return (disper...
def get_poi_by_type(poi_list, poi_type): """Find POI type""" if not poi_type: return True else: for i in range(len(poi_list)): for j in range(len(poi_type)): if poi_list[i] == poi_type[j]: return True return False
def get_hash_list(filename): """ read the hash list from file and load into a list """ hash_list = [] with open(filename, 'r') as hash_file: hash_list = hash_file.read().splitlines() return hash_list
def find_max_2(array: list) -> list: """ Best Case: Worst Case: O(n) :param array: list of integers :return: integer """ biggest = array[0] for i in array: if i > biggest: biggest = i return biggest
def check_format(cfg): """ We apply the following checks to configurations in dictionary format: - For fields ending in `_class`, map None to empty string. - If the `xyz_class` field is present, nesting has to happen and we add the `xyz` field and initialize it with an empty dictionary. - ...
def classname(ob): """Get the object's class's name as package.module.Class""" import inspect if inspect.isclass(ob): return '.'.join([ob.__module__, ob.__name__]) else: return '.'.join([ob.__class__.__module__, ob.__class__.__name__])
def create_table_if_not_exist(name: str, sql: str): """Creates tables if the don't exist in the database. Args: name (str): The name of the table. sql (str): The SQL string to define the tables columns. Returns: None """ return f"CREATE TABLE IF NOT EXISTS {name} {sql}"
def extract_identifiers(identifier_string): """ Parse database or Genprop identifiers from an EV or TG tag content string. :param identifier_string: The contents string from a EV or TG tag. :return: A list of identifiers. """ split_content = filter(None, identifier_string.split(';')) cleane...
def lgmres_params(inner_m=30, outer_k=3, maxiter=100, tol_coef=0.01): """ Bundles parameters for the LGMRES linear solver. These control the expense of finding the left and right environment Hamiltonians. PARAMETERS ---------- inner_m (int, 30): Number of gmres iterations per outer k loop. ...
def clean_list(lst): """ Returns a new but cleaned list. * None type values are removed * Empty string values are removed This function is designed so we only return useful data """ newlist = list(lst) for i in lst: if i is None: newlist.remove(i) if i == ""...
def is_singleline_comment_start(code, idx=0): """Position in string starts a one-line comment.""" return idx >= 0 and idx+2 <= len(code) and code[idx:idx+2] == '//'
def smashBase(x): """ Smash a base4 number to base2 x = a base4 encoded value """ if x > 0: x = 1 return x
def format_switch(switch): """ :param switch: A valid Switch returned from the db :return: A dictionary in the form of org.openkilda.messaging.info.event.SwitchInfoData """ return { 'clazz': 'org.openkilda.messaging.info.event.SwitchInfoData', 'switch_id': switch['name'], 'ad...
def validUTF8(data): """UTF-8 rules""" length = len(data) if length == 1: if data[0] < 128: return True else: return False checkahead = 0 for char in data: if char > 256: char -= 256 if checkahead > 0: if char < 128 or c...
def skip_i_delete_j(head, i, j): """ :param: head - head of linked list :param: i - first `i` nodes that are to be skipped :param: j - next `j` nodes that are to be deleted return - return the updated head of the linked list """ if i == 0: return None if head is None or j < 0 or...
def _hue2rgb(v1, v2, v_h): """Private helper function (Do not call directly). :param vH: rotation around the chromatic circle (between 0..1) """ while v_h < 0: v_h += 1 while v_h > 1: v_h -= 1 if 6 * v_h < 1: return v1 + (v2 - v1) * 6 * v_h if 2 * v_h < 1: ...
def get(method, start, end): """Return list of values generator by given method""" return [next(method) for i in range(end) if i >= start]
def schizophrenic(func): """ tag a function as schizophrenic so the metaclass knows when to effect the scope mangling. """ func.schizophrenic=True return func
def format_emote_list(emotelist): """Format emote json correctly.""" emotes = [] for emoteEntry in emotelist: emote = emoteEntry["code"].strip() emotes.append(emote) return emotes
def validate_float(value): """ Parses the given value whether it is float. If it is, returns it. Parameters ---------- value : `str` The value to validate. Returns ------- value : `None` or `float` """ if value.isnumeric(): return float(value)
def keep_cell(cell): """ Rule to decide whether to keep a cell or not. This is executed before converting the notebook back to a function """ cell_tags = set(cell['metadata'].get('tags', {})) # remove cell with this tag, they are not part of the function body tags_to_remove = { 'inj...
def repr_calling(args, kwargs): """ Reconstruct function calling code. """ li = [] li.extend(repr(a) for a in args) li.extend('%s=%r' % (k, v) for k, v in kwargs.items()) return ', '.join(li)
def translate_point(data, x0=0, y0=0, z0=0, scale=1): """ Translate a point [x, y, z] by some vector [x0, y0, z0], and simulataneously allow for conversion. Used in the NZ problem to convert the origin from some arbitrary value in UTM60S to [0, 0, 0], and also convert untits from m to km (171312...
def isNumber(x): """ Is the argument a python numeric type. """ return ( (type(x) == float) or (type(x) == int) )
def get_string_content(line): """ Get the quoted string content from a line. :param line: a string which contains a quoted substring :return: the string between the quotes """ first_index = line.find('\"') + 1 last_index = line.rfind('\"') content = line[first_index:last_index] conte...
def _compute_result_action(current_result, next_result, valid_actions): """ Compute the next result_action based on current one and the callback result """ current_status = current_result.get("status") next_status = next_result.get("status") # Check the validity of action per method if next_...
def is_number(arg: str) -> bool: """Check if a given string can be converted into a number. ```python x = fe.util.is_number("13.7") # True x = fe.util.is_number("ae13.7") # False ``` Args: arg: A potentially numeric input string. Returns: True iff `arg` represents a numb...
def is_iterable(obj): """Checks if an object is iterable. Parameters ---------- obj The object to check. ``obj`` is iterable if it can be used in the following expression:: for x in obj: pass Returns ------- :class:`bool` Whether ``obj``...
def reduce(function, array): """ Example: >>> from m2py import functional as f >>> >>> f.reduce(lambda a, b: a*b, [ 1, 2, 3, 4, 5]) 120 >>> >>> f.reduce(lambda a, b: a+b, [ 1, 2, 3, 4, 5, 6, 7, 8]) 36 >>> """ y = array[0] for i in range(len(array) - 1): #print(...
def permute(vect, start, end): """ compute all possible permutations of the set vect """ if start == end: return [tuple(vect)] else: perm = set([]) val = [] for i in range(start, end + 1): vect[start], vect[i] = vect[i], vect[start] val = permu...
def premium(q,mp): """ premium policy Args: q (numpy.float): Coverage amount p (float): Probability of the loss being incurred Returns: premium(function): What the agent pays the insurance company """ return mp['p']*q
def lstrip_string(s, prefix, ignore_case=False): """Remove leading string from s. Note: This is different than `s.lstrip('bar')` which would remove all leading 'a', 'b', and 'r' chars. """ if ignore_case: if s.lower().startswith(prefix.lower()): return s[len(prefix) :] else:...
def power_tail(x,y): """return x^y with tail recursion""" def power_tail_helper(x, y, accum): if(y==0): return accum return power_tail_helper(x, y-1, x*accum) return power_tail_helper(x, y, 1)
def calc_letterbox(width, height, fit_width, fit_height): """Return (x, y, width, height) to fit image into. Usage example: >>> calc_letterbox(4, 2, 2, 1) (0, 0, 2, 1) >>> calc_letterbox(2, 1, 4, 2) (1, 0, 2, 1) """ if width < fit_width and height < fit_height: s...
def get_gene_fam_columns(columns): """ return the ALLCAPS column names on the right """ gene_fam_cols = [] for c in reversed(columns): if c.upper() == c: gene_fam_cols.append(c) return gene_fam_cols
def single_site(x,Kd,A,B): """ First-order binding model model. """ return A + B*(x/(x + Kd))
def get_temp_dir(app_name): """Get the temporary directory for storing fab deploy artifacts. Args: app_name: a string representing the app name Returns: a string representing path to tmp dir """ return '/tmp/.fab-deploy-{}'.format(app_name)
def weasyl_sysname(target): """Return the Weasyl sysname for use in a URL for a given username.""" return ''.join(i for i in target if i.isalnum()).lower()
def get_tf_blocks(tf_weight_names): """Extract the block names from list of full weight names.""" # Example: 'efficientnet-b0/blocks_0/conv2d/kernel' -> 'blocks_0' tf_blocks = {x.split('/')[1] for x in tf_weight_names if 'block' in x} # sort by number tf_blocks = sorted(tf_blocks, key=lambda x: int(x.split('_...
def cpu(mean, sigma, USL): """Process capability index Cpu.""" return (USL - mean) / (3 * sigma)
def party_planner(cookies, people): """This function will calculate how many cookies each person will get in the party and also gives out leftovers ARGS: cookies: int, no of cookies is going to be baked people: int, no of people are attending this party_planner Returns: tuple of cookies per ...
def early_stopping(cost, opt_cost, threshold, patience, count): """ early stopping """ if opt_cost - cost <= threshold: count += 1 else: count = 0 if count >= patience: return True, count return False, count
def relative_difference(value_init, value_fit): """Calculate relative difference between two values. Parameter --------- value_init : float, reference value for error estimation value_fit : float, values to identify relative difference to Return ...
def is_collection(spocs): """ :param spocs: A list of spocs :return: True if the list of spocs is a sponsored collection; spocs that should be featured together. """ return all(spoc.get('collection_title') for spoc in spocs)
def convert_delay_number_to_delay_time(delay_num: int) -> float: """ Converts delay number into delay time for sleep function. """ return round((delay_num / 100) * (0.5 + delay_num/2), 2)
def bezier_cubic(p0, p1, p2, p3, t): """Returns a position on bezier curve defined by 4 points and t.""" return (1-t)**3*p0 + 3*(1-t)**2*t*p1 + 3*(1-t)*t**2*p2 + t**3*p3
def vis11(n): # DONE """ O O O OO O O OOO O OOOO Number of Os: 3 5 7""" result = 'O\n' * n result += 'O' * (n + 1) + '\n' return result
def remove_overlap(spans): """ remove overlapped spans greedily for flat-ner Args: spans: list of tuple (start, end), which means [start, end] is a ner-span Returns: spans without overlap """ output = [] occupied = set() for start, end in spans: if any(x for x in ...
def str_to_positive_float(text): """ Convert a string representation back to PositiveFloat. """ if text.strip(): val = float(text) if val >= 0.: return float(text) else: raise ValueError("Value should be positive.") else: return 0.0
def make_granular_marking(marking_defs, selectors): """ Makes a granular marking reference from STIX. This goes in the granular_markings list of an object example result: "granular_markings": [ { "marking_ref": "SOME UUID THAT IS VALID BUT NOT REALLY", "...
def role_dialogs(context, request, role=None, landingpage=False, delete_form=None): """ Modal dialogs for Role landing and detail page.""" return dict( role=role, landingpage=landingpage, delete_form=delete_form, )
def _peek_last(stack): """Returns the top element of stack or None""" return stack[-1] if stack else None
def _create_detected_instances_list(details): """ Generates report data for detected instances in list form with details """ result = [] for name, meta in details.items(): result.append(('Name: {name}\n' ' Instances: {instances}\n' ' Admin: {admin}\n' ...
def has_property(requirements, prop, rel_type): """Check if a requirement has the correct properties and type""" for requirement_dict in requirements: for requirement in requirement_dict.values(): if isinstance(requirement, str): return True relation = requirement...
def fib_ls(n): """ This return a list with n items. For example if n=5, this returns [0, 1, 1, 2, 3] and its length of the list is 5 """ fibo_ls = [0, 1] for _ in range(2, n): fibo_ls.append(fibo_ls[-1] + fibo_ls[-2]) return fibo_ls
def countSampleLeaves(node, samples): """Count the number of leaves descending from this node whose labels are in samples. Add the number as node['sampleCount'] and also return the list of samples found.""" samplesFound = set() if (node['kids']): for kid in node['kids']: samplesFound...
def strip_leading_zeros(version: str) -> str: """ Strips leading zeros from version number. This converts 1974.04.03 to 1974.4.3 as the format with leading month and day zeros is not accepted by PIP versioning. :param version: version number in CALVER format (potentially with leading 0s in date an...
def _between(string, start, end) -> str: """Returns what's between `start` and `end`, exclusive. Examples >>> _between("im a nice (person) to all", "(", ")") 'person' >>> _between("im a nice (person to all", "(", ")") Traceback (most recent call last): ... ValueError: substring not ...
def inverse_betweenness_index(n_nodes, n_times, index): """ find the triple associated to a point in the static graph. See betweenness_centrality. """ layer_index = index // (n_nodes * n_times) time_index = (index % (n_nodes * n_times)) // n_nodes node_index = (index % (n_nodes * n_times...
def _get_model_type(model_name): """ Returns the name of the model to which `model_name` belongs Parameters ---------- model_name : str name of the model Return ------ (str) : name of the folder to which this model belongs """ if "concat" in model_name: if "-pre...
def mirror_it_horizontal(x, side): """ Divide the matrix, depending upon the side (up or down), reverse the half which is has revealed squares and then merge the two halfs. """ dimension_y = len(x) half1 = [] half2 = [] for row in range(int(dimension_y/2)): half1.append(x[row]) ...
def quick_sort(_list): """ taking first element as pivot : by aman-goyal """ # Do nothing if list size if less than or equal to 1 if len(_list) <= 1: return _list pivot = _list[0] # Separating elements, left contains vlalue smaller than pivot # more - value more than...
def encode_db_connstr(name, # pylint: disable=too-many-arguments host='127.0.0.1', port=5432, user='postgres', password='password', scheme='postgresql'): """ builds a database connection string """ con...
def flatten(seq): """Given a nested datastructure, flatten it.""" lst = [] for el in seq: if type(el) in [list, tuple, set]: lst.extend(flatten(el)) else: lst.append(el) return lst
def get_by_name(yaml, ifname): """Return the tap by name, if it exists. Return None otherwise.""" try: if ifname in yaml["taps"]: return ifname, yaml["taps"][ifname] except KeyError: pass return None, None
def get_userlist_fields(fields): """ Returns the fields for `UserListSerializer`. """ fields = list(fields) fields.remove('is_superuser') fields = tuple(fields) return fields
def listify(obj): """Ensure that the object `obj` is of type list. If the object is not of type `list`, the object is converted into a list. Parameters ---------- obj : The object. Returns ------- list : The object inside a list. """ if obj is None: ...
def same_entries(a, b): """ checks if entries a and b represent the same publication """ for key in ['ID', 'doi', 'hal_id', 'title', 'chapter']: if key in a and key in b and a[key].lower() == b[key].lower(): return True if 'title' in a and 'chapter' in b and a['title'].lower() == b['chap...
def YNtoBool(str): """Convert Rinnai YN to Bool""" if str == "Y": return True else: return False
def remove_whitespace(string_to_parse): """remove spaces and tabs""" string_list = string_to_parse.split() return "".join(string_list)
def fastest_path(nums) : """ :param nums: :return: """ for i in range(1, len(nums)): len_i = len(nums[i]) for j in range(len_i): if j == 0 : nums[i][j] = nums[i - 1][j] + nums[i][j] elif j == len_i-1: nums[i][j] = nums[i - 1][j ...
def part1(input_data: str) -> int: """part1 solver take a str and return an int""" return sum(1 if char == '(' else -1 for char in input_data)
def frequency_dict_from_collection(collection): """ This is a useful function to convert a collection of items into a dictionary depicting the frequency of each of the items. :param collection: Takes a collection of items as input :return: dict """ assert len(collection) > 0, "Cannot perform the ope...
def partir_arreglo(arr, porc): """ Parte un arreglo en dos arreglos, retorna una tupla con dos arreglos repartidos segun el porcentaje indicado """ total1 = len(arr) * porc result1 = [] result2 = [] for i in range(0, len(arr)): if len(result1) < total1: result1.append(arr[i]...
def _parse_csv_row(row): """Parse the CSV row, returning variables and values. Parameters ---------- row : list of str A non-empty line from the CSV data file with starting and ending white space stripped out. Returns ------- str, list of str or None The variable na...
def nice_filename(org): """ Converts a string to a valid filename by removing any special characters :param org: the original string :return: a string usable as filename """ return "".join([c for c in org if c.isalpha() or c.isdigit() or c == ' ']).rstrip()
def span_exact_matching(gold_span, predicted_span): """Matching two spans Input: gold_span : a list of tuples :(DocID, list of tuples of token addresses) predicted_span : a list of tuples :(DocID, list of token indices) Returns: True if the spans match exactly """ gold_docI...
def get_readme_description(head_string: str) -> str: """ Parse the head of README and get description. :param head_string: A string containing title, description and images. :return: Stripped description string. """ # Split title section and rule out empty lines. parts = list(filter(bool, h...
def simple_test_keyword_in_text(text, keyword, ignore_case=True): """ Simple funtion for testing whether keyword exists in text. :param text: string to be tested on :param keyword: a single keyword interested in :param ignore_case: bool value indicates whether to ignore case for both text and k...
def get_extrusion_command(x: float, y: float, extrusion: float) -> str: """Format a gcode string from the X, Y coordinates and extrusion value. Args: x (float): X coordinate y (float): Y coordinate extrusion (float): Extrusion value Returns: str: Gcode line """ retu...
def harm_mu(mu, var): """ Recalculate mu to get the exponent for the harmonic mean in log-norm. Parameters ---------- mu : float Mean of the log-normal distribution. var : TYPE Variance of the log-normal distribution. Returns ------- float Recalculated mean....
def _bsj_junction_to_bed(info_str): """junction: chr|gene1_symbol:splice_position|gene2_symbol:splice_position|junction_type|strand junction types are reg (linear), rev (circle formed from 2 or more exons), or dup (circle formed from single exon) """ seq_name, gene_splice_1, gene_sp...
def split_passports_file(passports_file): """Split the passports_file in batches """ return passports_file.split('\n\n')
def pack(dict_of_list): """ Return dictionary of models with key is a tuple of (str, int) """ ret = {} for k in dict_of_list: for i, x in enumerate(dict_of_list[k]): ret[(k, i)] = x return ret