content
stringlengths
42
6.51k
def set_insertion_sieve(n): """Performing insertion over deletion""" factors = set() for i in range(2,int(n**0.5+1)): if i not in factors: factors |= set(range(i*i, n+1, i)) return set(range(2,n+1)) - factors
def query_string_to_kwargs(query_string: str) -> dict: """ Converts URL query string to keyword arguments. Args: query_string (str): URL query string Returns: dict: Generated keyword arguments """ key_value_pairs = query_string[1:].split("&") output = {} for key_value_pair in key_value_pairs: if "=" in key_value_pair: key, value = key_value_pair.split("=") if value == "None": value = None else: value = value.replace("+", " ") output[key] = value return output
def compute_ratio(hyp: str, ref: str) -> float: """ :param hyp: :param ref: :return: """ # naive tokenization hyp_len = len(hyp.split(" ")) ref_len = len(ref.split(" ")) return hyp_len / ref_len
def merge_runs_by_tag(runs, tags): """ Collect the (step, value) tuples corresponding to individual tags for all runs. Therefore the result might look like this: <tagA> + step: - <run-1-steps> - <run-2-steps> + value: - <run-1-values> - <run-2-values> ... Arguments: runs (dict): Collection of data from all runs. Usually the output of `visualization.helpers.load_run` tags (list): List of the tags to merge. Returns: data (dict): Dictionary containing the merged scalar data of all runs. The data.keys is composed of `tags`. """ _merged_runs = dict() # Merge the steps and values for each tag over all runs. for tag in tags: _run_values = [runs[run][tag]['value'] for run in runs] _run_steps = [runs[run][tag]['step'] for run in runs] _merged_runs[tag] = { 'step': _run_steps, 'value': _run_values } return _merged_runs
def calc_prior_probability(clazz, total_num_instances): """ Calculates the prior probability for clazz """ num_instances = len(clazz) prior_probability = (num_instances/total_num_instances) return prior_probability
def IsCloudPath(path): """Checks whether a given path is Cloud filesystem path.""" return path.startswith("gs://") or path.startswith("s3://")
def check_alleles(alleles, num_sites): """ Checks the specified allele list and returns a list of lists of alleles of length num_sites. If alleles is a 1D list of strings, assume that this list is used for each site and return num_sites copies of this list. Otherwise, raise a ValueError if alleles is not a list of length num_sites. """ if isinstance(alleles[0], str): return [alleles for _ in range(num_sites)] if len(alleles) != num_sites: raise ValueError("Malformed alleles list") return alleles
def value_from_char(character): """ Args: character (string): Takes an ASCII alphabet character and maps it 0-25, a-z. Returns: int: Numerical representation of the ASCII alphabet character inputted. """ return ord(character.lower()) - ord('a')
def ARGMAX(agg_column,out_column): """ Builtin arg maximum aggregator for groupby Example: Get the movie with maximum rating per user. >>> sf.groupby("user", ... {'best_movie':tc.aggregate.ARGMAX('rating','movie')}) """ return ("__builtin__argmax__",[agg_column,out_column])
def remove_any_pipe_values_from_topic_name(topic_name): """Removes any passed in piped values if they exist from the topic name. Keyword arguments: topic_name -- the topic name """ return topic_name.split("|")[0] if "|" in topic_name else topic_name
def calc_box_length(part_num, density, aspect_ratio): """ part_num, density, aspect_ratio = [x, y, z] -> x:y:z """ box_length = (float(part_num) / float(density) / (aspect_ratio[0] * aspect_ratio[1] * aspect_ratio[2]))**(1.0 / 3.0) return [box_length * aspect_ratio[0], box_length * aspect_ratio[1], box_length * aspect_ratio[2]]
def SIZE(expression): """ Counts and returns the total the number of items in an array. See https://docs.mongodb.com/manual/reference/operator/aggregation/size/ for more details :param expression: Any expression as long as it resolves to an array :return: Aggregation operator """ return {'$size': expression}
def _smallest_change(h, alpha): """Return smallest point not fixed by ``h`` else return None.""" for i in range(alpha, len(h)): if h[i] != i: return i
def path_nodes_to_edges(path): """ Returns an ordered list of edges given a list of nodes Args: path - a path, as a sequence of nodes Returns: An ordered list of edges. """ # Edge sequence initialization edge_sequence = [] for i in range(len(path) - 1): edge_sequence.append((path[i], path[i+1])) return edge_sequence
def solution(A): # O(N^2) """ Sort numbers in list A using bubble sort. >>> solution([5, 2, 2, 4, 1, 3, 7, 9]) [1, 2, 2, 3, 4, 5, 7, 9] >>> solution([2, 4, 6, 2, 0, 8]) [0, 2, 2, 4, 6, 8] >>> solution([1, 3, 5, 7, 3, 9, 1, 5]) [1, 1, 3, 3, 5, 5, 7, 9] """ length = len(A) # O(1) for i in range(0, length): # O(N) for j in range(0, length - i - 1): # O(N) if A[j] > A[j + 1]: # O(1) A[j], A[j + 1] = A[j + 1], A[j] # O(1) return A # O(1)
def format_domain_name(domain_name): """ :param domain_name: :return: """ format_domain_name = domain_name.split(",") return format_domain_name
def case_insensitive_equal(str1, str2): """ Compares two strings to determine if they are case-insensitively equal Args: str1 (str): str2 (str): Returns: bool: True if the strings are equal, ignoring case """ return str1.lower() == str2.lower()
def get_highest_action(life): """Returns highest action in the queue.""" if life['actions'] and life['actions'][0]: return life['actions'][0] else: return None
def _filter_scaling(reduction_indices, start_cell_num): """Compute the expected filter scaling at given PNASNet cell start_cell_num. In the pnasnet.py code, filter_scaling starts at 1.0. We instead adapt filter scaling to depend on the starting cell. At first cells, before any reduction, filter_scalling is 1.0. With passing any reduction cell, the filter_scaling is multiplied by 2. Args: reduction_indices: list of int indices. start_cell_num: int. Returns: filter_scaling: float. """ filter_scaling = 1.0 for ind in reduction_indices: if ind < start_cell_num: filter_scaling *= 2.0 return filter_scaling
def dict_to_conf_str(obj): """Dump dict as key=value to str object.""" config_list = [] for key in sorted(obj.keys()): value = obj[key] config_list.append("%s=%s" % (key, obj[key])) return '\n'.join(config_list)
def minNumberOfCoinsForChange(n, denoms): """ nc = number_coins nc[i=amount] = { min (nc[amount-coin] + 1 coin, nc[amount]) for i > 0, 0, for i = 0 """ number_coins = [float('inf')] * (n + 1) number_coins[0] = 0 for coin in denoms: # Since coin is always less than or equal to amount at the start # We don't need to compare each time within the loop amount = coin while amount < len(number_coins): # To compute the min number of coins to change at each amount number_coins[amount] = min(number_coins[amount-coin] + 1, number_coins[amount]) amount += 1 print("The minimum number of coins to change {} from {} = {}" .format(n, denoms, number_coins[n])) # Returns the min number of coins to change; Otherwise, return -1 # when not found. return number_coins[n] if number_coins[n] != float('inf') else -1
def cleanopts(optsin): """Takes a multidict from a flask form, returns cleaned dict of options""" opts = {} d = optsin for key in d: opts[key] = optsin[key].lower().replace(" ", "_") return opts
def reinterpret_latin1_as_utf8(wrongtext): """ :see:recode_unicode """ newbytes = wrongtext.encode('latin-1', 'replace') return newbytes.decode('utf-8', 'replace')
def parse_split_conf(conf): """ Function parse comma separated values from config """ result = [] if len(conf.strip()): conf = conf.split(',') for item in conf: index = conf.index(item) conf[index] = item result = list(map(str.strip, conf)) return result
def resample(X, n=None): """ Bootstrap resample an array_like Parameters :param X: array_like data to resample :param n: int, optional length of resampled array, equal to len(X) if n==None Results """ from random import sample, uniform if n == None: n = int(uniform(1,len(X))) X_resample = sample(X, n) return X_resample
def GetSvnBranchName(url, postfix_branch, logger): """ get svn branch name using it's url Args : url : svn url of module postfix_branch : postfix of branch logger : the object of Log.Log Returns : return svn branch name of module, if enconters some errors return None """ if url.endswith(postfix_branch): br_name = url.split('/')[-1] return br_name elif url.find('trunk') != -1: return "trunk" else: logger.LevPrint('ERROR', 'Unknow name of branch!!Check the url %s' % (url), False) return None
def rgb_to_hex(rgb): """ [255,255,255] -> "#FFFFFF" """ # Components need to be integers for hex to make sense rgb = [int(x) for x in rgb] hex_rgb = "".join([f"0{v:x}" if v < 16 else f"{v:x}" for v in rgb]) return f"#{hex_rgb}"
def str_to_seconds(tstring): """ Convert time strings to seconds. Strings can be of the form: <int> (ninutes) <int>m (minutes) <int>h (hours) <int>d (days) <int>y (years) Args: tstring (str): An integer followed by an (optional) 'm', 'h', 'd', 'y'. Returns int: The number of seconds represented by the input string. If the string is unadorned and represents a negative number, -1 is returned. Raises: ValueError: If the value cannot be converted to seconds. """ if tstring.endswith('m'): secs = 60 * int(tstring.replace('m', '')) elif tstring.endswith('h'): secs = 60 * 60 * int(tstring.replace('h', '')) elif tstring.endswith('d'): secs = 24 * 60 * 60 * int(tstring.replace('d', '')) elif tstring.endswith('y'): secs = 365 * 24 * 60 * 60 * int(tstring.replace('y', '')) else: secs = 60 * int(tstring) if secs < 0: secs = -1 return secs
def test_tiff(h, f): """TIFF (can be in Motorola or Intel byte order)""" if h[:2] in (b'MM', b'II'): return 'tiff'
def remove_list_indices(a_list, del_indices, opposite = True): """ ================================================================================================= remove_list_indices(a_list, del_indices, opposite) This function is meant to remove elements from a list, based on the deletion indices and the value of opposite. ================================================================================================= Arguments: a_list -> A list del_indices -> A list of integers that define either which indices to delete, or which to keep opposite -> A boolean, determines whether to delete all other indices or all indices in del_indices ================================================================================================= Returns: A list filtered by the commands specified above ================================================================================================= Example: a = [1,2,3,4] del_indices = [0,2] print(remove_list_indices(a,del_indices)) -> [2,4] print(remove_list_indices(a,del_indices, opposite = False)) -> [1,3] ================================================================================================= """ # Make sure the user inputs the proper typed objects. # Opposite must be a boolean assert opposite in [True, False], "opposite argument must be a boolean" # del_indices must be an iterable, specifically a list/tuple assert type(del_indices) in [list, tuple], "Deletion indices should be given as a list or tuple of integers" # All of the values in del_indices must be integers assert all([type(ind) == int for ind in del_indices]), "Deletion indices should be given as a list or tuple of integers" # a_list must be an interable, specifically a list/tuple assert type(a_list) in [list, tuple], "The argument 'a_list' should be a list or a tuple." # The a_list must include all indices required for deletion. assert sorted(del_indices)[-1] <= len(a_list), "The deletion indices given expand beyond the size of the list." # If the argument opposite is True if opposite: # Then return a list where all elements NOT IN del_indices are kept return [a_list[i] for i in range(len(a_list)) if i not in del_indices] # If the argument opposite is False else: # Then return a list where all elements IN del_indices are kept return [a_list[i] for i in range(len(a_list)) if i in del_indices]
def _get_permission_filters(permission_ids): """Helper function to filter permissions.""" if permission_ids == 'all': return {} else: return {'id': permission_ids}
def list_sum(num_list): """Returns the sum of all of the numbers in the list""" if len(num_list) == 1: return num_list[0] else: return num_list[0] + list_sum(num_list[1:])
def rescale(n, after=[0,1], before=[]): """ Helper function to rescale a vector between specified range of values :param numpy array n: a vector of numbers to be rescale :param list after: range of values to which to scale n :param list before: range of values in which n is contained """ if not before: before=[min(n), max(n)] if (before[1] - before[0]) == 0: return n return (((after[1] - after[0]) * (n - before[0]) / (before[1] - before[0])) + after[0])
def build_mpi_call_str(task_specs,common_options,format_opts=None,runner='mpiexec'): """Summary Args: task_specs (list): List of strings, each containing an MPI task description, eg e.g: ['-n {nrunners} python3 awrams.module.example {pickle_file}'] common_options (list): List of MPI options that are expanded to for all tasks format_opts (dict, optional): Dictionary for formatting options within task_specs runner (str, optional): Name of MPI executable Returns: str: Full runnable MPI call string """ if format_opts is None: format_opts = {} call_str = runner + ' ' for t_str in task_specs: call_str = call_str + ''.join([o + ' ' for o in common_options]) + t_str + ' : ' return call_str.format(**format_opts)
def get_hyperhdr_device_id(server_id: str, instance: int) -> str: """Get an id for a HyperHDR device/instance.""" return f"{server_id}_{instance}"
def AVL(game_board, rebalance): """Addional game rules when the DS is AVL.""" # Check if the graph is in rebalance state if rebalance and (game_board['graph']['balanced']): return {'cheat': True, 'reason': str('Tree is already balanced!')} # Check if user is attempting to do an action while tree is not balanced if not rebalance and (not game_board['graph']['balanced']): return {'cheat': True, 'reason': str('You must balance the tree first!')} # No cheat detected return {'cheat': False}
def decode_uint48(bb): """ Decode 6 bytes as an unsigned 48 bit integer Specs: * **uint48 len**: 6 bytes * **Format string**: 'J' """ return int.from_bytes(bb, byteorder='little', signed=False)
def correct_name_servers(logger, result, zone): """ This is to deal with issues in the whois library where the response is a string instead of an array. Known variants include: - "Hostname: dns-1.example.org\nHostname: dns-2.example.org\nHostname..." - "No nameserver" - "dns-1.example.org 1.2.3.4" - "Organization_Name The problem with inconsistent types is that it makes database queries harder downstream. """ if result['name_servers'].startswith("Hostname"): new_list = [] parts = result['name_servers'].split("\n") for part in parts: if part.startswith("Hostname"): sub_parts = part.split() new_list.append(sub_parts[1]) return(new_list) elif result['name_servers'] == "No nameserver": return([]) elif "." in result['name_servers']: if " " in result['name_servers']: new_list = [] temp = result['name_servers'].split() new_list.append(temp[0]) return(new_list) else: new_list = [] new_list.append(result['name_servers']) return(new_list) else: logger.warning("ERROR: " + zone + " had an unexpected name_servers response of " + result["name_servers"]) return([])
def monophonic(plain_txt: str, all_letters: list, shifted_letters: dict): """ enciphers a line of plaintext with monophonic shift (rot-key) cipher i.e. number of unique chars across plaintext and ciphertext remains conserved """ cipher_txt = [] for char in plain_txt: if char in all_letters: temp = shifted_letters[char] cipher_txt.append(temp) else: temp = char cipher_txt.append(temp) cipher_txt = "".join(cipher_txt) return cipher_txt
def is_node_active_at_timestamp(node, ts): """Check if a node is active at a given timestamp""" return node.get("from", 0) <= ts <= node.get("to", float("inf"))
def _all_same(all_gen): """ helper function to test if things are all the same """ if len(all_gen) == 1: return True for gen in all_gen[1:]: if gen != all_gen[0]: return False # I don't want to use 'set' because thing might not be hashable return True
def is_float(value: str) -> bool: """ Check value for float """ try: float(value) except (ValueError, TypeError): return False return True
def get_mail_domain_list(domain): """ Get an array of domains that should be covered for a given primary domain that uses email. Args: domain - The primary domain to use to create the list of domains/subdomains """ return [domain, 'www.' + domain, 'mail.' + domain, 'webmail.' + domain]
def _f_to_c(f): """ Converts temperature in Fahrenheit to Celsius Args: f (real) -- Fahrenheit Returns: real -- Celsius """ return (f-32)*5.0/9.0
def tlvs_by_subtype(tlvs, subtype): """Return list of TLVs with matching type.""" return [tlv for tlv in tlvs if tlv.subtype == subtype]
def year_cycle(year=0): """Year cycle. Parameters ---------- year : int, optional (dummy value). Returns ------- out : dict integer (1) as key, 'Year' as value. Notes ----- Appropriate for use as 'year_cycles' function in :class:`Calendar`, this allows to essentially have a direct division of the years in days, without months, weeks or other subdivisions. For example, see built-in calendar :data:`Cal365NoMonths`. """ return {1: 'Year'}
def create_permutation_list(length): """ Create a list of each permutation of length 'length'. """ numbers = range(1,length+1) permutations_dict = {} for number in numbers: permutations_dict[number] = (len(numbers) - 1) * [number] #For each number, reserve a list that starts with that number return permutations_dict
def atoi(s): """ Convert s to an integer. """ # determine sign sgn = 1 if s[0] == '-': sgn = -1 s = s[1:] # accumulate digits i = 0 for d in s: x = ord(d) - ord('0') if x < 0 or x > 9: raise ValueError('bad digit') i = 10*i + x return sgn*i
def reduceVtype(vtypeDict, taxis, period): """Reduces the vtypeDict to the relevant information.""" newVtypeDict = {} for t in vtypeDict: if t in taxis: newVtypeDict[t] = [] index = 0 for e in vtypeDict[t]: if index % period == 0: newVtypeDict[t].append(e) index = index + 1 return newVtypeDict
def _check_vdj_len(nt_seq): """ Verifies the length of a VDJ nucleotide sequence mod 3 equals 1 (The constant region continues the reading frame) """ if len(nt_seq) % 3 == 1: return True else: return False
def convert_pascal_bbox_to_coco(xmin, ymin, xmax, ymax): """ pascal: top-left-x, top-left-y, x-bottom-right, y-bottom-right coco: top-left-x, top-left-y, width and height """ return [xmin, ymin, xmax - xmin, ymax - ymin]
def schema_choices_helper(field): """ Test custom choices helper """ return [ { "value": "friendly", "label": "Often friendly" }, { "value": "jealous", "label": "Jealous of others" }, { "value": "spits", "label": "Tends to spit" } ]
def find_if_prime_num(check_prime): """ This function checks if any of the numbers represented are prime or not input: (list) check_prime output: (list) is_prime_number """ is_prime_number = [] for num in check_prime: # search for factors, iterating through numbers ranging from 2 to the number itself for i in range(2, num): # print(i) # number is not prime if modulo is 0 if (num % i) == 0: # print("{} is NOT a prime number, because {} is a factor of {}".format(num, i, num)) is_prime_number.append(False) break # otherwise keep checking until we've searched all possible factors, and then declare it prime if i == num - 1: is_prime_number.append(True) # print("{} IS a prime number".format(num) return is_prime_number
def marioAlgorithm(total_coins_inserted, coins_in_machine_dict): """ marioAlgorithm(total_coins, coins_dict) --> minimum coins for change """ min_coins_dispensed = [] partial_sum = 0 full_sum = 0 # Sorts the coins based on money value in descending order sorted_coins_in_machine = sorted(coins_in_machine_dict.items(), key = lambda coin: int(coin[0].strip('p')), reverse = True) for coin_type, quantity in sorted_coins_in_machine: coin_type = int(coin_type.strip('p')) coins_fit = 0 while True: coins_fit += 1 partial_sum = coin_type*coins_fit if(partial_sum + full_sum > total_coins_inserted or coins_fit > quantity): coins_fit -= 1 max_partial_sum = coin_type*coins_fit full_sum += max_partial_sum min_coins_dispensed.append((str(coin_type) + 'p', coins_fit)) break if(full_sum == total_coins_inserted): return dict(min_coins_dispensed) if(full_sum < total_coins_inserted): print("\nNOT ENOUGH RAGE--NEED MORE RAGE.\n" "To be precise, V\u00B2 needs {}p more worth of coins internally." "\nTherefore, your transaction with V\u00B2 has been " "discontinued.\n".format(total_coins_inserted - full_sum))
def get_chasm_context(tri_nuc): """Returns the mutation context acording to CHASM. For more information about CHASM's mutation context, look at http://wiki.chasmsoftware.org/index.php/CHASM_Overview. Essentially CHASM uses a few specified di-nucleotide contexts followed by single nucleotide context. Parameters ---------- tri_nuc : str three nucleotide string with mutated base in the middle. Returns ------- chasm context : str a string representing the context used in CHASM """ # check if string is correct length if len(tri_nuc) != 3: raise ValueError('Chasm context requires a three nucleotide string ' '(Provided: "{0}")'.format(tri_nuc)) # try dinuc context if found if tri_nuc[1:] == 'CG': return 'C*pG' elif tri_nuc[:2] == 'CG': return 'CpG*' elif tri_nuc[:2] == 'TC': return 'TpC*' elif tri_nuc[1:] == 'GA': return 'G*pA' else: # just return single nuc context return tri_nuc[1]
def euclideanGCD( a, b ): """Calculates the Greatest Common Denominator of two integers using the Euclidean algorithm. Arguments should be integers. Returns GCD(a,b) Note: This function will likely hit the recursion limit for big numbers. """ return abs(a) if ( b == 0 ) else euclideanGCD( b, a%b )
def tiers_for_dev(dev): """ Returns a tuple of tiers for a given device in ascending order by length. :returns: tuple of tiers """ t1 = dev['region'] t2 = dev['zone'] t3 = dev['ip'] t4 = dev['id'] return ((t1,), (t1, t2), (t1, t2, t3), (t1, t2, t3, t4))
def _is_power_of_two(number): """Checks whether a number is power of 2. If a number is power of 2, all the digits of its binary are zero except for the leading digit. For example: 1 -> 1 2 -> 10 4 -> 100 8 -> 1000 16 -> 10000 All the digits after the leading digit are zero after subtracting 1 from number. For example: 0 -> 0 1 -> 1 3 -> 11 7 -> 111 15 -> 1111 Therefore, given a non-zero number, (number & (number - 1)) is zero if number is power of 2. Args: number: Integer. Returns: Boolean. """ return number and not number & (number - 1)
def _group_name_from_id(project, group_id): """Build the group name given the project and group ID. :type project: string :param project: The project associated with the group. :type group_id: string :param group_id: The group ID. :rtype: string :returns: The fully qualified name of the group. """ return 'projects/{project}/groups/{group_id}'.format( project=project, group_id=group_id)
def impedance(vp, rho): """ Given Vp and rho, compute impedance. Convert units if necessary. Test this module with: python -m doctest -v impedance.py Args: vp (float): P-wave velocity. rho (float): bulk density. Returns: float. The impedance. Examples: >>> impedance(2100, 2350) 4935000 >>> impedance(2.1, 2.35) 4935000.0 >>> impedance(-2000, 2000) Traceback (most recent call last): ... ValueError: vp and rho must be positive """ if vp < 10: vp = vp * 1000 if rho < 10: rho = rho * 1000 if not vp * rho >= 0: raise ValueError("vp and rho must be positive") return vp * rho
def form_name_entries_special(pos, provenance, pw_id, pw_entry, kb_id, kb_entry): """ Create name match entries :param pos: :param pw_id: :param pw_entry: :param kb_id: :param kb_entry: :return: """ entries = [] for pw_name in set(pw_entry['aliases']): entries.append({ 'label': pos, 'provenance': provenance, 'pw_id': pw_id, 'pw_cls': pw_name, 'kb_id': kb_id, 'kb_cls': kb_entry[0] }) return entries
def _wrap(text, width): """Break text into lines of specific width.""" lines = [] pos = 0 while pos < len(text): lines.append(text[pos:pos + width]) pos += width return lines
def get_index_of_smallest(L, i): """Return the index of the smallest element of L. Args: L (list): List we want to analyse. i (int): Index from where we want to start. Returns: int: Index of smallest element of L. """ # The index of the smallest item so far index_of_smallest = i end = len(L) for j in range(i + 1, end): if L[j] < L[index_of_smallest]: index_of_smallest = j return index_of_smallest
def process_text(text): """ process text to remove symbols - remove tags: {spk}, {noise}, {click}, {beep}, <caller>, </caller>, <recipient>, </recipient> - invalid if contains: <bmusic>, <bnoise>, <bspeech>, <foreign>, [utx], +WORD, WOR-, -ORD, ~ WORD, (()), ((Word Word)) - conversion: %ah, %um, %hmm -> ah, um, hmm """ # return empty string if invalid tags present invalid_tags = ['<bmusic>', '<bnoise>', '<bspeech>', '<foreign>', '<nospeech>', '</error>', '[utx]', ' +', '- ', ' -', ' ~ ', '((', '))'] for tag in invalid_tags: if tag in text: return '' text2 = text[:] # remove removable tags remove_tags = ['{spk}', '{noise}', '{click}', '{beep}', '<caller>', '</caller>', '<recipient>', '</recipient>'] for tag in remove_tags: text2 = text2.replace(tag, '') # convert tags by removing '%' in the front convert_tags = ['%ah', '%um', '%hmm'] for tag in convert_tags: if tag in text2: text2 = text2.replace(tag, tag[1:]) # remove redundant spaces text2 = ' '.join(text2.strip().split()) # sanity check (should not contain following symbols) symbols = ['{', '}', '[', ']', '<', '>', '(', ')', '~', '/', '%'] for symbol in symbols: if symbol in text2: raise Exception('{} in {}'.format(symbol, text2)) return text2
def cvsecs(*args): """ converts a time to second. Either cvsecs(min, secs) or cvsecs(hours, mins, secs). """ if len(args) == 1: return args[0] elif len(args) == 2: return 60*args[0] + args[1] elif len(args) == 3: return 3600*args[0] + 60*args[1] + args[2]
def port_status_change(port, original): """port_status_change Checks whether a port update is being called for a port status change event. Port activation events are triggered by our own action: if the only change in the port dictionary is activation state, we don't want to do any processing. """ # Be defensive here: if Neutron is going to use these port dicts later we # don't want to have taken away data they want. Take copies. port = port.copy() original = original.copy() port.pop('status') original.pop('status') if port == original: return True else: return False
def nobrackets(v): """ Remove brackets """ return v.replace('[', '').replace(']', '')
def to_bool(bool_str): """Parse the string and return the boolean encoded or raise exception.""" if bool_str.lower() in ['true', 't', '1']: return True elif bool_str.lower() in ['false', 'f', '0']: return False else: return bool_str
def hard_limit(val, limits): """ Check if a value is outside specified limits :param val: value to be tested :param limits: two membered list of lower and upper limit :type val: float :type limits: list of floats :return: 1 if the input is outside the limits, 0 otherwise :return type: integer """ assert limits[1] > limits[0], 'limits are not well specified' if val is None: return 1 result = 1 if limits[0] <= val <= limits[1]: result = 0 return result
def some(seq): """Return some element of seq that is true.""" for e in seq: if e: return e return False
def add_saved_artists(auths, artists): """ Adds/follows artists. :param auths: dict() being the 'destinations'-tree of the auth object as returned from authorize() :param artists: list() containing the artists IDs to add to the 'destinations' accounts :return: True """ for username in auths: for artist in artists: if artist is not None: auths[username].user_follow_artists([artist]) return True
def sequences_overlap(true_seq, pred_seq): """ Boolean return value indicates whether or not seqs overlap """ start_contained = (pred_seq['start'] < true_seq['end'] and pred_seq['start'] >= true_seq['start']) end_contained = (pred_seq['end'] > true_seq['start'] and pred_seq['end'] <= true_seq['end']) return start_contained or end_contained
def search(keyword_to_queries: dict, keywords: list) -> list: """ Looks up the list of queries that satisfy a keyword. :param keyword_to_queries: a mapping of keywords to query indices :param keywords: a list of keywords to lookup :return: a list of query indices """ query_count = dict() for keyword in keywords: query_indices = keyword_to_queries.get(keyword, {}) for i, weight in query_indices.items(): query_count.setdefault(i, 0) query_count[i] += weight best_matches = list( dict(sorted(query_count.items(), key=lambda item: item[1], reverse=True)).keys()) return best_matches
def get_supported_extensions(): """ Returns a list of supported image extensions. """ return ('jpeg', 'jpg', 'png')
def cli_table(table, spl = " ", fill = " ", align = "left"): """ Args: table (List[List[str]]): input data spl (str): splitting string of columns fill (str): string of 1 byte, used to fill the space align (str): left and right is available """ len_row = len(table) len_column = len(table[0]) col_max = [0] * len_column for row in table: for cid, val in enumerate(row): if cid >= len_column: raise ValueError val = str(val) if len(val) > col_max[cid]: col_max[cid] = len(val) l_buf = [] for row in table: line = [] for cid, val in enumerate(row): cell = str(val) len_cell = col_max[cid] len_space = len_cell - len(cell) if align == "left": cell = cell + fill * len_space elif align == "right": cell = fill * len_space + cell else: raise NotImplementedError line.append(cell) l_buf.append(spl.join(line)) return "\n".join(l_buf)
def average(x): """This function calculates the average of a list of provided values. :param x: A list of values to be averaged. :type x: List of Integers :return: The average of the provided list. """ return sum(x) * 1.0 / len(x)
def get_unique_el_mapping(data_list): """Map each unique element in the data list to a number/index. """ key2idx = {el: idx for idx, el in enumerate(set(data_list))} idx2key = {v: k for k, v in key2idx.items()} for idx in idx2key.keys(): assert isinstance(idx, int) return key2idx, idx2key
def make_round_pairs(sequence): """ Given a sequence [A, B, C] of size n, creates a new sequence of the same size where each new item is the pair of the item at a given position paired up with next item. Additionally, last item is paired with the first one: [(A, B), (B, C), (C, A)]. :param sequence: original sequence :return: paired sequence """ length = len(sequence) return [ (sequence[i], sequence[(i + 1) % length]) for i in range(length) ]
def subarray(a: list, b: list) -> int: """ Time Complexity: O(n) """ l: int = len(a) hash_table: dict = {a[0] - b[0]: 0} length: int = 0 for i in range(1, l): a[i] += a[i - 1] b[i] += b[i - 1] diff = a[i] - b[i] if diff == 0: length = i + 1 elif diff in hash_table: length = max(length, i - hash_table[diff]) else: hash_table[diff] = i return length
def get_operand_string(mean, std_dev): """ Method to get operand string for Fsl Maths Parameters ---------- mean : string path to img containing mean std_dev : string path to img containing standard deviation Returns ------ op_string : string operand string """ str1 = "-sub %f -div %f" % (float(mean), float(std_dev)) op_string = str1 + " -mas %s" return op_string
def pv(flow, n, spot): """PV of cash flow after compounding spot rate over n periods""" return flow / ((1 + spot) ** n)
def runge_kutta4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. Parameters ---------- y : scalar Initial/current value for y x : scalar Initial/current value for x dx : scalar difference in x (e.g. the time step) f : ufunc(y,x) Callable function (y, x) that you supply to compute dy/dx for the specified values. """ k1 = dx * f(y, x) k2 = dx * f(y + 0.5*k1, x + 0.5*dx) k3 = dx * f(y + 0.5*k2, x + 0.5*dx) k4 = dx * f(y + k3, x + dx) return y + (k1 + 2*k2 + 2*k3 + k4) / 6.
def heronStep(y, x): """Perform one step of Heron's method for sqrt(y) with guess x.""" return 0.5*(x + y/x)
def point_is_under_triangle(x, y, p0, p1, p2): """Determine whether the vertical line through (x, y, 0) intersects the triangle (p0, p1, p2).""" dX = x - p2[0] dY = y - p2[1] dX21 = p2[0] - p1[0] dY12 = p1[1] - p2[1] # The Barycentric coordinates of (x, y) wrt the triangle. s = dY12 * dX + dX21 * dY t = (p2[1] - p0[1]) * dX + (p0[0] - p2[0]) * dY D = dY12 * (p0[0] - p2[0]) + dX21 * (p0[1] - p2[1]) if D < 0: return s <= 0 and t <= 0 and s + t >= D return s >= 0 and t >= 0 and s + t <= D
def find_namespace_vars_usages(analysis, namespace_usage): """ Returns usages of Vars from namespace_usage. It's useful when you want to see Vars (from namespace_usage) being used in your namespace. """ usages = [] for var_qualified_name, var_usages in analysis.get("vindex_usages", {}).items(): namespace, _ = var_qualified_name if namespace == namespace_usage.get("to"): usages.extend(var_usages) return usages
def add_critical_points(points: dict, coord: tuple, ax, stableonly: bool = False): """ Add the critical points to a graph Parameters ---------- points : dict keys are (s,h,z) coordinates, contains information on points coord : tuple tuple of which coordinates e.g. ('s','z') ax : matplotlib axes object axes to plot on stableonly : bool if only stable points should be plotted Returns ------- ax : matplotlib axes object """ loc = dict(s=0, h=1, z=2) for x, info in points.items(): xs = [x[loc[i]] for i in coord] c = {'stable': 'green', 'unstable': 'red'}[info['stability']] shape = {'node': '^', 'focus': 's', 'saddle': 'o'}[info['type']] label = info['stability'] + ' ' + info['type'] ax.scatter(*xs, c=c, marker=shape, s=15, label=label, zorder=2) return ax
def Union(List1,List2): """Returns union of two lists""" #----------------------------- # Copy List 1 Into Return List #----------------------------- # Put a copy of List 1 into ReturnList. This gives us the base list to # compare against. ReturnList = List1[:] #--------------------------- # For Each Element In List 2 #--------------------------- for Element in List2: #----------------------------------------- # Append Element To Return List If Missing #----------------------------------------- # If Element isn't in the return list, append it. if not Element in ReturnList: ReturnList.append(Element) #----------------- # Return To Caller #----------------- # The return list now contains a union of list 1 and list 2. return ReturnList
def kernel_mu(n_kernels, manual=False): """ get mu for each guassian kernel, Mu is the middele of each bin :param n_kernels: number of kernels( including exact match). first one is the exact match :return: mus, a list of mu """ mus = [1] # exact match if n_kernels == 1: return mus bin_step = (1 - (-1)) / (n_kernels - 1) # score from [-1, 1] mus.append(1 - bin_step / 2) # the margain mu value for k in range(1, n_kernels - 1): mus.append(mus[k] - bin_step) if manual: return [1, 0.95, 0.90, 0.85, 0.8, 0.6, 0.4, 0.2, 0, -0.2, -0.4, -0.6, -0.80, -0.85, -0.90, -0.95] else: return mus
def SquishHash(s): """ SquishHash() is derived from the hashpjw() function by Peter J. Weinberger of AT&T Bell Labs. https://en.wikipedia.org/wiki/PJW_hash_function """ h = 0 for f in s: h = (h << 4) + ord(f.lower()) g = h & 0xf0000000 if g != 0: h |= g >> 24 h |= g return h & 0x7fffffff
def stripnl(string): """Strip the final newline from <string>. It is an error if <string> does not end with a newline character, except for the empty string, which is okay. >>> stripnl('') '' >>> stripnl('he\\nllo\\n') 'he\\nllo' >>> try: ... stripnl('hello') ... except RuntimeError as e: ... e.message "string doesn't end in newline: hello" """ if string == '': return string elif string.endswith('\n'): return string[0:-1] else: raise RuntimeError("string doesn't end in newline: %s" % string)
def listify(item, delimiter=","): """Used for taking character (usually comma)-separated string lists and returning an actual list, or the empty list. Useful for environment parsing. Sure, you could pass it integer zero and get [] back. Don't. """ if not item: return [] if type(item) is str: item = item.split(delimiter) if type(item) is not list: raise TypeError("'listify' must take None, str, or list!") return item
def _get_charset(message): """Return charset, given a http.client.HTTPMessage""" if not message["content-type"] or not "charset=" in message["content-type"]: # utter guesswork return "utf-8" charset = message["content-type"].split("charset=")[1] return charset.split(";")[0]
def replace_it_in_list(original: list): """ This function replace all the 'it' to 'something' because 'it' is to general in knowledge. :param original: A list of strings to be replaced. :return: A list of strings after the replacement. """ result = [] for i in original: word = i.split(' ') result.append(" ".join(['something' if (w == 'it' or w == 'It') else w for w in word])) return result
def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0
def _linear_annealing(init, fin, step, annealing_steps): """Linear annealing of a parameter. Linearly increase parameter from value 'init' to 'fin' over number of iterations specified by 'annealing_steps'""" if annealing_steps == 0: return fin assert fin > init, 'Final value should be larger than initial' delta = fin - init annealed = min(init + delta * step / annealing_steps, fin) return annealed
def get_field(key_value_pair_list, key): """ Given a list of key-value pairs (dicts with keys 'key' and 'value'), find the entry that has the provided `key` and return its value. If no `key` is found, return None. It assumes that each `key` only appears one in `key_value_pair_list`, so the first appearance is returned. """ entry = list(filter(lambda d: d['key'] == key, key_value_pair_list)) if len(entry) == 0: return None return entry[0]['value']
def get_squares(num): """ Get the first n triangular numbers. """ return [int(i ** 2) for i in range(1, num + 1)]
def get_media_id_from_url(anilist_url): """ get media id from url used to strip an anilist url for the media id specifically """ # initialize media id based off url media_id = 0 if 'anilist' in anilist_url: try: media_id = int(anilist_url.split('anilist')[-1].split('/')[2]) except ValueError: return False else: return False return media_id
def hk_aocs_modes(bits: list) -> bytes: """ First bit should be on the left, bitfield is read from left to right """ enabled_bits = 0 bits.reverse() for i in range(len(bits)): enabled_bits |= bits[i] << i return enabled_bits.to_bytes(1, byteorder='big')
def get_best_v_for_gnh_tb(sorted_degrees, sorted_nen_counts): """ """ sub_list = [sorted_nen_counts[0][0]] min_count = sorted_nen_counts[0][1] for (v, count) in sorted_nen_counts[1:]: if count != min_count: break sub_list.append(v) for v, deg in sorted_degrees: if v in sub_list: sorted_degrees.remove((v,deg)) sorted_nen_counts.remove((v,min_count)) return v, sorted_degrees, sorted_nen_counts