content
stringlengths
42
6.51k
def pad_sequence_to_length(sequence, desired_length, default_value = lambda: 0, padding_on_right = True): """ Take a list of objects and pads it to the desired length, returning the padded list. The original list is not modified. Parameters ---------- sequence : List A list of objects to be padded. desired_length : int Maximum length of each sequence. Longer sequences are truncated to this length, and shorter ones are padded to it. default_value: Callable, default=lambda: 0 Callable that outputs a default value (of any type) to use as padding values. This is a lambda to avoid using the same object when the default value is more complex, like a list. padding_on_right : bool, default=True When we add padding tokens (or truncate the sequence), should we do it on the right or the left? Returns ------- padded_sequence : List """ # Truncates the sequence to the desired length. if padding_on_right: padded_sequence = sequence[:desired_length] else: padded_sequence = sequence[-desired_length:] # Continues to pad with default_value() until we reach the desired length. for _ in range(desired_length - len(padded_sequence)): if padding_on_right: padded_sequence.append(default_value()) else: padded_sequence.insert(0, default_value()) return padded_sequence
def normalizador(matriz: list) -> list: """Normaliza os valores da matriz passada.""" matriz_normalizada = [] maximizante_da_matriz = matriz[-1] for linha in matriz: nova_coluna = [] for i, coluna in enumerate(linha): nova_coluna.append(coluna / maximizante_da_matriz[i]) matriz_normalizada.append(nova_coluna) return matriz_normalizada
def _company_total_debt(column): """ Uses balance sheet to get company total debt rate """ long_term_debt = column["Long-term debt"] short_long_debt = column["Short-term debt"] return long_term_debt + short_long_debt
def bottom_up_fib(n): """Compute the nth fibonaci number; bottom-up dynamic programming approach""" memo = {} for k in range(1, n+1): if k <= 2: f = 1 else: f = memo[k-1] + memo[k-2] memo[k] = f return memo[n]
def notes(*grades, situation=False): """ -> Receives the grades os several students and returns a dictionary with varous information regarding the grades of the class :param grades: Receives student grades (undefined amount). :param situation: Indicates wheter or not show the class situation. :return: A dictionary with some of the following information about the class: number of notes, highest grade, lowest grade, class grade average, class situation(optional). """ notes = grades dict = {} number_of_notes = len(grades) cont = 0 highest = 0 lowest = 0 total = 0 for c in notes: if cont == 0: highest = c lowest = c if c > highest: highest = c if c < lowest: lowest = c total += c cont += 1 average = total / number_of_notes if average < 6: situation_class = 'BAD' elif 6 <= average <= 7.5: situation_class = 'REGULAR' else: situation_class = 'EXELLENT' dict['Total'] = number_of_notes dict['Highest'] = highest dict['Lowest'] = lowest dict['Average'] = average if situation: dict['Situation'] = situation_class return dict
def selectionsort(a): """ selectionsort implementation >>> selectionsort([6, 4, 8, 2, 1, 9, 10]) [1, 2, 4, 6, 8, 9, 10] """ for i in range(len(a)): min = i for j in range(i,len(a)): if a[j] < a[min]: min = j a[i],a[min] = a[min], a[i] return a
def subdict(o_dict, subset): """Method gets sub dictionary Args: o_dict (dict): original dictionary subset (list): requested subset key Returns: dict: sub dictionary """ return dict((key, value) for key, value in o_dict.items() if key in subset)
def decapitalize(s): """ De-capitalize a string (lower first character) :param s: :type s: :return: :rtype: """ return s[:1].lower() + s[1:] if s else ''
def chunks(lst, n): """Expand successive n-sized chunks from lst.""" return [lst[i - n : i] for i in range(n, len(lst) + n, n)]
def cubicCurve(P, t): """Evaluated the cubic Bezier curve (given by control points P) at t""" return P[0] * (1 - t) ** 3 + 3 * P[1] * t * (1 - t) ** 2 + 3 * P[2] * ( 1 - t) * t ** 2 + P[3] * t ** 3
def paste(x, sep=", "): """ Custom string formatting function to format (???) output. """ out = "" for i in x: out += i + sep return out.strip(sep)
def generate_probabilities(alpha, beta, x): """Generate probabilities in one pass for all t in x""" p = [alpha / (alpha + beta)] for t in range(1, x): pt = (beta + t - 1) / (alpha + beta + t) * p[t-1] p.append(pt) return p
def letter_count(num): """Returns the number of letters in the specified number""" assert 0 < num <= 1000 num = str(num) acc = 0 if len(num) > 3: acc += len("one thousand".replace(" ", "")) num = "0" if len(num) > 2: acc += ( len("hundred and".replace(" ", "")) if int(num[-2:]) > 0 else len("hundred") ) acc += ( 3 if num[0] in ["1", "2", "6"] else 4 if num[0] in ["4", "5", "9"] else 5 if num[0] in ["3", "7", "8"] else 0 ) num = str(int(num[-2:])) if int(num) > 12: acc += len("ty") if int(num) > 19 else len("teen") num = num if int(num) > 19 or int(num) == 14 else num[-1:] acc += ( 3 if num[0] in ["4", "5", "6"] else 4 if num[0] in ["2", "3", "8", "9"] else 5 if num[0] == "7" else 0 ) num = num[-1:] if int(num) > 19 or int(num) == 14 else "0" acc += ( 3 if num in ["1", "2", "6", "10"] else 4 if num in ["4", "5", "9"] else 5 if num in ["3", "7", "8"] else 6 if num in ["11", "12"] else 0 ) return acc
def strip_dir(path): """Returns directory of file path. .. todo:: Replace this with Python standard function :param str path: path is a file path. not an augeas section or directive path :returns: directory :rtype: str """ index = path.rfind("/") if index > 0: return path[:index+1] # No directory return ""
def is_annotation(obj): """ An object is an annotation object if it has the attributes help, kind, abbrev, type, choices, metavar. """ return (hasattr(obj, 'help') and hasattr(obj, 'kind') and hasattr(obj, 'abbrev') and hasattr(obj, 'type') and hasattr(obj, 'choices') and hasattr(obj, 'metavar'))
def leapfrog(theta, r, grad, epsilon, f): """ Perfom a leapfrog jump in the Hamiltonian space INPUTS ------ theta: ndarray[float, ndim=1] initial parameter position r: ndarray[float, ndim=1] initial momentum grad: float initial gradient value epsilon: float step size f: callable it should return the log probability and gradient evaluated at theta logp, grad = f(theta) OUTPUTS ------- thetaprime: ndarray[float, ndim=1] new parameter position rprime: ndarray[float, ndim=1] new momentum gradprime: float new gradient logpprime: float new lnp """ # make half step in r rprime = r + 0.5 * epsilon * grad # make new step in theta thetaprime = theta + epsilon * rprime # compute new gradient logpprime, gradprime = f(thetaprime) # make half step in r again rprime = rprime + 0.5 * epsilon * gradprime return thetaprime, rprime, gradprime, logpprime
def calc_mean(values): """Calculates the mean of a list of numbers.""" values_sum = 0 for value in values: values_sum += value return values_sum / len(values)
def insertion_sort(A): """do something.""" hi = 1 # upper bound while hi < len(A): j = hi while j > 0 and A[j-1] > A[j]: A[j-1], A[j] = A[j], A[j-1] # swap! j -= 1 hi += 1 return A
def parse_hour_spec(hour_spec): """Hour spec is a two-hour time-window that dictates when an hourly backup should kick off. Ex. h_0000_0200 is a backup off that kicks off sometime between midnight and 2am GMT. """ prefix, start_window, end_window = hour_spec.split('_') return int(start_window) / 100
def dir_get(path): """ Returns directory portion of the path argument. """ import os s = path.split(os.sep) s.pop() return os.sep.join(s)
def linear_anneal(t, anneal_steps, start_e, end_e, start_steps): """ Linearly anneals epsilon Args: t: Current time anneal_steps: Number of steps to anneal over start_e: Initial epsilon end_e: Final epsilon start_steps: Number of initial steps without annealing """ assert end_e <= start_e t = max(0, t - start_steps) return max(end_e, (anneal_steps - t) * (start_e - end_e) / anneal_steps + end_e)
def make_empty(seq): """ >>> make_empty([1, 2, 3, 4]) [] >>> make_empty(('a', 'b', 'c')) () >>> make_empty("No, not me!") '' """ if type(seq) == list: return list() elif type(seq) == tuple: return tuple() elif type(seq) == str: return str()
def accept_use_complete_history(t, distance_function, eps, x, x_0, par): """ Use the acceptance criteria from the complete history to evaluate whether to accept or reject. This includes time points 0,...,t, as far as these are available. If either the distance function or the epsilon criterion cannot handle any time point in this interval, the resulting error is simply intercepted and the respective time not used for evaluation. This situation can frequently occur when continuing a stopped run. A different behavior is easy to implement. """ # first test current criterion, which is most likely to fail d = distance_function(x, x_0, t, par) accept = d <= eps(t) if accept: # also check against all previous distances and acceptance criteria for t_prev in range(0, t): try: d_prev = distance_function(x, x_0, t_prev, par) accept = d_prev <= eps(t_prev) if not accept: break except Exception: # ignore as of now accept = True return d, accept
def check_split_ratio(split_ratio): """Check that the split ratio argument is not malformed""" valid_ratio = 0. if isinstance(split_ratio, float): # Only the train set relative ratio is provided # Assert in bounds, validation size is zero assert 0. < split_ratio < 1., ( "Split ratio {} not between 0 and 1".format(split_ratio)) test_ratio = 1. - split_ratio return (split_ratio, test_ratio, valid_ratio) elif isinstance(split_ratio, list): # A list of relative ratios is provided length = len(split_ratio) assert length == 2 or length == 3, ( "Length of split ratio list should be 2 or 3, got {}".format(split_ratio)) # Normalize if necessary ratio_sum = sum(split_ratio) if not ratio_sum == 1.: split_ratio = [float(ratio) / ratio_sum for ratio in split_ratio] if length == 2: return tuple(split_ratio + [valid_ratio]) return tuple(split_ratio) else: raise ValueError('Split ratio must be float or a list, got {}' .format(type(split_ratio)))
def pad(plaintext: bytearray, block_size=16): """PKCS#7 Padding""" num_pad = block_size - (len(plaintext) % block_size) return plaintext + bytearray([num_pad for x in range(num_pad)])
def list_wrap_(obj): """ normalize input to list Args: obj(obj): input values """ return list(obj) if isinstance(obj, (list, tuple)) else [obj]
def name_with_unit(var=None, name=None, log=False): """ Make a column title or axis label with "Name [unit]". """ text = "" if name is not None: text = name elif var is not None: text = str(var.dims[-1]) if log: text = "log\u2081\u2080(" + text + ")" if var is not None: if var.bins is not None: text += " [{}]".format(var.bins.constituents["data"].unit) else: text += " [{}]".format(var.unit) return text
def difference(list_1, list_2): """ Deterministically find the difference between two lists Returns the elements in `list_1` that are not in `list_2`. Behaves deterministically, whereas set difference does not. Computational cost is O(max(l1, l2)), where l1 and l2 are len(list_1) and len(list_2), respectively. Args: list_1 (:obj:`list`): one-dimensional list list_2 (:obj:`list`): one-dimensional list Returns: :obj:`list`: a set-like difference between `list_1` and `list_2` Raises: `TypeError` if `list_1` or `list_2` contains an unhashable (mutable) type """ list_2_set = set(list_2) return list(filter(lambda item:not item in list_2_set, list_1))
def Mid(text, start, num=None): """Return some characters from the text""" if num is None: return text[start - 1:] else: return text[(start - 1):(start + num - 1)]
def add_Ts(T0,T1): """ Merges two path dictionaries. :param T0: A path dictionary. :param T1: A path dictionary. :return: A merged path dictionary. """ for u in T1: if u not in T0: T0[u] = {} for v in T1[u]: if v not in T0[u]: T0[u][v] = set() for path in T1[u][v]: T0[u][v].add(path) return T0
def argsparseintlist(txt): """ Validate a list of int arguments. :param txt: argument with comma separated numbers. :return: list of integer converted numbers. """ txt = txt.split(",") listarg = [int(i) for i in txt] return listarg
def calchash(data, key): """Calculate file name hash. Args: data: File name data. key: Hash key. Returns: Hash value. """ ret = 0 for c in data: ret = (ret * key + ord(c)) & 0xffffffff return ret
def _getBounds(stats1, stats2): """ Gets low and high bounds that captures the interesting bits of the two pieces of data. @ In, stats1, dict, dictionary with either "low" and "high" or "mean" and "stdev" @ In, stats2, dict, dictionary with either "low" and "high" or "mean" and "stdev" @ Out, (low, high), (float, float) Returns low and high bounds. """ def getLowBound(stat): """ Finds the lower bound from the statistics in stat. @ In, stat, dict, Dictionary with either "low" or "mean" and "stdev" @ Out, getLowBound, float, the lower bound to use. """ if "low" in stat: return stat["low"] return stat["mean"] - 5*stat["stdev"] def getHighBound(stat): """ Finds the higher bound from the statistics in stat. @ In, stat, dict, Dictionary with either "high" or "mean" and "stdev" @ Out, getLowBound, float, the lower bound to use. """ if "high" in stat: return stat["high"] return stat["mean"] + 5*stat["stdev"] low = min(getLowBound(stats1), getLowBound(stats2)) high = max(getHighBound(stats1), getHighBound(stats2)) return (low,high)
def GetValueFromObjectCustomMetadata(obj_metadata, search_key, default_value=None): """Filters a specific element out of an object's custom metadata. Args: obj_metadata: (apitools_messages.Object) The metadata for an object. search_key: (str) The custom metadata key to search for. default_value: (Any) The default value to use for the key if it cannot be found. Returns: (Tuple(bool, Any)) A tuple indicating if the value could be found in metadata and a value corresponding to search_key (the value at the specified key in custom metadata, or the default value if the specified key does not exist in the custom metadata). """ try: value = next((attr.value for attr in obj_metadata.metadata.additionalProperties if attr.key == search_key), None) if value is None: return False, default_value return True, value except AttributeError: return False, default_value
def is_country_in_list(country, names): """Does country have any name from 'names' list among its name/name:en tags of boundary/label. """ return any( any( country[property].get(name_tag) in names for name_tag in ('name', 'name:en') ) for property in ('label', 'boundary') if country[property] )
def _get_acl_username(acl): """Port of ``copyAclUserName`` from ``dumputils.c``""" i = 0 output = '' while i < len(acl) and acl[i] != '=': # If user name isn't quoted, then just add it to the output buffer if acl[i] != '"': output += acl[i] i += 1 else: # Otherwise, it's a quoted username i += 1 if i == len(acl): raise ValueError('ACL syntax error: unterminated quote.') # Loop until we come across an unescaped quote while not (acl[i] == '"' and acl[i + 1:i + 2] != '"'): # Quoting convention is to escape " as "". if acl[i] == '"' and acl[i + 1:i + 2] == '"': i += 1 output += acl[i] i += 1 if i == len(acl): raise ValueError('ACL syntax error: unterminated quote.') i += 1 return i, output
def parse_id(i): """Since we deal with both strings and ints, force appid to be correct.""" try: return int(str(i).strip()) except: return None
def clean_spaces(txt): """ Removes multiple spaces from a given string. Args: txt (str): given string. Returns: str: updated string. """ return " ".join(txt.split())
def interp_bands(src_band, target_band, src_gain): """Linear interp from one band to another. All must be sorted.""" gain = [] for i, b in enumerate(target_band): if b in src_band: gain.append(src_gain[i]) continue idx = sorted(src_band + [b]).index(b) idx = min(max(idx, 1), len(src_band) - 1) x1, x2 = src_band[idx - 1:idx + 1] y1, y2 = src_gain[idx - 1:idx + 1] g = y1 + ((y2 - y1) * (b - x1)) / float(x2 - x1) gain.append(min(12.0, g)) return gain
def pretty_bytes(num): """ pretty print the given number of bytes """ for unit in ['', 'KB', 'MB', 'GB']: if num < 1024.0: if unit == '': return "%d" % (num) else: return "%3.1f%s" % (num, unit) num /= 1024.0 return "%3.1f%s" % (num, 'TB')
def get_lengthfield_width_by_wiretype(wiretype): """ Returns the width of the length field as number of bytes depending on the given wiretype. """ if wiretype is None: raise ValueError('Wiretype needed, can not convert NoneType.') if wiretype < 4: return 0 elif wiretype == 5: return 1 elif wiretype == 6: return 2 elif wiretype == 7: return 4 elif wiretype == 4: raise ValueError( f'Can not map given wiretype to lengthfield width {wiretype}, must be specified') else: raise ValueError( f'Can not map given wiretype to lengthfield width {wiretype}.')
def intent_slot(intent, slot_name): """return slot dict, avoid key errors""" if slot_name in intent['slots'] and 'value' in intent['slots'][slot_name]: return intent['slots'][slot_name] return None
def error_message(error_text: str, status_code=400): """Generate an error message with a status code. Args: error_text (str): Error text to return with the message body. status_code (int): HTTP status code to return. Return dict, int: Error message and HTTP status code. """ return {'error': error_text}, status_code
def _check_name_should_break(name): """ Checks whether the passed `name` is type `str`. Used inside of ``check_name`` to check whether the given variable is usable, so we should stop checking other alternative cases. Parameters ---------- name : `Any` Returns ------- should_break : `bool` If non empty `str` is received returns `True`, meanwhile if `None` or empty `str` is received `False`. Raises ------ TypeError If `name` was not passed as `None` or type `str`. """ if (name is None): return False if type(name) is not str: raise TypeError(f'`name` should be `None` or type `str`, got `{name.__class__.__name__}`.') if name: return True return False
def disjoint1(A, B, C): """O(n**3)""" for a in A: for b in B: for c in C: if a == b == c: return False return True
def format_node(node, indent, depth, to_str=str): """Return string of graph node based on arguments. Args node: tuple of two items indent: string of tree indentation chars depth: int of tree depth, 0 = root to_str: function to convert node to string, by default str Returns String representaiton of node. """ space = ' ' * ((len(indent) + 1) * (depth - 1)) leader = '|' + indent if depth > 0 else '' return space + leader + to_str(node)
def GetAllProjectsOfIssues(issues): """Returns a list of all projects that the given issues are in.""" project_ids = set() for issue in issues: project_ids.add(issue.project_id) return project_ids
def convertd2b__(amount, cad, decpre, binpre): """Return the result with the equality.""" d2b = str(amount) + " " + decpre + " = " + cad + " " + binpre return d2b
def basic_to_bio(tags): """ Convert a basic tag sequence into a BIO sequence. You can compose this with bio2_to_bioes to convert to bioes Args: tags: a list of tags in basic (no B-, I-, etc) format Returns: new_tags: a list of tags in BIO format """ new_tags = [] for i, tag in enumerate(tags): if tag == 'O': new_tags.append(tag) elif i == 0 or tags[i-1] == 'O' or tags[i-1] != tag: new_tags.append('B-' + tag) else: new_tags.append('I-' + tag) return new_tags
def recursive_itemgetter(data_structure, keys): """Recursively retrieve items with getitem, for mix of lists, dicts...""" curr_data_structure = data_structure for curr_key in keys: curr_data_structure = curr_data_structure[curr_key] return curr_data_structure
def har_request_headers(har, offset=-1): """helper to return specified request headers for requests call""" return {i['name']: i['value'] for i in har['log']['entries'][offset]['request']['headers']}
def to_ms_string(seconds, left=False): """ Convert seconds into a string of milliseconds. If the string is smaller than 6 positions it will add leading spaces to complete a total of 6 chars Args: seconds: time in seconds expressed as float left: reverse justification and fills blanks at the right Returns: String with with at least 6 positions. """ ms = str(int(1000 * seconds)) if left: return ms.ljust(6) return ms.rjust(6)
def linear_scale(input, in_low, in_high, out_low, out_high): """ (number, number, number, number, number) -> float Linear scaling. Scales old_value in the range (in_high - in-low) to a value in the range (out_high - out_low). Returns the result. >>> linear_scale(0.5, 0.0, 1.0, 0, 127) 63.5 """ in_range = (in_high - in_low) out_range = (out_high - out_low) result = (((input - in_low) * out_range) / in_range) + out_low return result
def preference_deploy(proto_commod, pref_fac, diff): """ This function deploys the facility with the highest preference only. Paramters: ---------- proto_commod: dictionary key: prototype name value: dictionary key: 'cap', 'pref', 'constraint_commod', 'constraint' value pref_fac: dictionary key: prototype name value: preference value diff: float amount of capacity that is needed Returns: -------- deploy_dict: dictionary key: prototype name value: number of prototype to deploy """ # get the facility with highest preference deploy_dict = {} proto = sorted(pref_fac, key=pref_fac.get, reverse=True)[0] if pref_fac[proto] < 0: return deploy_dict if diff >= proto_commod[proto]['cap']: deploy_dict[proto] = 1 diff -= proto_commod[proto]['cap'] while diff > proto_commod[proto]['cap']: deploy_dict[proto] += 1 diff -= proto_commod[proto]['cap'] if diff == 0: return deploy_dict else: deploy_dict[proto] += 1 elif diff > 0: deploy_dict[proto] = 1 return deploy_dict
def extract_reason(openfield): """ Extract optional reason data from openfield. :param openfield: str :return: str """ if "," in openfield: # Only allow for 1 extra param at a time. No need for more now, but beware if we add! parts = openfield.split(",") parts.pop(0) for extra in parts: key, value = extra.split("=") if key == "reason": return value return ""
def null(n): """ Return the null matrix of size n :param n: size of the null matrix to return :return: null matrix represented by a 2 dimensional array of size n*n """ return [[0 for _ in range(n)] for _ in range(n)]
def bubble_sort(array): """ my own implementation of the bubble sort algorithm. Args: array (list[int]): A unsorted list with n numbers. Returns: list[int]: The sorted input list. Examples: >>> bubble_sort([]) == sorted([]) True >>> bubble_sort([1]) == [1] True >>> bubble_sort([4,3,2,1]) == sorted([4,3,2,1]) True >>> bubble_sort(['a','d','h','c']) == sorted(['a','d','h','c']) True """ for _ in range(len(array)-1): for j in range(len(array)-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array
def sequence_accuracy(references, hypotheses): """ Compute the accuracy of hypothesis tokens: correct tokens / all tokens Tokens are correct if they appear in the same position in the reference. :param hypotheses: list of hypotheses (strings) :param references: list of references (strings) :return: """ assert len(hypotheses) == len(references) correct_sequences = sum( [1 for (hyp, ref) in zip(hypotheses, references) if hyp == ref] ) return (correct_sequences / len(hypotheses)) * 100 if hypotheses else 0.0
def normalize(l): """ Normalizes input list. Parameters ---------- l: list The list to be normalized Returns ------- The normalized list or numpy array Raises ------ ValueError, if the list sums to zero """ s = float(sum(l)) if s == 0: raise ValueError("Cannot normalize list with sum 0") return [x / s for x in l]
def _validate_port(port_value): """Makes sure the port value is valid and can be used by a non-root user. Args: port_value: Integer or string version of integer. Returns: Integer version of port_value if valid, otherwise None. """ try: port_value = int(port_value) except (ValueError, TypeError): return None if not (1024 <= port_value <= 49151): return None return port_value
def _is_empty(query): """Checks if the result table of a query is empty Parameters ---------- query : dict JSON of the result of the query Returns ------- bool TRUE if the result table is empty, else FALSE """ return len(query["bindings"]) == 0
def _convert_freq_string_to_description(freq): """Get long description for frequency string.""" if freq in ('H', '1H'): return 'hourly' if freq in ('D', '1D'): return 'daily' if freq in ('W', '1W', 'W-SUN'): return 'weekly' if freq in ('1M', '1MS', 'MS'): return 'monthly' if freq in ('1A', '1AS', '1BYS', 'A-DEC'): return 'yearly' raise ValueError("Unsupported frequency string '%r'" % freq)
def check_de(current_de, list_of_de): """Check if any of the strings in ``list_of_de`` is contained in ``current_de``.""" return any(de in current_de for de in list_of_de)
def list_difference(list1, list2): """ Given two lists with alignments list1 and list2, return a new list (new_list2) that contains all elements of list2 without elements of list1. """ # Create an inverted list of alignments names in list1 to allow fast # lookups. inverted_list1 = {} for alignment in list1: inverted_list1[alignment.name] = 1 # Copy only elements of list2 that are not in list1, by looking up the # inverted list. new_list2 = list() for alignment in list2: if alignment.name not in inverted_list1: new_list2.append(alignment) return new_list2
def safe_issubclass(*args): """Like issubclass, but will just return False if not a class.""" try: if issubclass(*args): return True except TypeError: pass return False
def set_of_county_tuples(cluster_list): """ Input: A list of Cluster objects Output: Set of sorted tuple of counties corresponds to counties in each cluster """ set_of_clusters = set([]) for cluster in cluster_list: counties_in_cluster = cluster.fips_codes() # convert to immutable representation before adding to set county_tuple = tuple(sorted(list(counties_in_cluster))) set_of_clusters.add(county_tuple) return set_of_clusters
def harmonize_url(url): """Harmonize the url string. This function checks if url ends with slash, if not, add a slash to the url string. Args: url (str): A string of url. Returns: str: A string of url ends with slash. """ url = url.rstrip('/') return url + '/'
def get_relevant_parameters(feature_data, iob_type): """ Gets features relevant to a specific IOB type and assign them verilog parameter names. """ # Get all features and make parameter names all_features = set( [f for data in feature_data.values() for f in data.keys()]) parameters = [] # Check if a feature is relevant to particular IOB type is_diff = "DIFF_" in iob_type for feature in all_features: for iosettings in feature_data: if iosettings.is_diff == is_diff: base_iob_type = iob_type.replace("DIFF_", "") if base_iob_type in feature_data[iosettings][feature]: parameters.append(( feature, feature.replace(".", "_"), )) break return parameters
def embed(information:dict) -> str: """ input: item:dict ={"url":str,"text":str} """ return f"[{information['url']}]({information['url']})"
def snake_to_camel(s: str): """ Convert a snake_cased_name to a camelCasedName :param s: the snake_cased_name :return: camelCasedName """ components = s.split("_") return components[0] + "".join(y.title() for y in components[1:])
def as_frozen(x): """Return an immutable representation for x.""" if isinstance(x, dict): return tuple(sorted((k, as_frozen(v)) for k, v in x.items())) else: assert not isinstance(x, (list, tuple)) return x
def check_1(sigs, exps): """ Repository in src-openeuler and openeuler should be managed by the single SIG. """ print("Repository in src-openeuler and openeuler should be managed by the single SIG.") repositories = {} errors_found = 0 for sig in sigs: if sig["name"] == "Private": continue for repo in sig["repositories"]: repo_name = repo.replace("src-openeuler/", "").replace("openeuler/", "").lower() supervisor = repositories.get(repo_name, set()) supervisor.add(sig["name"]) repositories[repo_name] = supervisor for repo in repositories: sigs = repositories[repo] if len(sigs) != 1: if repo in exps: continue print("ERROR! " + repo + ": Co-managed by these SIGs " + str(sigs)) errors_found += 1 if errors_found == 0: print("PASS WITHOUT ISSUES FOUND.") return errors_found
def split_mapping_by_keys(mapping, key_lists): """Split up a mapping (dict) according to connected components Each connected component is a sequence of keys from mapping; returned is a corresponding sequence of head mappings, each with only the keys from that connected component. """ mappings = [] for seq in key_lists: mappings.append(dict((head_id, value) for head_id, value in list(mapping.items()) if head_id in seq)) return mappings
def clamp(value, minval, maxval): """Clamp a numeric value to a specific range. Parameters ---------- value: numeric The value to clamp. minval: numeric The lower bound. maxval: numeric The upper bound. Returns ------- numeric The clamped value. It will be in the range ``[minval, maxval]``. """ return max(min(value, maxval), minval)
def int_node_filter(int_node_list, tol=1E-4): """ """ s_list = sorted(int_node_list) # , key=lambda x:x[i]) #print('s_list', s_list) return s_list[:1] + [t2 for t1, t2 in zip(s_list[:-1], s_list[1:]) if ( (t1[1:] != t2[1:]) and ((t2[0]-t1[0]) > tol) )]
def var_K(N_atoms, avg_momentum): """compute variances of kinetic energy Args: N_atoms (TYPE): Description avg_momentum (TYPE): Description Returns: TYPE: Description """ return (2 * ((0.5 * 3 * N_atoms * avg_momentum **2 ) ** 2)/(3 * N_atoms) ) ** (1/2)
def kernel_zhao(s, s0=0.08333, theta=0.242): """ Calculates Zhao kernel for given value. :param s: time point to evaluate :param s0: initial reaction time :param theta: empirically determined constant :return: value at time point s """ c0 = 1.0 / s0 / (1 - 1.0 / -theta) # normalization constant if s >= 0: if s <= s0: return c0 else: return c0 * (s / s0)**(-(1. + theta)) else: return 0
def ghi_to_w(ghi, eff=0.19, surf=0.0568): """ Description of ghi_to_w Args: ghi (undefined): Global Horizontal Irradiance eff=0.19 (undefined): Efficiency of solar panel surf=0.0568 (undefined): Solar panel surface area """ return ghi*eff*surf
def convert_to_spans(raw_text, tokens): """Convert tokenized version of `raw_text` to character spans into it. Args: raw_text: The raw string tokens: The tokenized version of the string Returns: [list of (start, end) tuples] mapping each token to corresponding indices in the text. """ cur_idx = 0 spans = [] for token in tokens: tmp = raw_text.find(token, cur_idx) l = len(token) cur_idx = tmp spans.append((cur_idx, cur_idx + l)) cur_idx += l return spans
def temperature_convert(inputvalue, inputunits, outputunits): """ Converts temperature from one unit to another. Parameters ---------- inputvalue : float Input temperature value inputunits : string Input temperature units: c = celsius f = fahrenheit k = kelvin outputunits : string Output temperature units: c = celsius f = fahrenheit k = kelvin Returns ------- float Returns temperature value in required units. """ if inputunits.lower() == "c": if outputunits.lower() == "f": return (9/5)*inputvalue+32 elif outputunits.lower() == "k": return inputvalue + 273.15 elif outputunits.lower() == "c": return inputvalue if inputunits.lower() == "f": if outputunits.lower() == "c": return (5/9)*inputvalue-32 elif outputunits.lower() == "k": return (inputvalue-32) * (5/9)+273.15 elif outputunits.lower() == "f": return inputvalue if inputunits.lower() == "k": if outputunits.lower() == "c": return inputvalue - 273.15 elif outputunits.lower() == "f": return (inputvalue-273.15)*(9/5)+32 elif outputunits.lower() == "k": return inputvalue units = ["k", "c", "f"] if inputunits.lower() not in units or outputunits.lower() not in units: raise Exception("Enter a valid temperature inputunit or outputunit value. Must be: c, f or k")
def my_isinstance(obj, class_or_tuple): """Same as builtin instance, but without position only constraint. Therefore, we can partialize class_or_tuple: Otherwise, couldn't do: >>> isinstance_of_str = partial(my_isinstance, class_or_tuple=str) >>> isinstance_of_str('asdf') True >>> isinstance_of_str(3) False """ return isinstance(obj, class_or_tuple)
def q_zero(bits=8): """ The quantized level of the 0.0 value. """ return 1 << (bits - 1)
def _FORMAT(s): """Helper to provide uniform appearance for formats in cmdline options""" return ". Specified as %r" % s
def distinct(number): """Checks if the digits of a natural number are distinct""" seen = [] while number: digit = number % 10 if digit in seen: return False seen.append(digit) # Remove the last digit from the number number //= 10 return True
def stress_model(strain, modulus): """ Returns the linear estimate of the stress-strain curve using the strain and estimated modulus. Used for fitting data with scipy. Parameters ---------- strain : array-like The array of experimental strain values, unitless (or with cancelled units, such as mm/mm). modulus : float The estimated elastic modulus for the data, with units of GPa (Pa * 10^9). Returns ------- array-like The estimated stress data following the linear model, with units of Pa. """ return strain * modulus * 1e9
def calcite(piezometer=None): """ Data base for calcite piezometers. It returns the material parameter, the exponent parameter and a warn with the "average" grain size measure to be use. Parameter --------- piezometer : string or None the piezometric relation References ---------- | Barnhoorn et al. (2004) https://doi.org/10.1016/j.jsg.2003.11.024 | Platt and De Bresser (2017) https://doi.org/10.1016/j.jsg.2017.10.012 | Rutter (1995) https://doi.org/10.1029/95JB02500 | Valcke et al. (2015) https://doi.org/10.1144/SP409.4 Assumptions ----------- - The piezometer of Rutter (1995) requires entering the grain size as the linear mean apparent grain size calculated using equivalent circular diameters with no stereological correction. """ if piezometer is None: print('Available piezometers:') print("'Barnhoorn'") print("'Platt_Bresser'") print("'Rutter_SGR'") print("'Rutter_GBM'") print("'Valcke'") return None elif piezometer == 'Rutter_SGR': B, m = 812.83, 0.88 warn = 'Ensure that you entered the apparent grain size as the arithmetic mean in linear scale' linear_interceps = False correction_factor = False elif piezometer == 'Rutter_GBM': B, m = 2691.53, 0.89 warn = 'Ensure that you entered the apparent grain size as the arithmetic mean in linear scale' linear_interceps = False correction_factor = False elif piezometer == 'Barnhoorn': B, m = 537.03, 0.82 warn = 'Ensure that you entered the apparent grain size as the arithmetic mean in linear scale' linear_interceps = False correction_factor = False elif piezometer == 'Platt_Bresser': B, m = 538.40, 0.82 warn = 'Ensure that you entered the apparent grain size as the root mean square in linear scale' linear_interceps = False correction_factor = False elif piezometer == 'Valcke': B, m = 1467.92, 1.67 warn = 'Ensure that you entered the apparent grain size the arithmetic mean in linear scale' linear_interceps = False correction_factor = False else: calcite() raise ValueError('Piezometer name misspelled. Please choose between valid piezometers') return B, m, warn, linear_interceps, correction_factor
def pre_process_data(linelist): """Empty Fields within ICD data point are changed from Null to 0""" for index in range(len(linelist)): if not linelist[index]: linelist[index] = '0' return linelist
def rain_attenuation(distance): """Calculate rain attenuation.""" attenuation = 9 * (distance / 1000) # convert from m to km return round(attenuation, 3)
def Ecmrel2Enm(Ecmrel, ref_wavelength=515): """Converts energy from cm-1 relative to a ref wavelength to an energy in wavelength (nm) Parameters ---------- Ecmrel: float photon energy in cm-1 ref_wavelength: float reference wavelength in nm from which calculate the photon relative energy Returns ------- float photon energy in nm Examples -------- >>> Ecmrel2Enm(500, 515) 528.6117526302285 """ Ecm = 1 / (ref_wavelength * 1e-7) - Ecmrel return 1 / (Ecm * 1e-7)
def make_definition(resources, include_sqs): """ Makes a definition for the demo based on resources created by the AWS CloudFormation stack. :param resources: Resources to inject into the definition. :param include_sqs: When True, include a state that sends messages to an Amazon Simple Queue Service (Amazon SQS). Otherwise, don't include this state. This is used by the demo to show how to update a state machine's definition. :return: The state machine definition. """ state_record_sent = { "Record Sent": { "Type": "Task", "Resource": "arn:aws:states:::dynamodb:updateItem", "Parameters": { "TableName": resources["MessageTableName"], "Key": { "user_name": { "S.$": "$.user_name"}, "message_id": { "S.$": "$.message_id"}}, "UpdateExpression": "SET sent=:s", "ExpressionAttributeValues": { ":s": {"BOOL": True}}}, "End": True}} state_send_to_sqs = { "Send": { "Type": "Task", "Resource": "arn:aws:states:::sqs:sendMessage", "Parameters": { "QueueUrl": resources["SendQueueUrl"], "MessageBody.$": "$.message", "MessageAttributes": { "user": { "DataType": "String", "StringValue.$": "$.user_name"}, "message_id": { "DataType": "String", "StringValue.$": "$.message_id"}}}, "ResultPath": None, "Next": "Record Sent"}} map_states = state_record_sent if include_sqs: map_states.update(state_send_to_sqs) definition = { "Comment": "Read messages from DynamoDB in a loop.", "StartAt": "Scan DynamoDB For Messages", "TimeoutSeconds": 3600, "States": { "Scan DynamoDB For Messages": { "Type": "Task", "Resource": resources["ScanFunctionArn"], "ResultPath": "$.List", "Next": "Send Messages"}, "Send Messages": { "Type": "Map", "ItemsPath": "$.List", "Iterator": { "StartAt": "Send" if include_sqs else "Record Sent", "States": map_states}, "ResultPath": None, "Next": "Pause Then Loop"}, "Pause Then Loop": { "InputPath": None, "Type": "Wait", "Seconds": 10, "Next": "Scan DynamoDB For Messages"}}} return definition
def atfile_sci(filename): """ Return the filename of the science image which is assumed to be the first word in the atfile the user gave. """ return filename.split()[0]
def calc_IoU(bbox1, bbox2): """ Calculate intersection over union for two boxes. Args: bbox1 (array_like[int]): Endpoints of the first bounding box in the next format: [ymin, xmin, ymax, xmax]. bbox2 (array_like[int]): Endpoints of the second bounding box in the next format: [ymin, xmin, ymax, xmax]. Returns: float: Intersection over union for given bounding boxes. """ ymin1, xmin1, ymax1, xmax1 = bbox1 ymin2, xmin2, ymax2, xmax2 = bbox2 ymin = max(ymin1, ymin2) xmin = max(xmin1, xmin2) ymax = min(ymax1, ymax2) xmax = min(xmax1, xmax2) if xmax <= xmin or ymax <= ymin: return 0 intersection = (ymax - ymin) * (xmax - xmin) union = ((ymax1 - ymin1) * (xmax1 - xmin1) + (ymax2 - ymin2) * (xmax2 - xmin2) - intersection) return intersection / union
def _split_list(mylist, chunk_size): """Split list in chunks. Parameters ---------- my_list: list list to split. chunk_size: int size of the lists returned. Returns ------- list list of the chunked lists. See: https://stackoverflow.com/a/312466/5201771 """ return [ mylist[offs : offs + chunk_size] for offs in range(0, len(mylist), chunk_size) ]
def extract_expression(expr: str) -> str: """Extract the sub-expression surrounded by parentheses in ``expr``.""" parenthesis_balance = 0 result = "" for c in expr: if c == "(": parenthesis_balance += 1 elif c == ")": parenthesis_balance -= 1 if parenthesis_balance == 0: return result[1:] else: result += c raise Exception("I should never end up here!")
def sum_digits(n): """Recursively calculate the sum of the digits of 'n' >>> sum_digits(7) 7 >>> sum_digits(30) 3 >>> sum_digits(228) 12 """ """BEGIN PROBLEM 2.4""" return n % 10 + (0 if n < 10 else sum_digits(n // 10)) """END PROBLEM 2.4"""
def binary_quadratic_coefficients_from_invariants(discriminant, invariant_choice='default'): """ Reconstruct a binary quadratic from the value of its discriminant. INPUT: - ``discriminant`` -- The value of the discriminant of the binary quadratic. - ``invariant_choice`` -- The type of invariants provided. The accepted options are ``'discriminant'`` and ``'default'``, which are the same. No other options are implemented. OUTPUT: A set of coefficients of a binary quadratic, whose discriminant is equal to the given ``discriminant`` up to a scaling. EXAMPLES:: sage: from sage.rings.invariants.reconstruction import binary_quadratic_coefficients_from_invariants sage: quadratic = invariant_theory.binary_form_from_invariants(2, [24]) # indirect doctest sage: quadratic Binary quadratic with coefficients (1, -6, 0) sage: quadratic.discriminant() 24 sage: binary_quadratic_coefficients_from_invariants(0) (1, 0, 0) """ if invariant_choice not in ['default', 'discriminant']: raise ValueError('unknown choice of invariants {} for a binary ' 'quadratic'.format(invariant_choice)) if discriminant == 0: return (1, 0, 0) else: try: return (1, 0, -discriminant/4) except ZeroDivisionError: return (0, 1, 0)
def bool_to_text(b): """ Changes a provided boolean into a 'Yes' or 'No' string No test is performed on whether or not the provided variable is boolean or not, only an 'if b: / else:' test is performed. Parameters ---------- b: any Object that will be tested for its evaluation to a boolean. Returns ------- text: :obj:`str` 'Yes' if input variable is evaluated as `True`, 'No' otherwise. """ if b: return "Yes" return "No"
def preprocess_text(text): """Remove tags like [P], [D], [R]""" return text[3:].strip()
def response_loader(request): """ Just reverse the message content. He take dict object and return dict object """ res = {"message": request["message"][::-1]} return res
def convert_list_str(string_list, type): """ Receive a string and then converts it into a list of selected type """ new_type_list = (string_list).split(",") for inew_type_list, ele in enumerate(new_type_list): if type is "int": new_type_list[inew_type_list] = int(ele) elif type is "float": new_type_list[inew_type_list] = float(ele) return new_type_list