content
stringlengths
42
6.51k
def get_context_first_matching_object(context, context_lookups): """ Return the first object found in the context, from a list of keys, with the matching key. """ for key in context_lookups: context_object = context.get(key) if context_object: return key, context_object return None, None
def convert_to_boolean(value): """Turn strings to bools if they look like them Truthy things should be True >>> for truthy in ['true', 'on', 'yes', '1']: ... assert convert_to_boolean(truthy) == True Falsey things should be False >>> for falsey in ['false', 'off', 'no', '0']: ... assert convert_to_boolean(falsey) == False Other things should be unchanged >>> for value in ['falsey', 'other', True, 0]: ... assert convert_to_boolean(value) == value """ if isinstance(value, str): if value.lower() in ['t', 'true', 'on', 'yes', '1']: return True elif value.lower() in ['f', 'false', 'off', 'no', '0']: return False return value
def get_max_offset_supported(atten): """Get maximum supported offset for given attenuation""" if atten >= 0.1: return (-8, +8) else: return (-2, +2)
def _parse_expected_tuple(arg, default=tuple()): """ Parse the argument into an expected tuple. The argument can be None (i.e., using the default), a single element (i.e., a length-1 tuple), or a tuple """ try: _ = iter(arg) except TypeError: tpl = tuple(default) if arg is None else (arg,) else: tpl = tuple(arg) return tpl
def parse_name_scope(name): """ Given a tensor or op name, return the name scope of the raw name. Args: name: The name of a tensor or an op. Returns: str: The name scope """ i = name.rfind('/') if i != -1: return name[:i] if not name.startswith('^') else name[1:i] return ''
def get_full_action_name(service, action_name): """ Gets the proper formatting for an action - the service, plus colon, plus action name. :param service: service name, like s3 :param action_name: action name, like createbucket :return: the resulting string """ action = service + ':' + action_name return action
def bond_dimension(mps): """ Given an MPS/MPO as a list of tensors with indices (N, E, S, W), return the maximum dimension of the N indices. (Equivalently, given an MPS/MPO as a list of tensors with indices (L, U, R, D), return the maximum dimension of the L indices.) Notes: * None objects in the MPS/MPO are considered to have dimension 0. :param mps: MPS/MPO :type mps: list of numpy.array (4d) :return: Bond dimension of MPS/MPO. :rtype: int """ # return max dimension of north indices, or zero if empty mps return max((t.shape[0] if t is not None else 0) for t in mps) if len(mps) else 0
def update_consistently(base, other): """Update base dict with other dict until a conflict is found. Returns whether a conflict was found.""" for key, value in other.items(): if base.setdefault(key, value) != value: # attempted update is inconsistent with content, so stop here return False return True
def invertIndices(selectedIndices, fullSetOfIndices): """ Returns all indices in fullSet but not in selected. """ selectedIndicesDict = dict((x, True) for x in selectedIndices) return [x for x in fullSetOfIndices if x not in selectedIndicesDict]
def camelCaseName(name): """Convert a CSS property name to a lowerCamelCase name.""" name = name.replace('-webkit-', '') words = [] for word in name.split('-'): if words: words.append(word.title()) else: words.append(word) return ''.join(words)
def registered_as_of( reference_date, # Required keyword return_expectations=None, ): """ All patients registed on the given date """ return "registered_as_of", locals()
def _has_matched_brackets(text: str) -> bool: """ Evaluate whether every opening bracket '[' in the 'text' has a matching closing bracket ']'. :param text: the text. :return: Boolean result, and associated message. """ open_bracket_stack = [] for index, _ in enumerate(text): if text[index] == "[": open_bracket_stack.append(index) elif text[index] == "]": if len(open_bracket_stack) == 0: return False open_bracket_stack.pop() return len(open_bracket_stack) == 0
def atof(text): """ helper for natural_keys attempt to convert text to float, or return text :param text: arbitrary text :return: float if succeeded to convert, the input text as is otherwise """ try: retval = float(text) except ValueError: retval = text return retval
def padding0(data): """ padding '0' into a number. so given a number=1, then it return '01' """ if data is None: return '00' if type(data) == str: int_data = int(data) else: int_data = data if int_data < 10: return '0' + str(int_data) else: return str(int_data)
def calculate_product(alist): """ Returns the product of a list of numbers. """ product = 1 for fact in alist: product *= fact return product
def _get_help_lines(content): """ Return the help text split into lines, but replacing the progname part of the usage line. """ lines = content.splitlines() lines[0] = 'Usage: <progname> ' + ' '.join(lines[0].split()[2:]) return lines
def apply_transform(best_transformation, current_tagged_corpus, size_of_corpus): """ Apply the best transform onto given corpus and return new tagged corpus Format of the output is same as that of input, namely: (word,tag) """ print("Applying best transform to corpus.", end="", flush=True) # new_corpus = [(word,best_transform.to_tag) if old_tag==best_transform.from_tag else (word,old_tag) for (word, # old_tag) in tagged_corpus] new_corpus = [current_tagged_corpus[0]] prev = current_tagged_corpus[0][1] for i in range(1, size_of_corpus): word, old_tag = current_tagged_corpus[i] if old_tag == best_transformation.from_tag and prev == best_transformation.prev_tag: new_corpus.append((word, best_transformation.to_tag)) prev = best_transformation.to_tag else: new_corpus.append((word, old_tag)) prev = old_tag # end for i print(".End") return new_corpus
def format_board(board): """Print off the board""" formatted_board = '-------------\n' for index in range(0, len(board)): # print player letter if present, else board index value = index + 1 if board[index] == '.' else board[index] formatted_board += f'| {value} ' if index == 2 or index == 5: formatted_board += '|\n-------------\n' if index == 8: formatted_board += '|\n-------------' return formatted_board
def get_plane(coords): """ three reference points points in form np.array( [ [x_1, y_1, z_1], [x_2, y_2, z_2], [x_3, y_3, z_3] ] ) make sure that three points are not in one line as this "breaks" math used here. """ # variables expanded x_1, y_1, z_1 = coords[0] x_2, y_2, z_2 = coords[1] x_3, y_3, z_3 = coords[2] # first we get vectors between points: # p_1 to p_2 r_12 = x_2-x_1, y_2-y_1, z_2-z_1 # p_1 to p_3 r_13 = x_3-x_1, y_3-y_1, z_3-z_1 # Now we compute the normal vector of the plane n = ( r_12[1]*r_13[2] - r_12[2]*r_13[1], r_12[2]*r_13[0] - r_12[0]*r_13[2], r_12[0]*r_13[1] - r_12[1]*r_13[0], ) # We add values to get plane equation plane = ( n[0], n[1], n[2], n[0]*x_1+n[1]*y_1+n[2]*z_1 ) return plane
def first_separator_index(data, separators, check_quotes): """Find the first index of a separator in |data|.""" in_quote_type = None escaped = False for index, ch in enumerate(data): if escaped: escaped = False continue elif in_quote_type: if ch == '\\': escaped = True elif ch == in_quote_type or ch == '\n': in_quote_type = None continue elif check_quotes: if ch == '"' or ch == "'": in_quote_type = ch if ch in separators: return index, ch return -1, None
def q_learn(old_state_action_q_value, new_state_max_q_value, reward, learn_rate=0.01, discount_factor=0.9): """ Returns updated state-action Q_value. :param old_state_action_q_value: Q_value of the chosen action in the previous state. :param new_state_max_q_value: maximum Q_value of new state. :param reward: received reward as result of taken action. :param learn_rate: learning rate. :param discount_factor: discount factor. :return: Updated Q-value of previous state-action pair. """ error = (reward + (discount_factor * new_state_max_q_value)) - old_state_action_q_value return old_state_action_q_value + (learn_rate * error)
def get_enabled_vhost_path(version, domain): """ Get the path for an enabled PHP vhost file regardless of wether or not it exists. Args: version - The PHP version used in the file path domain - The domain used in the file path """ return '/opt/php-' + version + '/etc/php-fpm.d/' + domain + '.conf'
def inward_radial_disp_plastic(ro, Po, crit_press, v, E, rp, Pi): """ Calculates and returns the inward radial displacement for plastic analysis. """ return (ro*(1+v)/E)*(2*(1-v)*(Po-crit_press)*(rp/ro)**2-(1-2*v)*(Po-Pi))
def _sha256(sha256): """Fallback to an incorrect default value of SHA-256 hash to prevent the hash check from being disabled, but allow the first download attempt of an archive to fail and print the correct hash. Args: sha256: expected SHA-256 hash of the archive to be downloaded. """ if not sha256: sha256 = "0" * 64 return sha256
def get_seq_identity_bytes(seq: bytes, other_seq: bytes) -> float: """Return the fraction of amino acids that are the same in `seq` and `other_seq`. Examples: >>> get_seq_identity(b'AAGC', b'AACC') 0.75 """ assert len(seq) == len(other_seq) return sum(a == b for a, b in zip(seq, other_seq)) / len(seq)
def interlis_model_dictionary(french_lexicon, german_lexicon): """ :param french_lexicon: lexicon of french model :param german_lexicon: lexicon of german model :return: """ if len(french_lexicon) == len(german_lexicon): unique_translations = set(list(zip(french_lexicon, german_lexicon))) translations = [translation for translation in unique_translations if translation[0] != translation[1]] return translations else: raise Exception("I must have missed something when creating the model lexicon!")
def convert_names(data, names_map): """ Dato un dict questa funzione ritorna un dict con i nomi opportunamente convertiti dalla mappa di coversione fornita.. """ converted_row = {} for csv_key, model_field in names_map.items(): converted_row[model_field] = data[csv_key] return converted_row
def allowable_stress_unity_check(sigma, allowable, df=0.72): """Calculate the allowable stress unity check value. Refs: https://en.wikipedia.org/wiki/Permissible_stress_design https://en.wikipedia.org/wiki/Factor_of_safety :param sigma: applied stress level to be checked. :type sigma: float :param allowable: the allowable stress, e.g. the yield stress. :type allowable: float :param df: the design factor. :type df: float :returns: unity check value. :rtype: float """ return sigma / allowable * df
def technique(attack_id, mapped_controls): """create a technique for a layer""" return { "techniqueID": attack_id, "score": len(mapped_controls), # count of mapped controls "comment": f"Mitigated by {', '.join(sorted(mapped_controls))}", # list of mapped controls }
def cal_local_high_low_point_score(high_low_points): """ :param high_low_points: :return: """ score = 0 if len(high_low_points) <= 1: return score for i in range(1, len(high_low_points)): score_i = 0 for j in range(0, i): if high_low_points[i] >= high_low_points[j]: score_i += (1.0 / (i - j)) else: score_i -= (1.0 / (i - j)) score_i /= (1.0 * i) score += score_i return score * 1.0 / (len(high_low_points) - 1)
def split_list(tx): """ split list in two with '+' as a separator """ idx_list = [idx for idx, val in enumerate(tx) if val == '+'] idx_list1 = [idx+1 for idx, val in enumerate(tx) if val == '+'] size = len(tx) if(size == 2): # lovelace only return [tx] # lovelace + tokens tx = [tx[i: j] for i, j in zip([0] + idx_list1, idx_list + ([size] if idx_list[-1] != size else []))] return tx
def dotted_name(cls): """Return the dotted name of a class.""" return "{0.__module__}.{0.__name__}".format(cls)
def factorial(n): """Factorial function implementation.""" return n * factorial(n-1) if n else 1
def add64(a, b): """ Perform addition as if we are on a 64-bit register. """ return (a + b) & 0xFFFFFFFFFFFFFFFF
def member_lis(lis1, lis2): """ If lis1 is last item in lis2, it returns the rest of lis2.""" found_at = -1 if lis1 is None or lis1 == []: return [] for index, rule in enumerate(lis2): if lis1 == rule: found_at = index break # lis1 found at last pos in lis2, return [] as nothing is #lis2 after this. if found_at == len(lis2) - 1: return [] # Return sub-lists after the index found_at, i.e return all # the elements in lis2 after element lis1. return lis2[found_at+1:]
def URLify(input_string): """Replace spaces in input_string with '%20', without using the replace() method of Python str objects, and must be done in-place. List slicing in Python is O(k), where k is the slice size, so this solution could be more optimal. Parameters ---------- input_string : str String to process Returns ------- str input_string, with spaces replaces by '%20' """ # Convert to char array chars = list(input_string) # Get indices of spaces space_indices = [] for i, char in enumerate(chars): if char == ' ': space_indices.append(i) # Extend char array to correct size chars.extend([None] * len(space_indices) * 2) # Replace spaces with '%20' for i, index in enumerate(space_indices): adjusted_index = index + (i * 2) # * 2, since adding 2 chars each loop str_end_index = len(input_string) + (i * 2) - 1 chars[adjusted_index: str_end_index + 2 + 1] = ( list('%20') + chars[adjusted_index + 1: str_end_index + 1] ) return ''.join(chars)
def get_action(actions, action_id): """ Gets an action by action ID @param actions (list) of Action objects @param action_id (int) action ID @return (Action) """ for action in actions: if action.id == action_id: return action return None
def get_items(matrix, items): """ :param matrix: matrix of the knapsack problem :param items: list of tuples (weight, value) :return: list of items """ # get the max value max_value = matrix[-1][-1] # get the index of the first item with a value equal to the max value i = len(items) - 1 while i > 0 and matrix[i][-1] != max_value: i -= 1 # get the index of the first item with a weight equal to the max weight # of the knapsack j = len(matrix[0]) - 1 while j > 0 and matrix[i][j] != max_value: j -= 1 # get the list of items items_list = [] while i > 0 and j > 0: if matrix[i][j] != matrix[i - 1][j]: items_list.append(items[i - 1]) j -= items[i - 1][0] i -= 1 return items_list
def has_unknown_matches(license_matches): """ Return True if any on the license matches has a license match with an `unknown` rule identifier. :param license_matches: list List of LicenseMatch. """ match_rule_identifiers = ( license_match.rule_identifier for license_match in license_matches ) match_rule_license_expressions = ( license_match.license_expression for license_match in license_matches ) return any( "unknown" in identifier for identifier in match_rule_identifiers ) or any( "unknown" in license_expression for license_expression in match_rule_license_expressions )
def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp
def arg_cond_req(args_array, opt_con_req): """Function: arg_cond_req Description: This checks a dictionary list array for options that require other options to be included in the argument list. Arguments: (input) args_array -> Array of command line options and values. (input) opt_con_req -> Dictionary list containing the option as the dictionary key to a list of arguments that are required for the dictionary key option. (output) status -> True|False - If required args are included. """ args_array = dict(args_array) opt_con_req = dict(opt_con_req) status = True for item in set(args_array.keys()) & set(opt_con_req.keys()): for _ in set(opt_con_req[item]) - set(args_array.keys()): status = False print("Error: Option {0} requires options {1}.". format(item, opt_con_req[item])) break return status
def sortSelection(A, k): """ Selects the @k-th smallest number from @A in O(nlogn) time by sorting and returning A[k] Note that indexing begins at 0, so call sortSelection(A, 0) to get the smallest number in the list, call sortselection(A, len(A) / 2) to get the median number of the list, call sortselection(A, len(A) - 1) to get the largest number of the list param A : an unsorted list param k : the k-th smallest number of @A to find return : the k-th smallest number of @A """ if k < 0 or k >= len(A): raise IndexError\ ('Requested k-th smallest value is out of index range for the provided list') B = A[:] B.sort() return B[k]
def eh_coordenada(coord): """ eh_coordenada: universal >>> logico - Determina se o valor dado e do tipo coordenada """ if not isinstance(coord, tuple) or len(coord) != 2: return False return (coord[0] in (0, 1, 2)) and (coord[1] in (0, 1, 2))
def get_dummy_from_bool(row, column_name): """Returns 0 if value in column_name is no, returns 1 if value in column_name is yes""" return 1 if row[column_name] == "yes" else 0
def utf_8_encode_array(array): """ encode 2D array to utf8 """ return [[val.encode("utf-8") for val in line] for line in array]
def GetContainingWhileContext(ctxt, stop_ctxt=None): """Returns the first ancestor WhileContext of `ctxt`. Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a while loop. Args: ctxt: ControlFlowContext stop_ctxt: ControlFlowContext, optional. If provided, the search will end if it sees stop_ctxt. Returns: `ctxt` if `ctxt` is a WhileContext, the most nested WhileContext containing `ctxt`, or None if `ctxt` is not in a while loop. If `stop_ctxt` is not `None`, this returns `ctxt` if it matches `stop_ctxt` in its traversal. """ while ctxt: if ctxt.IsWhileContext() or ctxt == stop_ctxt: return ctxt ctxt = ctxt.outer_context return None
def title_to_ids(title): """Function to convert a title into the id, name, and description. This is just a quick-n-dirty implementation, and is definately not meant to handle every FASTA title line case. """ # first split the id information from the description # the first item is the id info block, the rest is the description all_info = title.split(" ") id_info = all_info[0] rest = all_info[1:] descr = " ".join(rest) # now extract the ids from the id block # gi|5690369|gb|AF158246.1|AF158246 id_info_items = id_info.split("|") id = id_info_items[3] # the id with version info name = id_info_items[4] # the id without version info return id, name, descr
def _DictWithReturnValues(retval, pass_fail): """Create a new dictionary pre-populated with success/fail values.""" new_dict = {} # Note: 0 is a valid retval; test to make sure it's not None. if retval is not None: new_dict['retval'] = retval if pass_fail: new_dict[''] = pass_fail return new_dict
def _negaconvolution_naive(L1, L2): """ Negacyclic convolution of L1 and L2, using naive algorithm. L1 and L2 must be the same length. EXAMPLES:: sage: from sage.rings.polynomial.convolution import _negaconvolution_naive sage: from sage.rings.polynomial.convolution import _convolution_naive sage: _negaconvolution_naive([2], [3]) [6] sage: _convolution_naive([1, 2, 3], [3, 4, 5]) [3, 10, 22, 22, 15] sage: _negaconvolution_naive([1, 2, 3], [3, 4, 5]) [-19, -5, 22] """ assert len(L1) assert len(L1) == len(L2) N = len(L1) return [sum([L1[i] * L2[j-i] for i in range(j+1)]) - \ sum([L1[i] * L2[N+j-i] for i in range(j+1, N)]) for j in range(N)]
def concat_req_field(list): """ Import in pieces grabbing main fields plus unique amount and basis of estimate fields assigns fields to variables """ source_name = ['TRIFID','CHEMICAL NAME', 'CAS NUMBER', 'UNIT OF MEASURE'] + list return source_name
def spacelist(listtospace, spacechar=" "): """ Convert a list to a string with all of the list's items spaced out. :type listtospace: list :param listtospace: The list to space out. :type spacechar: string :param spacechar: The characters to insert between each list item. Default is: " ". """ output = '' space = '' output += str(listtospace[0]) space += spacechar for listnum in range(1, len(listtospace)): output += space output += str(listtospace[listnum]) return output
def GetStatus(plist): """Plists may have a RunAtLoad key.""" try: return plist['RunAtLoad'] except KeyError: return 'False'
def ensure_list(i): """If i is a singleton, convert it to a list of length 1""" # Not using isinstance here because an object that inherits from a list # is not considered a list here. That is, I only want to compare on the final-type. if type(i) is list: return i return [i]
def get_interest(ammount): """ Returns the ammount owed for interests """ if ammount > 1000: return ammount - ammount * 0.98 return ammount - ammount * 0.985
def BitsInCommon(v1, v2): """ Returns the number of bits in common between two vectors **Arguments**: - two vectors (sequences of bit ids) **Returns**: an integer **Notes** - the vectors must be sorted - duplicate bit IDs are counted more than once >>> BitsInCommon( (1,2,3,4,10), (2,4,6) ) 2 Here's how duplicates are handled: >>> BitsInCommon( (1,2,2,3,4), (2,2,4,5,6) ) 3 """ res = 0 v2Pos = 0 nV2 = len(v2) for val in v1: while v2Pos < nV2 and v2[v2Pos] < val: v2Pos += 1 if v2Pos >= nV2: break if v2[v2Pos] == val: res += 1 v2Pos += 1 return res
def get_host_finding_details_hr(host_finding_detail): """ Prepare human readable json for "risksense-get-host-finding-detail" command. Including basic details of host finding. :param host_finding_detail: host finding details from response :return: List of dict """ return [{ 'Title': host_finding_detail.get('title', ''), 'Host Name': host_finding_detail.get('host', {}).get('hostName', ''), 'Ip Address': host_finding_detail.get('host', {}).get('ipAddress', ''), 'Source': host_finding_detail.get('source', ''), 'Network': host_finding_detail.get('network', {}).get('name', ''), 'Risk Rating': host_finding_detail.get('riskRating', '') }, {}]
def _make_labels_wrap(labels): """Break labels which contain more than one name into multiple lines.""" for i, l in enumerate(labels): if len(l) > 25: # Split lines at ", " and rejoin with newline. labels[i] = '\n'.join(l.split(", ")) return labels
def get_data_score(data, freq): """ Scores the bytes in data according the probability that it is English text. Used to detect correctly-decoded plaintexts """ return sum([freq[chr(ch)] for ch in data])
def _int_ceiling(value, multiple_of=1): """Round C{value} up to be a C{multiple_of} something.""" # Mimicks the Excel "floor" function (for code stolen from occupancy calculator) from math import ceil return int(ceil(value/multiple_of))*multiple_of
def iterate_parameters(parameters, default, count): """ Goes through recursively senstivity nested parameter dictionary. Args: paramters (dict): nested dictionary default (dict): default parameter dictionary count (int): number of scenarios """ for key, value in parameters.items(): if key == 'count' or key == 'scenario': continue elif isinstance(value, dict): if key in default: default[key] = iterate_parameters(value, default[key], count) else: print(key + ' not in parameters') else: if isinstance(value, tuple): default[key] = value[count] else: default[key] = value return default
def set_file_name(fig_name, fmt): """ Returns a file name with the base given by fig_name and the extension given by fmt. Parameters ---------- fig_name : str base name string fmt : str extension of the figure (e.g. png, pdf, eps) Returns -------- filename : str a string of the form "fig_name.fmt" Example ------- set_file_name("figure","jpg") returns "figure.jpg" """ if not isinstance(fig_name, str): raise TypeError("fig_name must be a string.") if not isinstance(fmt, str): raise TypeError("fmt must be a string.") if len(fig_name) == 0: raise ValueError("fig_name must contain at least one character.") if len(fmt) == 0: raise ValueError("fmt must contain at least one character.") filename = fig_name + "." + fmt return filename ####################
def check_integer(num): """Devuelve True si el string empieza por "-" y su longitud es mayor que 1.""" if num.startswith('-') and len(num) > 1: return True
def list_tokenizer(tokenizer, text_list): """Split train dataset corpus to list """ line_list = list() for text in text_list: line_list.append(tokenizer.tokenize(text)) return line_list
def fuel_requirement(module_mass): """ Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. Repeat this for the weight of the fuel until the added weight is 0. :param module_mass: :return: fuel_requirement """ total = 0 current_mass = module_mass while (current_mass // 3 - 2) > 0: current_mass = current_mass // 3 - 2 total += current_mass return total
def blue(message): """ blue color :return: str """ return f"\x1b[34;1m{message}\x1b[0m"
def remove_comments(text: str) -> str: """Remove comments from a JSON string.""" return "\n".join( line for line in text.split("\n") if not line.strip().startswith("//") )
def char_to_info(kind): """ How to represent entry in gopher directory in control column. """ return {'i': " ", '0': "TEXT ", '1': " DIR "}.get(kind, "?[{}] ".format(kind))
def promote_xyz(a): """ Add a 'z' coordinate to each xy pair """ for p in a: p.append(1.0-p[0]-p[1]) return a
def ARRAY_ELEM_AT(array, idx): """ Returns the element at the specified array index. See https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/ for more details :param array: An expression that can be any valid expression as long as it resolves to an array. :param idx: An expression can be any valid expression as long as it resolves to an integer. :return: Aggregation operator """ return {'$arrayElemAt': [array, idx]}
def extract(ref: str, hyp: str) -> list: """ This function extracts identifiable ambiguities. Only ambiguities within the equal amount of words in both reference and hypothesis are processed. Then the code tries to find boundaries of error string, as it subtracts common prefix and suffix of words. If length of both error and correction is > 7, it will not be loaded by Tesseract OCR (search for MAX_AMBIG_SIZE constant in Tesseract source code). :param ref: reference string :param hyp: hypothesis string :return: list of tuples, where each tuple contains error and correction """ ref_words = ref.split() hyp_words = hyp.split() ambiguities = [] if len(ref_words) == len(hyp_words): # Equal amount of words means ambiguity(-ies) is within one word for rw, hw in zip(ref_words, hyp_words): if rw != hw: error = hw correction = rw # Remove common prefix while len(error) > 1 and len(correction) > 1 and error[0] == correction[0]: error = error[1:] correction = correction[1:] # Remove common suffix while len(error) > 1 and len(correction) > 1 and error[-1] == correction[-1]: error = error[:-1] correction = correction[:-1] # Store results ambiguities.append((error, correction)) return ambiguities
def find_cfn_output(key, outputs): """Return CFN output value.""" for i in outputs: if i['OutputKey'] == key: return i['OutputValue'] return None
def version_key(ver): """ A key function that takes a version and returns a numeric value that can be used for sorting >>> version_key('2') 2000000 >>> version_key('2.9') 2009000 >>> version_key('2.10') 2010000 >>> version_key('2.9.1') 2009001 >>> version_key('2.9.1.1') 2009001 >>> version_key('2.9B') Traceback (most recent call last): ... ValueError: invalid literal for int() ... """ padded = ver + '.0.0' values = padded.split('.') return int(values[0]) * 1000000 + int(values[1]) * 1000 + int(values[2])
def get_benchmark_repetition_count(runner: str) -> int: """Returns the benchmark repetition count for the given runner.""" if runner == "iree-vmvx": # VMVX is very unoptimized for now and can take a long time to run. # Decrease the repetition for it until it's reasonably fast. return 3 return 10
def unicode(word): """Only takes in a string without digits""" assert type(word) is str try: int(word) except ValueError: return sum(map(ord, word)) raise ValueError(f"Word {word} contains integer(s)")
def parenthesise(_value): """Adds a parenthesis around a values.""" return '(' + _value + ')'
def default_memnet_embed_fn_hparams(): """Returns a dictionary of hyperparameters with default hparams for :func:`~texar.tf.modules.memory.default_embed_fn` .. code-block:: python { "embedding": { "dim": 100 }, "temporal_embedding": { "dim": 100 }, "combine_mode": "add" } Here: "embedding": dict, optional Hyperparameters for embedding operations. See :meth:`~texar.tf.modules.WordEmbedder.default_hparams` of :class:`~texar.tf.modules.WordEmbedder` for details. If `None`, the default hyperparameters are used. "temporal_embedding": dict, optional Hyperparameters for temporal embedding operations. See :meth:`~texar.tf.modules.PositionEmbedder.default_hparams` of :class:`~texar.tf.modules.PositionEmbedder` for details. If `None`, the default hyperparameters are used. "combine_mode": str Either **'add'** or **'concat'**. If 'add', memory embedding and temporal embedding are added up. In this case the two embedders must have the same dimension. If 'concat', the two embeddings are concated. """ return { "embedding": { "dim": 100 }, "temporal_embedding": { "dim": 100 }, "combine_mode": "add" }
def get_place_coords(location): """ Parses a geo coord in the form of (latitude,longitude) and returns them as an array. Note that a simple "latitude,longitude" is also valid as a coordinate set """ latitude, longitude = map(float, location.strip('()[]').split(',')) return [latitude, longitude]
def sec2hmsc(secs): """ convert seconds to (hours, minutes, seconds, cseconds) secs:float -> (int, int, int, int) """ hours, rem = divmod(secs, 3600) # extract hours minutes, rem = divmod(rem, 60) # extract minutes seconds, cseconds = divmod(rem*100, 100) # extract seconds, cseconds return (int(hours), int(minutes), int(seconds), int(cseconds))
def coerce(string): """Changing strict JSON string to a format that satisfies eslint""" # Double quotes to single quotes coerced = string.replace("'", r"\'").replace("\"", "'") # Spaces between brace and content coerced = coerced.replace('{', '{ ').replace('}', ' }') return coerced
def make_empty_table(row_count, column_count): """ Make an empty table Parameters ---------- row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell will be an empty str ('') """ table = [] while row_count > 0: row = [] for column in range(column_count): row.append('') table.append(row) row_count -= 1 return table
def eggs(number): """Function to request your preferred number of eggs for breakfast. Parameters ---------- number : int The number of eggs you'd like for breakfast. Returns ------- str A polite request for your desired number of eggs. """ result = "{} eggs, please!".format(number) return result
def match_cases(original, replacement): """ Returns a copy of the replacement word with the cases altered to match the original word's case Only supports upper case, capitalised (title) and lower case - everything else gets lower cased by default""" if original.isupper(): return replacement.upper() if original.istitle(): return replacement.title() return replacement
def rev_comp(seq: str) -> str: """ Returns reverse complementary sequence of the input DNA string """ comp = { 'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N', 'M': 'K', # M = A C 'K': 'M', # K = G T 'R': 'Y', # R = A G 'Y': 'R', # Y = C T 'S': 'S', # S = C G 'W': 'W', # W = A T 'B': 'V', # B = C G T 'V': 'B', # V = A C G 'D': 'H', # D = A G T 'H': 'D', # H = A C T 'a': 't', 'c': 'g', 'g': 'c', 't': 'a', 'n': 'n', 'm': 'k', 'k': 'm', 'r': 'y', 'y': 'r', 's': 's', 'w': 'w', 'b': 'v', 'v': 'b', 'd': 'h', 'h': 'd' } return ''.join([comp[base] for base in seq[::-1]])
def _is_sunder(name): """ A copy of enum._is_sunder from Python 3.6. Returns True if a _sunder_ (single underscore) name, False otherwise. """ return (len(name) > 2 and name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_')
def LeapYear(year): """Leapyear returns 1 if year is a leap year and 0 otherwise. Note that leap years famously fall on all years that divide by 4 except those that divide by 100 but including those that divide by 400.""" if year%4: return 0 elif year%100: return 1 elif year%400: return 0 else: return 1
def process_anno(anno_scaled, base=0, window_radius=16000000): """ Process annotations to the format used by Orca plotting functions such as `genomeplot` and `genomeplot_256Mb`. Parameters ---------- anno_scaled : list(list(...)) List of annotations. Each annotation can be a region specified by `[start: int, end: int, info:str]` or a position specified by `[pos: int, info:str]`. Acceptable info strings for region currently include color names for matplotlib. Acceptable info strings for position are currently 'single' or 'double', which direct whether the annotation is drawn by single or double lines. base : int The starting position of the 32Mb (if window_radius is 16000000) or 256Mb (if window_radius is 128000000) region analyzed. window_radius : int The size of the region analyzed. It must be either 16000000 (32Mb region) or 128000000 (256Mb region). Returns ------- annotation : list Processed annotations with coordinates transformed to relative coordinate in the range of 0-1. """ annotation = [] for r in anno_scaled: if len(r) == 3: annotation.append( [(r[0] - base) / (window_radius * 2), (r[1] - base) / (window_radius * 2), r[2],] ) elif len(r) == 2: annotation.append([(r[0] - base) / (window_radius * 2), r[1]]) else: raise ValueError return annotation
def validate_capacity(capacity): """ Validate ScalingConfiguration capacity for serverless DBCluster Property: ScalingConfiguration.MaxCapacity Property: ScalingConfiguration.MinCapacity """ VALID_MYSQL_SCALING_CONFIGURATION_CAPACITIES = (1, 2, 4, 8, 16, 32, 64, 128, 256) VALID_POSTGRESL_SCALING_CONFIGURATION_CAPACITIES = (2, 4, 8, 16, 32, 64, 192, 384) if ( capacity not in VALID_POSTGRESL_SCALING_CONFIGURATION_CAPACITIES and capacity not in VALID_MYSQL_SCALING_CONFIGURATION_CAPACITIES ): raise ValueError( "ScalingConfiguration capacity must be one of: {}".format( ", ".join( map( str, VALID_MYSQL_SCALING_CONFIGURATION_CAPACITIES + VALID_POSTGRESL_SCALING_CONFIGURATION_CAPACITIES, ) ) ) ) return capacity
def expose(fn): """ Decorator function that exposes methods of a web application to the web server. Use infront of functions that you wish to expose """ if fn: fn.exposed = True return fn
def isFloat( obj ): """ Returns a boolean whether or not 'obj' is of type 'float'. """ return isinstance( obj, float )
def NeedEnvFileUpdateOnWin(changed_keys): """Returns true if environment file need to be updated.""" # Following GOMA_* are applied to compiler_proxy not gomacc, # you do not need to update environment files. ignore_envs = ( 'GOMA_API_KEY_FILE', 'GOMA_DEPS_CACHE_DIR', 'GOMA_HERMETIC', 'GOMA_RPC_EXTRA_PARAMS', 'GOMA_ALLOWED_NETWORK_ERROR_DURATION' ) for key in changed_keys: if key not in ignore_envs: return True return False
def return_parent_label(label_name): """ Example: Input: /education/department Output: /education """ if label_name.count('/') > 1: return label_name[0:label_name.find('/', 1)] return label_name
def remove_dash_lines(value): """Some social media values are '---------'""" return None if value[:2] == '--' else value
def _antnums_to_bl(antnums): """ Convert tuple of antenna numbers to baseline integer. A baseline integer is the two antenna numbers + 100 directly (i.e. string) concatenated. Ex: (1, 2) --> 101 + 102 --> 101102. Parameters ---------- antnums : tuple tuple containing integer antenna numbers for a baseline. Ex. (ant1, ant2) Returns ------- bl : <i6 integer baseline integer """ # get antennas ant1 = antnums[0] + 100 ant2 = antnums[1] + 100 # form bl bl = int(ant1*1e3 + ant2) return bl
def unpack_bitstring(string): """ Creates bit array out of a string :param string: The modbus data packet to decode example:: bytes = 'bytes to decode' result = unpack_bitstring(bytes) """ byte_count = len(string) bits = [] for byte in range(byte_count): value = int(string[byte]) for _ in range(8): bits.append((value & 1) == 1) value >>= 1 return bits
def trunc(s, chars): """ Trucante string at ``n`` characters. This function hard-trucates a string at specified number of characters and appends an elipsis to the end. The truncating does not take into account words or markup. Elipsis is not appended if the string is shorter than the specified number of characters. :: >>> trunc('foobarbaz', 6) 'foobar...' .. note:: Keep in mind that the trucated string is always 3 characters longer than ``n`` because of the appended elipsis. """ if len(s) <= chars: return s return s[:chars] + '...'
def u_2_u10(u_meas,height): """ % u10 = calc_u10(umeas,hmeas) % % USAGE:------------------------------------------------------------------- % % [u10] = u_2_u10(5,4) % % >u10 = 5.5302 % % DESCRIPTION:------------------------------------------------------------- % Scale wind speed from measurement height to 10 m height % % INPUTS:------------------------------------------------------------------ % umeas: measured wind speed (m/s) % hmeas: height of measurement (m) % % OUTPUTS:----------------------------------------------------------------- % % u10: calculated wind speed at 10 m % % REFERENCE:--------------------------------------------------------------- % % Hsu S, Meindl E A and Gilhousen D B (1994) Determining the Power-Law % Wind-Profile Exponent under Near-Neutral Stability Conditions at Sea % J. Appl. Meteor. 33 757-765 % % AUTHOR:--------------------------------------------------------------- % David Nicholson - Adapted from calc_u10.m by Cara Manning % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% """ u10 = u_meas * (10.0 / height)**0.11 return u10
def _resolve_none(inp): """ Helper function to allow 'None' as input from argparse """ if inp == "None": return return inp
def are_all_strings_in_text(text, list_of_strings): """Check that all strings in list_of_strings exist in text Parameters ---------- text : str output from IQDMPDF.pdf_reader.convert_pdf_to_text list_of_strings : list of str a list of strings used to identify document type Returns ---------- bool Returns true if every string in list_of_strings is found in text data """ for str_to_find in list_of_strings: if str_to_find not in text: return False return True
def _process_transcript(transcripts, x): """ Helper method to split into words. Args: transcripts: x: Returns: """ extracted_transcript = transcripts[x].split('(')[0].strip("<s>").split('<')[0].strip().upper() return extracted_transcript
def code(text): """Returns a text fragment (tuple) that will be displayed as code.""" return ('code', text)