content
stringlengths
42
6.51k
def prime_factors(n): """ Return the prime factors of the given number. """ # < 1 is a special case if n <= 1: return [1] factors = [] lastresult = n while True: if lastresult == 1: break c = 2 while True: if lastresult % c == 0: break c += 1 factors.append(c) lastresult /= c return factors
def make_header(in_files,args): """Make sam header given input file species and""" #parse input barcode file and make list of individuals in_files['header'] = 'location of header' return in_files
def _validate_print_table(tuple_list: list, col_headers: tuple) -> int: """Validate arguments on behalf of _print_table() and returns number of columns.""" # LOCAL VARIABLES num_columns = 0 # Number of columns detected # INPUT VALIDATION # tuple_list if not isinstance(tuple_list, list): raise TypeError(f'The tuple_list argument must of type list instead of {type(tuple_list)}') if not tuple_list: raise ValueError('The tuple_list argument can not be empty') # tuple_list entries num_columns = len(tuple_list[0]) # Check all entries against the length of the first for entry in tuple_list: if not isinstance(entry, tuple): raise TypeError(f'Found an invalid tuple_list entry of type {type(entry)}') if len(entry) != num_columns: raise ValueError('Tuple entries are not a standard length') # col_headers if not isinstance(col_headers, tuple): raise TypeError('The col_headers argument must of type tuple instead of ' f'{type(col_headers)}') for entry in col_headers: if not isinstance(entry, str): raise TypeError(f'Found an invalid col_headers entry of type {type(entry)}') if len(col_headers) != num_columns: raise ValueError('The col_headers argument does not match the length of the tuples') # DONE return num_columns
def make_dices(tup): """Make a string with comma separated dice values from tuple. From a given tuple, dice values are written in a string separated by ',' Arguments: tup: (tuple) Tuple with dice values Returns: string: (str) string with dice values separated by comma Examples: >>> make_dices((1, 3)) '1,3' >>> make_dices((5, 6)) '5,6' Only tuple allowed: >>> make_dices('4,7') Traceback (most recent call last): TypeError: Only tuples allowed, not <class 'str'> Only integer values allowed in tuple: >>> make_dices((1.5, 3)) Traceback (most recent call last): TypeError: Only integer values allowed, not 1.5 Only integer values between 1 and 6 allowed: >>> make_dices((3, 5, 8)) Traceback (most recent call last): ValueError: Only values between 1 and 6 allowed, not 8 """ if not type(tup) == tuple: raise TypeError('Only tuples allowed, not ' + str(type(tup))) for number in tup: if not type(number) == int: raise TypeError('Only integer values allowed, not ' + str(number)) if number < 1 or number > 6: raise ValueError(f'Only values between 1 and 6 allowed, not {number:d}') string = ','.join(str(number) for number in tup) return string
def value_approximation(value_a: float, value_b: float, value_threshold: float) -> bool: """Compare two numbers to check if they are roughly the same. Args: value_a (float): First number. value_b (float): Second number. value_threshold (float): Approximation threshold. Returns: bool: Whether or not the numbers are the same. """ position = round(value_a/float(value_b), 1) flag = True if position >= ( 1-value_threshold) and position <= (1+value_threshold) else False return flag
def ring_level(num): """Return the side lenth, level, and max value of a spiral ring of consecutive ints""" max_value = 1 level = 0 side_len = 1 while max_value < num: level = level + 1 side_len = (level * 2) + 1 max_value = side_len + side_len * (side_len - 1) return side_len, level, max_value
def count_restricted_partitions(n, m, l): """ Returns the number of partitions of n into m or less parts """ if n == 0: return 1 elif l == 0: return 0 elif m == 0: return 0 return sum(count_restricted_partitions(n - i, m - 1, i) for i in range(1, min(n, l) + 1))
def _get_column_property_display_data(row, col_str, data): """ This function is used to get the columns data. :param row: :param col_str: :param data: :return: """ if row['collnspname']: col_str += ' COLLATE ' + row['collnspname'] if row['opcname']: col_str += ' ' + row['opcname'] # ASC/DESC and NULLS works only with btree indexes if 'amname' in data and data['amname'] == 'btree': # Append sort order col_str += ' ' + row['options'][0] # Append nulls value col_str += ' ' + row['options'][1] return col_str
def split_string(x, separator=' '): """ Quick function to tidy up lines in an ASCII file (split on spaces and strip consecutive spaces). Parameters ---------- x : str String to split. separator : str, optional Give a separator to split on. Defaults to space. Returns ------- y : list The split string. """ return [i.strip() for i in x.split(separator) if i.strip()]
def prior(theta, parameter_intervals): """ Very simple prior estimator only for MH as it checks if the parametrisation is inside of respective domain or not. This simulates uniform distribution. Args: theta: (tuple): parameter point parameter_intervals (list of pairs): parameter domains, (min, max) Returns: 1 for all parametrisations inside the parameter space 0 otherwise @author: xhajnal """ for index, value in enumerate(theta): ## If inside of param domains if (theta[index] < parameter_intervals[index][0]) or (theta[index] > parameter_intervals[index][1]): return 0 return 1
def get_channel_for_utt(flist, ch, utt): """ Returns a specific channel for one utterance. Raises a KeyError if the channel does not exist :param flist: A dict representing a file list, i.e. the keys are the utt ids :param ch: The channel to fetch (i.e. X/CH1). Separator must be `/` :param utt: The utterance to fetch :return: Path to the file """ val = flist[utt] for branch in ch.split('/'): if branch in val: val = val[branch] else: raise KeyError('No channel {} for {}'.format(ch, utt)) return val
def jwt_response_payload_handler(token, user=None, request=None): """ Custom response payload handler. This function controlls the custom payload after login or token refresh. This data is returned through the web API. """ return { 'token': token, }
def turn_list_to_int(list_): """converts elements of a list to integer""" list_ = [int(i) for i in list_] return list_
def list_to_dict(items, value): """ Converts a list into a dict. """ key = items.pop() result = {} bracket_index = key.find('[') if bracket_index > 0: value = [value] result[key] = value if items: result = list_to_dict(items, result) return result
def get_user_parameters_string(data): """Returns the UserParameters string in a given data object. :type data: dict :param data: data object in a CodePipeline event. :rtype: dict :return: UserParameters string in ``data``. :raises KeyError: if ``data`` does not have a necessary property. """ return data['actionConfiguration']['configuration']['UserParameters']
def check_constraints(param_constraints): """Checks whether user provided list specifying which parameters are to be free versus fixed is in proper format, and assigns default values where necessary. Keyword arguments: param_constraints -- specifies which parameters to estimate (list) """ if param_constraints is None: # If no parameter constraints provided, set default values to # [alpha = True, beta = True, gamma = False, lambda = True] param_constraints = [True, True, False, False] elif param_constraints is not None: # Check whether the variable for the parameter constraints provided is of type list if isinstance(param_constraints, list) is False: raise ValueError('''User Error: Please provide a argument of type list indicating which parameters of the model are free (i.e., TRUE) versus fixed (i.e., FALSE).''') # Check whether arguments in list are of type boolean for i in param_constraints: if isinstance(i, bool) is False: raise ValueError('''User Error: Please provide boolean arguments for parameter ' constraints (i.e., free vs fixed) of the model.''') # Check number of arguments provided and set the remaining arguments to default values. if len(param_constraints) < 2: raise ValueError('''User Error: Please provide at least two constraints (scale; slope) for parameters of the model.''') elif len(param_constraints) == 2: print('Setting parameter constraints for gamma and lambda to default values (i.e., fixed)!') param_constraints.append(False) param_constraints.append(True) elif len(param_constraints) == 3: print('Setting parameter constraints for lambda to default value (i.e., fixed)!') param_constraints.append(True) elif len(param_constraints) > 4: raise ValueError('''User Error: More than 4 constraints for parameters of the model provided!''') return param_constraints
def objective(s, s_min=100): """ minimum is reached at s=s_min """ return -0.5 * ((s - s_min) ** 2)
def random_morphing_points(n_thetas, priors): """ Utility function to be used as input to various SampleAugmenter functions, specifying random parameter points sampled from a prior in a morphing setup. Parameters ---------- n_thetas : int Number of parameter points to be sampled priors : list of tuples Priors for each parameter is characterized by a tuple of the form `(prior_shape, prior_param_0, prior_param_1)`. Currently, the supported prior_shapes are `flat`, in which case the two other parameters are the lower and upper bound of the flat prior, and `gaussian`, in which case they are the mean and standard deviation of a Gaussian. Returns ------- output : tuple Input to various SampleAugmenter functions """ return "random_morphing_points", (n_thetas, priors)
def _field_index(header, field_names, index): """Determine a field index. If the index passed is already a valid index, that index is returned. Otherwise, the header is searched for a field name matching any of the passed field names, and the index of the first one found is returned. If no matching field can be found, a ValueError is raised. """ if index > -1: return index for index, value in enumerate(header): if value in field_names: print(f'Detected field \'{value}\' at index {index}') return index expected_names = ', '.join(field_names) raise ValueError(f'No header field is named any of {expected_names}')
def _get_deconv_pad_outpad(deconv_kernel): """Get padding and out padding for deconv layers.""" if deconv_kernel == 4: padding = 1 output_padding = 0 elif deconv_kernel == 3: padding = 1 output_padding = 1 elif deconv_kernel == 2: padding = 0 output_padding = 0 else: raise ValueError(f"Not supported num_kernels ({deconv_kernel}).") return deconv_kernel, padding, output_padding
def to_readable_dept_name(dept_name): """Converts a department acronym into the full name Arguments: dept_name {String} -- The department acronym Returns: String -- The department's full name """ depts = ['TWS', 'BIOL', 'RSM', 'MUS', 'COMM', 'ECON', 'CHIN', 'NENG', 'CGS', 'LAWS', 'USP', 'ETHN', 'EDS', 'BENG', 'LING', 'SOC', 'RELI', 'VIS', 'FPMU', 'HUM', 'PSYC', 'PHIL', 'STPA', 'COGS', 'ECE', 'ANTH', 'CENG', 'MATH', 'INTL', 'CHEM', 'ICAM', 'SIO', 'THEA', 'HIST', 'PHYS', 'JUDA', 'LATI', 'POLI', 'ESYS', 'CSE', 'LIT', 'JAPN', 'HDP', 'MAE', 'ENVR', 'SE'] readable = ['3rd\nWorld\nStudies', "Biology", "Rady\nSchool\nof Mgmt", "Music", "Communi-\ncations","Economics","Chinese","Nano\nEngineering","Gender\nStudies", "Law", "Urban\nStudies","Ethnic\nStudies","Education\nStudies", "Biology\nEngineering", "Linguistics", "Sociology", "Religion", "Visual\nArts", "Medicine", "Humanities", "Psychology", "Phil-\nosophy", "Sci-tech\nPublic\nAffairs", "Cognitive\nScience", "ECE", "Anthro-\npology", "Chemical\nEngineering", "Math", "Inter-\nnational\nStudies", "Chemistry", "Comp.\nArts", "Scripps\nOceanography", "Theatre","History","Physics","Judaic\nStudies", "Latin\nAmerican\nStudies", "Political\nScience", "Environmental\nSystems","CSE","Liter-\nature", "Japanese", "Human\nDev.", "Mech. &\nAero.\nEngineering", "Environmental\nStudies", "Structural\nEngineering"] convert_dict = {depts[i]:readable[i] for i in range(len(depts))} return convert_dict[dept_name]
def np_bitwise_maj (x, y, z): """ Bitwise MAJ function """ return (x & y) | (x & z) | (y & z)
def is_prime(n): """ Return True if the given integer is prime, False otherwise. >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(9) False >>> is_prime(10) False """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, n): if n % i == 0: return False return True
def _extract_conflict_packages(license_service_output): """Extract conflict licenses. This helper function extracts conflict licenses from the given output of license analysis REST service. It returns a list of pairs of packages whose licenses are in conflict. Note that this information is only available when each component license was identified ( i.e. no unknown and no component level conflict ) and there was a stack level license conflict. :param license_service_output: output of license analysis REST service :return: list of pairs of packages whose licenses are in conflict """ license_conflict_packages = [] if not license_service_output: return license_conflict_packages conflict_packages = license_service_output.get('conflict_packages', []) for conflict_pair in conflict_packages: list_pkgs = list(conflict_pair.keys()) assert len(list_pkgs) == 2 d = { "package1": list_pkgs[0], "license1": conflict_pair[list_pkgs[0]], "package2": list_pkgs[1], "license2": conflict_pair[list_pkgs[1]] } license_conflict_packages.append(d) return license_conflict_packages
def job_ids(log_stream): """Grep out all lines with scancel example.""" id_rows = [line for line in log_stream if 'scancel' in line] jobs = [id_row.strip()[-7:-1] for id_row in id_rows] return jobs
def _fix_name(name): """Clean up descriptive names""" return name.strip('_ ')
def to_locale(language, to_lower=False): """ Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us). """ p = language.find('-') if p >= 0: if to_lower: return language[:p].lower() + '_' + language[p + 1:].lower() else: # Get correct locale for sr-latn if len(language[p + 1:]) > 2: return language[:p].lower() + '_' + language[p + 1].upper() + language[p + 2:].lower() return language[:p].lower() + '_' + language[p + 1:].upper() else: return language.lower()
def comma_list_to_hex(cpus): """ Converts a list of cpu cores in corresponding hex value of cpu-mask """ cpu_arr = cpus.split(",") binary_mask = 0 for cpu in cpu_arr: binary_mask = binary_mask | (1 << int(cpu)) return format(binary_mask, '02x')
def _format_stages_summary(stage_results): """ stage_results (list of (tuples of (success:boolean, stage_name:string, status_msg:string))) returns a string of a report, one line per stage. Something like: Stage: <stage x> :: SUCCESS Stage: <stage y> :: FAILED Stage: <stage z> :: SUCCESS """ #find the longest stage name to pad report lines max_name_len = 0 for entry in stage_results: x, stage_name, y = entry name_len = len(stage_name) if name_len > max_name_len: max_name_len = name_len summary = "" for entry in stage_results: x, stage_name, status_msg = entry summary += 'Stage: ' + stage_name.ljust(max_name_len) + ":: " summary += status_msg + '\n' return summary
def str2tuple(string, sep=","): """ Map "1.0,2,0" => (1.0, 2.0) """ tokens = string.split(sep) # if len(tokens) == 1: # raise ValueError("Get only one token by " + # f"sep={sep}, string={string}") floats = map(float, tokens) return tuple(floats)
def is_sane_slack_webhook(url): """Really basic sanity checking.""" if url is None: return False return "https://hooks.slack.com/" in url.strip()
def is_cybox(entity): """Returns true if `entity` is a Cybox object""" try: return entity.__module__.startswith("cybox.") except AttributeError: return False
def is_pal(test): """ Returns bool of whether test is a palindrome. Does so iteratively """ # Reverse the test reverse_test = test[::-1] # Loop through to test test against reverse for i in range(len(test)): if test[i] != reverse_test[i]: return False return True
def solution(n): """Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 """ answer = 0 for i in range(999, 99, -1): # 3 digit nimbers range from 999 down to 100 for j in range(999, 99, -1): t = str(i * j) if t == t[::-1] and i * j < n: answer = max(answer, i * j) return answer
def processObjectListWildcards(objectList, suffixList, myId): """Replaces all * wildcards with n copies that each have appended one element from the provided suffixList and replaces %id wildcards with myId ex: objectList = [a, b, c_3, d_*, e_%id], suffixList=['0', '1', '2'], myId=5 => objectList = [a, b, c_3, e_5, d_0, d_1, d_2] :objectList: list of objects :suffixList: list of strings that are going to be appended to each object that has the * wildcard :myId: string used to replace '%id' wildcard :returns: the new list""" # we iterate over a copy of the object list (in order to modify it) for item in objectList[:]: if ('*' in item): # append the new items for suffix in suffixList: objectList.append(item.replace("*", suffix)) # delete the item that contains the wildcards objectList.remove(item) if ('%id' in item): # replace the id wildcard with the id parameter objectList.append(item.replace("%id", myId)) # delete the item that contains the '%id' wildcard objectList.remove(item) return objectList
def _validate_manifest_upload(expected_objs, upload_results): """ Given a list of expected object names and a list of dictionaries of `SwiftPath.upload` results, verify that all expected objects are in the upload results. """ uploaded_objs = { r['object'] for r in upload_results if r['success'] and r['action'] in ('upload_object', 'create_dir_marker') } return set(expected_objs).issubset(uploaded_objs)
def int_convert_to_minute(value): """Convert value into min & sec >>> int_convert_to_minute(123) '02:03' """ min = int(int(value) / 60) sec = int(int(value) % 60) return "%02d" % min + ":" + "%02d" % sec
def empty_1d_array(size, fill_default=None): """ Create and return 1-D array :param size: :param fill_default: Default value to be filled in cells. :return: """ return [fill_default] * size
def get_color(score: float) -> str: """Return a colour reference from a pylint score""" colors = { "brightgreen": "#4c1", "green": "#97CA00", "yellow": "#dfb317", "yellowgreen": "#a4a61d", "orange": "#fe7d37", "red": "#e05d44", "bloodred": "#ff0000", "blue": "#007ec6", "grey": "#555", "gray": "#555", "lightgrey": "#9f9f9f", "lightgray": "#9f9f9f", } if score > 9: return colors["brightgreen"] if score > 8: return colors["green"] if score > 7.5: return colors["yellowgreen"] if score > 6.6: return colors["yellow"] if score > 5.0: return colors["orange"] if score > 0.00: return colors["red"] return colors["bloodred"]
def create_dict(entities): """Create the html5 dict from the decoded json object.""" new_html5 = {} for name, value in entities.items(): new_html5[name.lstrip('&')] = value['characters'] return new_html5
def only_alpha(tokens): """ Exclude non-alphanumeric tokens from a list of tokens """ tokens = [token for token in tokens if token.isalpha()] return tokens
def map_quads(coord): """ Map a quadrant number to Moran's I designation HH=1, LH=2, LL=3, HL=4 Input: @param coord (int): quadrant of a specific measurement Output: classification (one of 'HH', 'LH', 'LL', or 'HL') """ if coord == 1: return 'HH' elif coord == 2: return 'LH' elif coord == 3: return 'LL' elif coord == 4: return 'HL' else: return None
def try_parse_int(candidate): """ Convert the given candidate to int. If it fails None is returned. Example: >>> type(try_parse_int(1)) # int will still be int <class 'int'> >>> type(try_parse_int("15")) <class 'int'> >>> print(try_parse_int("a")) None Args: candidate: The candidate to convert. Returns: Returns the converted candidate if convertible; otherwise None. """ try: return int(candidate) except (ValueError, TypeError): return None
def generate_label_asm(label, address): """ Return label definition text at a given address. Format: '{label}: ; {address}' """ label_text = '%s: ; %x' % (label, address) return (address, label_text, address)
def suffix_replace(original, old, new): """ Replaces the old suffix of the original string by a new suffix """ return original[:-len(old)] + new
def cleanup_code(content: str) -> str: """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith("```") and content.endswith("```"): return "\n".join(content.split("\n")[1:-1]) # remove `foo` return content.strip("` \n")
def quote_string(prop): """Wrap given prop with quotes in case prop is a string. RedisGraph strings must be quoted. """ if not isinstance(prop, str): return prop if prop[0] != '"': prop = '"' + prop if prop[-1] != '"': prop = prop + '"' return prop
def _iszero(x): """Returns True if x is zero.""" return getattr(x, 'is_zero', None)
def int_to_bytes(x): """Changes an unsigned integer into bytes.""" return x.to_bytes((x.bit_length() + 7) // 8, 'big')
def process_entries(entries): """ Ignore empty lines, comments and editable requirements :param list entries: List of entries :returns: mapping from a project to its version specifier :rtype: dict """ data = {} for e in entries: e = e.strip() if e and not e.startswith('#') and not e.startswith('-e'): # Support for <= was added as part of # https://github.com/certbot/certbot/pull/8460 because we weren't # able to pin a package to an exact version. Normally, this # functionality shouldn't be needed so we could remove it in the # future. If you do so, make sure to update other places in this # file related to this behavior such as this file's docstring. for comparison in ('==', '<=',): parts = e.split(comparison) if len(parts) == 2: project_name = parts[0] version = parts[1] data[project_name] = comparison + version break else: raise ValueError("Unexpected syntax '{0}'".format(e)) return data
def create_result(flags): """ Create the correct return value for YCM. :param flags: The flags for the requested file. :type flags: list[str] :rtype: dict[str,object] :return: A dictionary in the format wanted by YCM. """ return {"flags": flags}
def is_parans_exp(istr): """ Determines if an expression is a valid function "call" """ fxn = istr.split('(')[0] if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')': return False plevel = 1 for c in '('.join(istr[:-1].split('(')[1:]): if c == '(': plevel += 1 elif c == ')': plevel -= 1 if plevel == 0: return False return True
def parsed_length(line: str) -> int: """The length of the string after evaluating.""" return len(eval(line))
def findMinWidth(list): """ Finds and returns the length of the longest string in list Parameter: (list) containing strings Return: (int) length of longest string in list """ longest = "" for item in list: item = str(item) # Can't use len() on int if len(longest) < len(item): longest = item return len(longest)
def _bytearray_comparator(a, b): """Implements a comparator using the lexicographical ordering of octets as unsigned integers.""" a_len = len(a) b_len = len(b) i = 0 while i < a_len and i < b_len: a_byte = a[i] b_byte = b[i] if a_byte != b_byte: if a_byte - b_byte < 0: return -1 else: return 1 i += 1 len_diff = a_len - b_len if len_diff < 0: return -1 elif len_diff > 0: return 1 else: return 0
def split_data(line): """ Split each line into columns """ data = str.split(line, ',') return [data[0], data[1]]
def count_possibilities(dic): """ Counts how many unique names can be created from the combinations of each lists contained in the passed dictionary. """ total = 1 for key, value in dic.items(): total *= len(value) return total
def parse_addr(addrstr): """ parse 64 or 32-bit address from string into int """ if addrstr.startswith('??'): return 0 return int(addrstr.replace('`', ''), 16)
def nacacode4(tau, maxthickpt, camb): """Converts airfoil parameters to 4-digit naca code :param tau: maximum thickness as percent of chord :type tau: float :param maxthickpt: Location of maximum thickness as percent of chord :type maxthickpt: float :param camb: max camber as a percentage of chord :type camb: float :returns: string 4 digit naca code .. note:: Non-integer values will be rounded to the nearest percent. maxthick is rounded to the nearest tens of percent. """ nc = round(tau) if(camb > 0): nc += 100*round(maxthickpt, -1)/10 nc += 1000*round(camb) return '%04d' % int(nc)
def _levenshtein_compute(source, target, rd_flag): """Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using the Wagner-Fischer algorithm (https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm). These distances are defined recursively, since the distance between two strings is just the cost of adjusting the last one or two characters plus the distance between the prefixes that exclude these characters (e.g. the distance between "tester" and "tested" is 1 + the distance between "teste" and "teste"). The Wagner-Fischer algorithm retains this idea but eliminates redundant computations by storing the distances between various prefixes in a matrix that is filled in iteratively. """ # Create matrix of correct size (this is s_len + 1 * t_len + 1 so that the # empty prefixes "" can also be included). The leftmost column represents # transforming various source prefixes into an empty string, which can # always be done by deleting all characters in the respective prefix, and # the top row represents transforming the empty string into various target # prefixes, which can always be done by inserting every character in the # respective prefix. The ternary used to build the list should ensure that # this row and column are now filled correctly s_range = range(len(source) + 1) t_range = range(len(target) + 1) matrix = [[(i if j == 0 else j) for j in t_range] for i in s_range] # Iterate through rest of matrix, filling it in with Levenshtein # distances for the remaining prefix combinations for i in s_range[1:]: for j in t_range[1:]: # Applies the recursive logic outlined above using the values # stored in the matrix so far. The options for the last pair of # characters are deletion, insertion, and substitution, which # amount to dropping the source character, the target character, # or both and then calculating the distance for the resulting # prefix combo. If the characters at this point are the same, the # situation can be thought of as a free substitution del_dist = matrix[i - 1][j] + 1 ins_dist = matrix[i][j - 1] + 1 sub_trans_cost = 0 if source[i - 1] == target[j - 1] else 1 sub_dist = matrix[i - 1][j - 1] + sub_trans_cost # Choose option that produces smallest distance matrix[i][j] = min(del_dist, ins_dist, sub_dist) # If restricted Damerau-Levenshtein was requested via the flag, # then there may be a fourth option: transposing the current and # previous characters in the source string. This can be thought of # as a double substitution and has a similar free case, where the # current and preceeding character in both strings is the same if rd_flag and i > 1 and j > 1 and source[i - 1] == target[j - 2] \ and source[i - 2] == target[j - 1]: trans_dist = matrix[i - 2][j - 2] + sub_trans_cost matrix[i][j] = min(matrix[i][j], trans_dist) # At this point, the matrix is full, and the biggest prefixes are just the # strings themselves, so this is the desired distance return matrix[len(source)][len(target)]
def img_pred(path): """Sends a path to an image to the classifier, should return a JSON object.""" if path == "https://michelangelostestbucket.s3.us-west-2.amazonaws.com/8bf0322348cc11e7e3cc98325fbfcaa1": result = "{'frogs' : '3'}" else: result = {'sharks': '17'} return result
def _generate_mark_code(rule_name): """Generates a two digit string based on a provided string Args: rule_name (str): A configured rule name 'pytest_mark3'. Returns: str: A two digit code based on the provided string '03' """ code = ''.join([i for i in str(rule_name) if i.isdigit()]) code = code.zfill(2) return code
def getObjName(objID, objList): """ Returns an object's name (str) given its 'objID' (int) and a reference 'objList' (list) Format of 'objList' is [['name_1', id_1], ['name_2', id_2], ...] """ for i in range(0, len(objList)): if objList[i][1] == objID: return objList[i][0]
def get_tile_prefix(rasterFileName): """ Returns 'rump' of raster file name, to be used as prefix for tile files. rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f) where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"] The rump is defined as <date>_<time>_<sat. ID>_<product type> """ return rasterFileName.rsplit("_", 1)[0].rsplit("_AnalyticMS")[0]
def stream_name_to_dict(stream_name, separator='-'): """Transform stream name string to dictionary""" catalog_name = None schema_name = None table_name = stream_name # Schema and table name can be derived from stream if it's in <schema_nama>-<table_name> format s_parts = stream_name.split(separator) if len(s_parts) == 2: schema_name = s_parts[0] table_name = s_parts[1] if len(s_parts) > 2: catalog_name = s_parts[0] schema_name = s_parts[1] table_name = '_'.join(s_parts[2:]) return { 'catalog_name': catalog_name, 'schema_name': schema_name, 'table_name': table_name }
def get_audio_samplerate(samplerate): """ Get audio sample rate into a human easy readable format. Arguments: :param samplerate: integer :return: string """ return "%s kHz" %(samplerate)
def overlap(start1: float, end1: float, start2: float, end2: float) -> float: """how much does the range (start1, end1) overlap with (start2, end2) Looks strange, but algorithm is tight and tested. Args: start1: start of interval 1, in any unit end1: end of interval 1 start2: start of interval 2 end2: end of interval 2 Returns: overlap of intervals in same units as supplied.""" return max(max((end2 - start1), 0) - max((end2 - end1), 0) - max((start2 - start1), 0), 0)
def convert_bytes(num, suffix='B'): """Convert bytes int to int in aggregate units""" for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def configure(args): """Use default hyperparameters. Parameters ---------- args : dict Old configuration Returns ------- args : dict Updated configuration """ configure = { 'node_hidden_size': 128, 'num_propagation_rounds': 2, 'lr': 1e-4, 'dropout': 0.2, 'nepochs': 400, 'batch_size': 1, } args.update(configure) return args
def _get_main_is_module(main_is): """Parses the module name from a "main_is" attribute. The attribute may be either Foo.Bar or Foo.Bar.baz. Args: main_is: A string, the main_is attribute Returns: A string, a valid Haskell module name. """ components = main_is.split(".") if components and components[-1] and components[-1][0:1].islower(): return ".".join(components[:-1]) else: return main_is
def digital_method(coefficients, val, add, mul, act, power, zero, one): """ Evaluate a univariate polynomial at val. The polynomial is given as an iterator 'coefficients' which yields (degree, coefficient) pair in descending order of degree. If the polynomial is of R-coefficients, then val should be in an R-algebra D. All operations 'add', 'mul', 'act', 'power', 'zero', 'one' should be explicitly given, where: 'add' means addition (D x D -> D), 'mul' multiplication (D x D -> D), 'act' action of R (R x D -> D), 'power' powering (D x Z -> D) and 'zero', 'one' constants in D. """ result = zero val_pow = {0:one, 1:val} d = None for d_next, c_next in coefficients: if d: diff = d - d_next if diff not in val_pow: val_pow[diff] = power(val, diff) result = add(mul(result, val_pow[diff]), act(c_next, one)) else: result = act(c_next, one) d = d_next if d: return mul(result, val_pow.get(d, power(val, d))) else: return result
def check_anagrams(first_str: str, second_str: str) -> bool: """ Two strings are anagrams if they are made of the same letters arranged differently (ignoring the case). >>> check_anagrams('Silent', 'Listen') True >>> check_anagrams('This is a string', 'Is this a string') True >>> check_anagrams('This is a string', 'Is this a string') True >>> check_anagrams('There', 'Their') False """ return ( "".join(sorted(first_str.lower())).strip() == "".join(sorted(second_str.lower())).strip() )
def _noaa_names(i): """Return set of possible NOAA names for sat number - lower or UPPER case - zero-padded number or not (noaa7, noaa07) - with or without dash (noaa-14, noaa14) - long (noaa) or short (n) Does not include pre-launch names. Arguments: i [int]: Number of NOAA satellite Returns: Set of possible spellings for this satellite. """ S = {f"{nm:s}{dash:s}{i:>{w:>02d}}" for nm in {"noaa", "n"} for dash in {"", "-", "_"} for w in {1, 2}} return S|{nm.upper() for nm in S}
def post_details(post): """ Displays info about a post: title, date, feed and tags. """ return {"post": post}
def cleanup_social_account(backend, uid, user=None, *args, **kwargs): """ 3rd party: python-social-auth. Social auth pipeline to cleanup the user's data. Must be placed after 'social_core.pipeline.user.create_user'. """ if user and kwargs.get('is_new', False): user.first_name = kwargs['details']['first_name'] user.last_name = kwargs['details']['last_name'] user.save() return {'user': user}
def data_process(input_string): """ This is where all the processing happens. Let's just read the string backwards """ output = input_string return output # Test # return input_string
def extract_scalar_reward(value, scalar_key='default'): """ Extract scalar reward from trial result. Raises ------ RuntimeError Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int. """ if isinstance(value, float) or isinstance(value, int): reward = value elif isinstance(value, dict) and scalar_key in value and isinstance(value[scalar_key], (float, int)): reward = value[scalar_key] else: raise RuntimeError('Incorrect final result: the final result should be float/int, or a dict which has a key named "default" whose value is float/int.') return reward
def fraction_str(numerator, denominator) -> str: """ Formats a fraction to the format %.5f [numerator/deniminator] :param numerator: :param denominator: :return: Formatted string """ if denominator > 0: return "%.5f [%.5f/%d]" % (float(numerator)/denominator, numerator, denominator) else: return "No Data"
def datesuffix(n): """Given day of month return English Ordinal Suffix""" if (n == 1 or n == 21 or n == 31): suffix = "st" elif (n == 2 or n == 22): suffix = "nd" elif (n == 3 or n == 23): suffix = "rd" else: suffix = "th" return suffix
def get_key_from_value(haystack: dict, needle: str): """ Returns a dict key by it's value, ie get_key_from_value({key: value}, value) returns key """ return next((k for k, v in haystack.items() if v == needle), None)
def build_aggregation(facet_name, facet_options, min_doc_count=0): """Specify an elasticsearch aggregation from schema facet configuration. """ exclude = [] if facet_name == 'type': field = '[email protected]' exclude = ['Item'] elif facet_name.startswith('audit'): field = facet_name else: field = 'embedded.' + facet_name + '.raw' agg_name = facet_name.replace('.', '-') facet_type = facet_options.get('type', 'terms') if facet_type == 'terms': agg = { 'terms': { 'field': field, 'min_doc_count': min_doc_count, 'size': 100, }, } if exclude: agg['terms']['exclude'] = exclude elif facet_type == 'exists': agg = { 'filters': { 'filters': { 'yes': {'exists': {'field': field}}, 'no': {'missing': {'field': field}}, }, }, } else: raise ValueError('Unrecognized facet type {} for {} facet'.format( facet_type, field)) return agg_name, agg
def clean_paths(url): """Translate urls into human-readable filenames.""" to_remove = ['http://', 'https://', 'www.', '.com', '.json', '.'] for item in to_remove: url = url.replace(item, '') return url.replace('/', '_')
def unique(L1, L2): """Return a list containing all items in 'L1' that are not in 'L2'""" L2 = dict([(k, None) for k in L2]) return [item for item in L1 if item not in L2]
def transform_file_output(result): """ Transform to convert SDK file/dir list output to something that more clearly distinguishes between files and directories. """ from collections import OrderedDict new_result = [] iterable = result if isinstance(result, list) else result.get('items', result) for item in iterable: new_entry = OrderedDict() entity_type = item['type'] # type property is added by transform_file_directory_result is_dir = entity_type == 'dir' new_entry['Name'] = item['name'] + '/' if is_dir else item['name'] new_entry['Content Length'] = ' ' if is_dir else item['properties']['contentLength'] new_entry['Type'] = item['type'] new_entry['Last Modified'] = item['properties']['lastModified'] or ' ' new_result.append(new_entry) return sorted(new_result, key=lambda k: k['Name'])
def _split_up_multiple_entries(entry): """Split up lists of entries that have been recorded as a single string.""" split_types = ['<br>', '<br/>', '<br />'] for split_type in split_types: if split_type in entry: return entry.split(split_type) return [entry]
def YDbDrtoYUV(Y, Db, Dr): """ convert RGB to YUV color :param Y: Y value (0;1) :param Db: Db value (-1.333-1.333) :param Dr: Dr value (-1.333-1.333) :return: YUV (PAL) tuple (Y0;1 U-0.436-0.436 V-0.615-0.615) """ U = Db / 3.059 V = Dr / -2.169 return Y, U, V
def triwhite(x, y): """ Convert x,y chromaticity coordinates to XYZ tristimulus values. """ X = x / y Y = 1.0 Z = (1-x-y)/y return [X, Y, Z]
def hypot(a): # type: (tuple) -> float """Returns the hypotenuse of point.""" return (a[0] ** 2) + (a[1] ** 2)
def did_commands_succeed(report): """ Returns true if all the commands succeed""" for com in report['command_set']: if com['result']['status'] != 0: return False return True
def adjustEdges(height, width, point): """ This handles the edge cases if the box's bounds are outside the image range based on current pixel. :param height: Height of the image. :param width: Width of the image. :param point: The current point. :return: """ newPoint = [point[0], point[1]] if point[0] >= height: newPoint[0] = height - 1 if point[1] >= width: newPoint[1] = width - 1 return tuple(newPoint)
def get_query_params(query): """ Extract (key, value) pairs from the given GET / POST query. Pairs can be split by '&' or ';'. """ params = {} if query: delim = "&" if "&" not in query and ";" in query: delim = ";" for k_v in query.split(delim): k, v = k_v, "" if "=" in k_v: k, v = k_v.split("=") params[k] = v return params
def piece_size(file_size): """ Based on the size of the file, we decide the size of the pieces. :param file_size: represents size of the file in MB. """ # print 'Size {0} MB'.format(file_size) if file_size >= 1000: # more than 1 gb return 2 ** 19 elif file_size >= 500 and file_size < 1000: return 2 ** 18 elif file_size >= 250 and file_size < 500: return 2 ** 17 elif file_size >= 125 and file_size < 250: return 2 ** 16 elif file_size >= 63 and file_size < 125: return 2 ** 15 else: return 2 ** 14
def remove_digits(name: str) -> str: """ "O1" -> "O" """ return ''.join([i for i in name if not i.isdigit()])
def fname_to_code(fname: str): """file name to stock code Parameters ---------- fname: str """ prefix = "_qlib_" if fname.startswith(prefix): fname = fname.lstrip(prefix) return fname
def unencrypted_ami_volume(rec): """ author: airbnb_csirt description: Identifies creation of an AMI with a non encrypted volume reference: https://amzn.to/2rQilUn playbook: (a) Reach out to the user who created the volume (b) Re-create the AMI with encryption enabled (c) Delete the old AMI """ if rec['detail']['eventName'] != 'CreateImage': # check the event type early to avoid unnecessary performance impact return False elif rec['detail']['requestParameters'] is None: # requestParameters can be defined with a value of null return False req_params = rec['detail']['requestParameters'] block_device_items = req_params.get('blockDeviceMapping', {}).get('items', []) if not block_device_items: return False volume_encryption_enabled = set() for block_device in block_device_items: volume_encryption_enabled.add(block_device.get('ebs', {}).get('encrypted')) return not any(volume_encryption_enabled)
def verify_policy_map_row_added(table, parameter_name, parameter_value): """Add row to Table Args: table (`obj`): Table object parameter_name (`str`): Parameter name parameter_value (`str`): Parameter value Returns: True False """ try: table.add_row( [ "{parameter_name}: {parameter_value}".format( parameter_name=parameter_name, parameter_value=parameter_value, ), "", "", ] ) table.add_row( [ "***********************************************", "*************************", "*************************", ] ) except Exception: return False return True
def unsigned_leb128_decode(data) -> int: """Read variable length encoded 128 bits unsigned integer .. doctest:: >>> from ppci.utils.leb128 import unsigned_leb128_decode >>> signed_leb128_decode(iter(bytes([0xe5, 0x8e, 0x26]))) 624485 """ result = 0 shift = 0 while True: byte = next(data) result |= (byte & 0x7F) << shift # Detect last byte: if byte & 0x80 == 0: break shift += 7 return result
def get_unique_user_lexeme(data_dict): """Get all unique (user, lexeme) pairs.""" pairs = set() for u_id in data_dict.keys(): pairs.update([(u_id, x) for x in data_dict[u_id].keys()]) return sorted(pairs)
def get_screen_name_to_player(players_dict): """Based on player-account assigments this function returns 'screen_name' -> schedule player name mapping.""" screen_name_to_player = {} for player in players_dict: for screen_name in players_dict[player]: if screen_name in screen_name_to_player: raise RuntimeError("screen_name duplication for '%s' is note allowed!" % screen_name) else: screen_name_to_player[screen_name] = player return screen_name_to_player
def PreProcessScore(s): """ Remove all the | and the || """ s = s.replace("|", " ") s = s.replace(" ", " ") return s