content
stringlengths
42
6.51k
def year2Century(year): """ year to century """ str_year = str(year) if(len(str_year)<3): return 1 elif(len(str_year) == 3): if(str_year[1:3] == "00"): # 100 ,200 300, 400 ... 900 return int(str_year[0]) else: # 190, 250, 450 return int(str_year[0])+1 else: # 1750, 1700, 1805 if(str_year[2:4]=="00"): # 1700, 1900, 1100 return int(str_year[:2]) else: # 1705, 1645, 1258 return int(str_year[:2])+1
def join_opening_bracket(lines): """When opening curly bracket is in it's own line (K&R convention), it's joined with precluding line (Java).""" modified_lines = [] for i in range(len(lines)): if i > 0 and lines[i] == "{": modified_lines[-1] += " {" else: modified_lines.append(lines[i]) return modified_lines
def parse_attribute(attribute): """ Convert GTF entry attribute to dictionary """ data = attribute.strip(';').split(';') data = [d.strip() for d in data] pairs = [d.split() for d in data] attribute_dict = {k: v.strip('"') for k, v in pairs} return attribute_dict
def write_trapezoid(base1, base2, height, length, loc, mat, orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0): """ @brief Writes a trapezoid. @param base1 bottom base of the trapezoid @param base2 top base of the trapezoid @param height height of the triangle @param length length of the prism @param loc location of center point @param mat material keyword for json file @param orPhi azimuthal angle of the main axis @param orTheta polar angle of the main axis @param uvecs list of unit vectors for the three main axes (use instead of angles) @param pols Lorentz-Drude parameter list for polarizations [[sigma, gamma, omega]] (use if mat = 'custom') @param eps high frequency dielectric constant of material (use if mat = 'custom') @param mu high frequency permeability of material (use if mat = 'custom') @param tellegen tellegen parameter of the material (use if mat = 'custom') @return { description_of_the_return_value } """ return {'shape' : 'trapezoid_prism', 'loc' : loc, 'material' : mat, "base1" : round(base1, 7), "base2" : round(base2, 7), "height" : round(height,7), "length" : round(length,7), "orPhi" : orPhi, "orTheta" : orTheta, "unit_vectors" : uvecs, "pols": pols, "eps":round(eps, 7), "mu":round(mu, 7), "tellegen":round(tellegen, 7), 'Basis_Set' : []}
def separate_strings_from_dicts(elements): """ Receive a list of strings and dicts an returns 2 lists, one solely with string and the other with dicts. :param List[Union[str, Dict[str, str]]] elements: :rtype: Tuple[List[str], List[Dict[str, str]]] """ all_strs = [] all_dicts = [] for item in elements: if isinstance(item, str): all_strs.append(item) elif isinstance(item, dict): all_dicts.append(item) else: raise RuntimeError(f"Only strings and dicts are supported, got: {item!r}") return all_strs, all_dicts
def first_index(lst, predicate): """Return the index of the first element that matches a predicate. :param lst: list to find the matching element in. :param predicate: predicate object. :returns: the index of the first matching element or None if no element matches the predicate. """ for i, e in enumerate(lst): if predicate(e): return i return None
def calc_install(runs, cost_index, system_index, tax_rate): """ Calculate total install cost for a manufacturing job. :param runs: Number of runs in the job. :param cost_index: Cost Index for the item. :param system_index: Cost Index for the star system where construction would occur. :param tax_rate: Tax rate for the facility where construction would occur. Rate should be represented as a percent. (e.g. the 10% of cost index tax charged in NPC stations is given as 10) :return: """ job_fee = runs * float(cost_index) * float(system_index) facility_tax = job_fee * float(tax_rate) / 100 return job_fee + facility_tax
def get_test_submission_case(case_obj): """Returns a test casedata submission object""" casedata_subm_obj = { '_id' : "{}_a99ab86f2cb3bc18b993d740303ba27f_subj1".format(case_obj['_id']), 'csv_type': "casedata", 'case_id' : case_obj['_id'], 'linking_id' : "a99ab86f2cb3bc18b993d740303ba27f", 'individual_id' : "subj1", 'clin_features' : "HP:0001392" } return casedata_subm_obj
def lcore_core_ids(lcore_mask_host): """ Convert CPU ID mask from argument 'lcore_mask' to a list of CPU IDs """ lcore_cores = [] binary_mask = bin(int(lcore_mask_host, 16))[2:] for i, val in enumerate(binary_mask[::-1]): if val == "1": lcore_cores.append(i) return lcore_cores
def filter_string(filtr): """ Filter function to remove invalid characters :param filtr: :return: """ return "".join(x for x in filtr if x.isalpha())
def concat(L): """ tools for concat new dataframe """ result = None for l in L: if l is None: continue if result is None: result = l else: try: result[l.columns.tolist()] = l except Exception as err: print(err) print(l.head()) return result
def print_error(p, i): """ Returns the error message for package installation issues. :param str p: The name of the package to install. :param str i: The name of the package when imported. """ error_message = f""" {i} not present. Please do the installation using either: - pip install {p} - conda install -c conda-forge {p} """ return error_message
def is_image(ext): """ Checks if the file_format is a supported image to read. :param ext: the extension of a file. :return: whether or not the file is a image """ return ext == '.jpeg' or ext == '.png' or ext == '.jpg' or ext == '.bmp'
def simplified_value_difference(attribute, category0, category1, categorical_class_probability_dict, exponent=1): """Return the simplified value difference between the two passed categories, checking the passed dictionary of class-given-category probabilities""" # equal categories have no distance if category0 == category1: return 0 # get the probability dictionaries for each category category0_dict = categorical_class_probability_dict[attribute].get(category0, None) category1_dict = categorical_class_probability_dict[attribute].get(category1, None) # consider the distance is maximum if there is no information about one of the categories if not category0_dict or not category1_dict: return 1 dist = 0 # compute the distance for each class, computing the probability difference for y_class in category0_dict.keys(): category0_prob = category0_dict[y_class] category1_prob = category1_dict[y_class] dist += abs(category0_prob - category1_prob) ** exponent return dist
def separate_elements(list1, list2): """Check of different values of two lists""" print(f"Liste 1: {len(list1)}") print(f"Liste 2: {len(list2)}") print("\n") print(f"Separate elements: ") return list(set(list1) ^ set(list2))
def _is_int(string): """Returns true or false depending on whether or not the passed in string can be converted to an int""" result = False try: value = int(string) result = True except ValueError: result = False return result
def pop_highest(l): """doc""" # warning, pass-by-ref so WILL modify input arg return l.pop() if l[-1] >= l[0] else l.pop(0)
def enforce_excel_cell_string_limit(long_string, limit): """ Trims a long string. This function aims to address a limitation of CSV files, where very long strings which exceed the char cell limit of Excel cause weird artifacts to happen when saving to CSV. """ trimmed_string = '' if limit <= 3: limit = 4 if len(long_string) > limit: trimmed_string = (long_string[:(limit-3)] + '...') return trimmed_string else: return long_string
def sig_refine(sig): """ To correct deformed signture patterns. e.g., signatures contains spaces. """ sig = sig.replace(' ', '') return sig
def much_greater_than(lhs, rhs, r=0.2): """ Determine if lhs >> rhs :param lhs: Left side of the comparison :param rhs: Right side of the comparison :param r: Ratio to use for comparison :returns True: If the ratio of lhs-to-rhs < r :returns False: Otherwise :rtype: bool """ if rhs / lhs < r: return True return False
def get_bearing_difference(bearing1, bearing2): """ Given two bearings, returns the angle between them """ return (((bearing1 - bearing2) + 180) % 360) - 180
def encode_color(color, n_bits): """ If color is given as boolean, interpret it as maximally on or totally off. Otherwise check whether it fits within the number of bits. """ if isinstance(color, bool): return (2 ** n_bits - 1) * color elif 0 <= color < 2 ** n_bits: return color else: raise ValueError( "`color` should be a boolean or be between 0 and 2 ** n_bits - 1" )
def replace_all(text, dic): """ replaces multiple strings based on a dictionary replace_all(string,dictionary) -> string """ for i, j in dic.items(): text = text.replace(i, str(j)) return text
def format_device(region=None, zone=None, ip=None, device=None, **kwargs): """ Convert device dict or tier attributes to a representative string. :returns: a string, the normalized format of a device tier """ return "r%sz%s-%s/%s" % (region, zone, ip, device)
def imc(peso: float, estatura: float) -> float: """Devuele el IMC :param peso: Peso en kg :peso type: float :param estatura: Estatura en cm :estatura type: float :return: IMC :rtype: float >>> imc(78, 1.83) 23.29 """ return round(peso/(estatura**2), 2)
def get_data(method_name, file_metadata): """ Return the method data containing in the file metadata. """ for data in file_metadata: if (method_name == data[1]): return data
def _parse_single_arg(function_name, additional_parameter, args, kwargs): """ Verifies that a single additional argument has been given (or no additional argument, if additional_parameter is None). Also verifies its name. :param function_name: the name of the caller function, used for the output messages :param additional_parameter: None if no additional parameters should be passed, or a string with the name of the parameter if one additional parameter should be passed. :return: None, if additional_parameter is None, or the value of the additional parameter :raise TypeError: on wrong number of inputs """ # Here all the logic to check if the parameters are correct. if additional_parameter is not None: if len(args) == 1: if kwargs: raise TypeError("{}() received too many args".format( function_name)) additional_parameter_data = args[0] elif len(args) == 0: kwargs_copy = kwargs.copy() try: additional_parameter_data = kwargs_copy.pop( additional_parameter) except KeyError: if kwargs_copy: raise TypeError("{}() got an unexpected keyword " "argument '{}'".format( function_name, kwargs_copy.keys()[0])) else: raise TypeError("{}() requires more " "arguments".format(function_name)) if kwargs_copy: raise TypeError("{}() got an unexpected keyword " "argument '{}'".format( function_name, kwargs_copy.keys()[0])) else: raise TypeError("{}() received too many args".format( function_name)) return additional_parameter_data else: if kwargs: raise TypeError("{}() got an unexpected keyword " "argument '{}'".format( function_name, kwargs.keys()[0])) if len(args) != 0: raise TypeError("{}() received too many args".format( function_name)) return None
def _fix_page(page: dict) -> dict: """ Fix a page dict as returned by the API. :param page: :return: """ # Some (all?) pages with a number as their title have an int in this field. # E.g. https://fr.wikipedia.org/wiki/2040. if "page_title" in page: page["page_title"] = str(page["page_title"]) return page
def _days_before_year(year): """year -> number of days before January 1st of year.""" y = year - 1 return y * 365 + y // 4 - y // 100 + y // 400
def get_illust_url(illust_id: int) -> str: """Get illust URL from ``illust_id``. :param illust_id: Pixiv illust_id :type illust_id: :class:`int` :return: Pixiv Illust URL :rtype: :class:`str` """ return ( 'https://www.pixiv.net/member_illust.php' '?mode=medium&illust_id={}'.format( illust_id, ) )
def pull_top(piles, pos): """ Pulls the top card of pile number `pos`, and returns the new set of piles. Example: > pull_top([[1,2,3], [], [4,5,6], [7,8,9]], 2) [[1,2,3], [], [4,5], [7,8,9]] """ rest = piles[:] rest[pos] = piles[pos][:-1] return rest
def shootoutkey(row, col1=None, coldiff=None): """Calculate key for sorting a shootout. row - a tuple (testname, results) where results is [(passing, ...), ...] and passing is a truthy or falsy value. col1 and col2 - indices into results Return a tuple (col12same, col1fail, failcount) where - col1fail is 0 if results[col1] passes else 1 - col12same is 1 if passing for results[col1] and results[col2] have same truthiness """ testname, results = row fails = [0 if x[0] else 1 for x in results] col1fail = 0 if col1 is None else fails[col1] col2fail = 0 if coldiff is None else fails[coldiff] return col2fail == col1fail, col1fail, sum(fails)
def get_provenance_record(project, ancestor_files): """Create a provenance record describing the diagnostic data and plot.""" record = { 'caption': (f'Transient climate response (TCR) against equilibrium climate ' f'sensitivity (ECS) for {project} models.'), 'statistics': ['mean'], 'domains': ['global'], 'authors': ['schlund_manuel'], 'references': ['flato13ipcc'], 'realms': ['atmos'], 'themes': ['phys'], 'ancestors': ancestor_files, } return record
def get_access_set(access, set): """Get access set.""" try: return access[set] except KeyError: return []
def dms_deg(degree_tuple): """ Convert degree minute' second'' to decimal angle :param degree_tuple: (degree, minute, second) tuple :return: Decimal angle in degrees Example: >>> import units as u >>> >>> u.dms_deg((45, 23, 34)) 45.39277777777778 """ degree, minute, second = degree_tuple decimal_degree = degree + minute/60.0 + second/3600.0 return decimal_degree
def _pack_into_dict(value_or_dict, expected_keys, allow_subset = False): """ Used for when you want to either a) Distribute some value to all predictors b) Distribute different values to different predictors and check that the names match up. :param value_or_dict: Either a) A value b) A dict<predictor_name: value_for_predictor> :param expected_keys: Names of predictors :return: A dict<predictor_name: value_for_predictor> """ if not isinstance(value_or_dict, dict): output_dict = {predictor_name: value_or_dict for predictor_name in expected_keys} else: output_dict = value_or_dict if allow_subset: assert set(value_or_dict.keys()).issubset(expected_keys), 'Expected a subset of: %s. Got %s' % (expected_keys, value_or_dict.keys()) else: assert set(expected_keys) == set(value_or_dict.keys()), 'Expected keys: %s. Got %s' % (expected_keys, value_or_dict.keys()) return output_dict
def subst_variables_in_str(line: str, values: dict, start_char: str = "%") -> object: """ Replace variables inside the specified string :param line: String to replace the variables in. :param values: Dictionary, holding variables and their values. :param start_char: Character used to identify the beginning of a variable inside the string. :return: String where variables have been replaced by their respective values. """ ret_val = line for k, v in zip(values.keys(), values.values()): ret_val = ret_val.replace(start_char + str(k), str(v)) return ret_val
def legacy_convert_time(float_time): """take a float unix timestamp and convert it into something legacy Session likes""" return int(float_time * 1000)
def map_colnames(row, name_map): """Return table row with renamed column names according to `name_map`.""" return { name_map.get(k, k): v for k, v in row.items()}
def create_bm_dictionary(name, federate_count, core_type, real_time, cpu_time, threads): """This function creates a dictionary for a single benchmark run. Args: name (str) - The name of the benchmark, e.g. BMecho_singleCore federate_count (int) - The number of federates. core_type (str) - The name of the core type. real_time (float) - The human-interpreted time it takes to execute this script. cpu_time (float) - The time it takes a CPU to execute this script. threads (int) - The number of threads. Returns: bm_dict (dict) - A dictionary of the benchmark results. """ if name == "BMecho_singleCore": bm_dict = { "name": "{}/{}/iterations:1/real_time".format(name, federate_count), "run_name": "{}/{}/iterations:1/real_time".format(name, federate_count), "run_type": "iteration", "repetitions": 1, "repetitions_index": 1, "threads": threads, "iterations": 1, "real_time": real_time, "cpu_time": cpu_time, "time_unit": "s", } else: bm_dict = { "name": "{}/{}Core/{}/real_time".format(name, core_type, federate_count), "run_name": "{}/{}Core/{}/real_time".format(name, core_type, federate_count), "run_type": "iteration", "repetitions": 1, "repetitions_index": 1, "threads": threads, "iterations": 1, "real_time": real_time, "cpu_time": cpu_time, "time_unit": "s", } return bm_dict
def order_by_leaves(list_graph): """ list_graph: A list of list of graphs. Creates a new list of lists of graphs by dividing the previous lists depending on the number of leaves in each graph. Returns the new list. """ C_l = [] for graph in list_graph: k = len(graph.leaves()) if len(C_l) < k: for i in range(len(C_l), k): C_l.append([]) C_l[k-1] += [graph] i = len(C_l)-1 while i >= 0: if len(C_l[i]) == 0: C_l.pop(i) i += -1 return C_l
def addNamespaceToName(name, namespace): """ Args: name: namespace: Returns: """ return namespace + "::" + name
def split_url(url): """Splits the given URL into a tuple of (protocol, host, uri)""" proto, rest = url.split(':', 1) rest = rest[2:].split('/', 1) host, uri = (rest[0], rest[1]) if len(rest) == 2 else (rest[0], "") return (proto, host, uri)
def enlarge_name(name): """Enlarges a parkour room name.""" if name[0] == "*": return "*#parkour" + name[1:] else: return name[:2] + "-#parkour" + name[2:]
def to_xml_name(name): """Convert field name to tag-like name as used in QuickBase XML. >>> to_xml_name('This is a Field') 'this_is_a_field' >>> to_xml_name('800 Number') '_800_number' >>> to_xml_name('A & B') 'a___b' >>> to_xml_name('# of Whatevers') '___of_whatevers' """ xml_name = ''.join((ch if ch.isalnum() else '_') for ch in name.lower()) if not xml_name[0].isalpha(): xml_name = '_' + xml_name return xml_name
def _aprime(pHI,pFA): """recursive private function for calculating A'""" pCR = 1 - pFA # use recursion to handle # cases below the diagonal defined by pHI == pFA if pFA > pHI: return 1 - _aprime(1-pHI ,1-pFA) # Pollack and Norman's (1964) A' measure # formula from Grier 1971 if pHI == 0 or pFA == 1: # in both of these cases pHI == pFA return .5 return .5 + (pHI - pFA)*(1 + pHI - pFA)/(4*pHI*(1 - pFA))
def compute_fixed_points(m, n, L): """ Find the fixed points of the BCN. A state is called a fixed point if it can transit to itself by a certain input. """ M = 2 ** m N = 2 ** n fps = [] for i in range(1, N + 1): for k in range(1, M + 1): blk = L[(k - 1) * N: k * N] j = blk[i - 1] if j == i: fps.append(i) print('FP: ', i) break return fps
def unique_characters(input_str: str) -> bool: """Returns true if a string has all unique characters using a dict. Args: input_str: Input string Returns: Returns True if a string has all unique characters. """ seen_chars = {} for char in input_str: if char in seen_chars: return False seen_chars[char] = True return True
def delta_temperature(wavelength, length, dn=1.87e-4): """Return the delta temperature for a pi phase shift on a MZI interferometer.""" return wavelength / 2 / length / dn
def shuffle_first_axis(arrays): """ Shuffle a (possible) multi-dimensional list by first axis """ import random random.shuffle(arrays) return arrays
def validate_coin_choice(selection, unique_cans): """Translates user menu selection into the name of can that was chosen. No errors.""" if 0 < selection <= len(unique_cans): return True, unique_cans[selection - 1].name else: print("Not a valid selection\n") return False, None
def find_nearest_multiple(num, n): """Find the nearest multiple of n to num 1. num: a number, num must be larger than n to have a meaningful result. 2. n : a number to be multipled """ return int(round(num / n)) * n
def sqnorm(v): """Compute the square euclidean norm of the vector v.""" res = 0 for elt in v: for coef in elt: res += coef ** 2 return res
def bytes_to_hex(bs): """ Convert a byte string to an hex string. Parameters ---------- bs: bytes byte string Returns ------- str: hex string """ return ''.join('%02x' % i for i in bs)
def ignore_escape(path: str) -> str: """ Escape a path appropriately for a docker ignore file. """ special_chars = "\\*?[]" return "".join("\\" + ch if ch in special_chars else ch for ch in path)
def get_odd_numbers(num_list: list) -> list: """Returns a list of odd numbers from a list.""" return [num for num in num_list if num % 2 != 0]
def choices(x): """ Takes a list of lists x and returns all possible choices of one element from each sublist. >>> choices([range(2), range(3), ["foo"]]) [ [0, 0, "foo"], [0, 1, "foo"], [0, 2, "foo"], [1, 0, "foo"], [1, 1, "foo"], [1, 2, "foo"] ] """ if len(x) == 0: return [[]] else: res = [] for item in x[0]: res += [ [item] + sub for sub in choices(x[1:]) ] return res
def recall(ground_truth_permutated, **kwargs): """ Calculate the recall at k @param ground_truth_permutated: Ranked results with its judgements. """ rank = ground_truth_permutated limit = kwargs.get('limit', len(ground_truth_permutated)) nrel = float(kwargs.get('nrel', len(ground_truth_permutated))) if nrel > len(ground_truth_permutated): nrel = len(ground_truth_permutated) if len(rank) < limit: # 0-padding rank += [0] * (limit - len(rank)) recall = 0.0 for hit in rank[:limit + 1]: if hit > 0: recall += hit return recall / nrel if nrel > 0 else 0.0
def parse_similar_words(similar_words_file): """ as produced by similar_words_batch.py """ similar_words = {} word = "" for line in open(similar_words_file, "r"): if line == "----------------------------------------------------\n": word = "" elif word == "": word = line.strip() similar_words[word] = set() else: for w, c in eval(line): if w not in similar_words[word]: similar_words[word].add(w) return similar_words
def prepare_dict(hermes_dict): """ Prepare a rhasspy type like dict from a hermes intent dict """ intent = hermes_dict["intent"]["intentName"] out_dict = {} out_dict.update({"slots": {s["slotName"]:s["rawValue"] for s in hermes_dict["slots"]}}) out_dict["intent"] = {"name": intent} return out_dict
def _DiskSize(value): """Returns a human readable string representation of the disk size. Args: value: str, Disk size represented as number of bytes. Returns: A human readable string representation of the disk size. """ size = float(value) the_unit = 'TB' for unit in ['bytes', 'KB', 'MB', 'GB']: if size < 1024.0: the_unit = unit break size = float(size) / 1024.0 if size == int(size): return '%d %s' % (size, the_unit) else: return '%3.1f %s' % (size, the_unit)
def norm_angle_diff(angle_in_degrees): """Normalize the difference of 2 angles in degree. This function is used to normalize the "delta psi" angle. """ return abs(((angle_in_degrees + 90) % 180) - 90.)
def _process_iss_arg(arg_key, arg_val): """Creates a list with argument and its value. Argument values represented by a list will be converted to a single string joined by spaces, e.g.: [1, 2, 3] -> '1 2 3'. Argument names will be converted to command line parameters by appending a '--' prefix, e.g.: 'some_parameter' -> '--some_parameter'. Args: arg_key (str): Argument name. arg_val: Argument value. Returns: [converted_arg, arg_value, ...]: List containing a prepared command line parameter and its value(s). """ if isinstance(arg_val, bool) and arg_val: return [f'--{arg_key}'] elif not isinstance(arg_val, list): return [f'--{arg_key}', str(arg_val)] else: flags = [f'--{arg_key}'] flags.extend([str(x) for x in arg_val]) return flags
def _romberg_diff(b, c, k): """ Compute the differences for the Romberg quadrature corrections. See Forman Acton's "Real Computing Made Real," p 143. """ tmp = 4.0**k return (tmp * c - b)/(tmp - 1.0)
def problem_1_4(s: str) -> str: """ replace all spaces in a string with %20 >>> problem_1_4("foo bar ") 'foo%20bar' >>> problem_1_4("a s") Traceback (most recent call last): ... ValueError: Size of provided string is incorrect """ from collections import deque response = deque([]) for char in s: if len(response) == len(s): return "".join(response) if char == " ": response.append("%") response.append("2") response.append("0") else: response.append(char) raise ValueError("Size of provided string is incorrect")
def get_identifiers_given_scope_of_selection(available_idfs_in_scopes: dict, scope_of_selection: str, target_function_range: str) -> set: """ Given identifiers in different scopes and the scope of selection, get the list of possible Identifiers that may be used as an unbound Identifier token :param available_idfs_in_scopes: :param scope_of_selection: :param target_function_range: The range (token location) of the function where the target is present :return: """ if scope_of_selection == 'function': return set(available_idfs_in_scopes['functions_to_identifiers'][target_function_range]) elif scope_of_selection == 'file': return set(available_idfs_in_scopes['all_identifiers_in_same_file']) else: # Also include top-K most frequent return set(available_idfs_in_scopes['all_identifiers_in_same_file'] + available_idfs_in_scopes[ 'K_most_frequent_identifiers'])
def splitList(inputList, bins = None, preserveOrder = False): """Split a list into sublists and return the list of sublists. Args: inputList: The list to be split bins: The number of bins. Overrides cpu_count() preserveOrder: if true, append to each sublist in list order, otherwise round robin. Returns: List of sublists. """ import multiprocessing # Break the list of candidates up into the number of CPUs listLength = len(inputList) if bins: # and bins <= 256: nProcessors = bins else: nProcessors = multiprocessing.cpu_count() if listLength <= nProcessors: nProcessors = listLength # Create nProcessors x empty arrays listChunks = [ [] for i in range(nProcessors) ] i = 0 if preserveOrder: # work out the remainder remainder = listLength % nProcessors chunkSize = listLength / nProcessors ch = 0 for item in inputList: listChunks[i].append(item) ch += 1 if remainder > 0: rem = 1 else: rem = 0 if ch >= chunkSize + rem: i += 1 ch = 0 if remainder > 0: remainder -= 1 else: for item in inputList: listChunks[i].append(item) i += 1 if i >= nProcessors: i = 0 return nProcessors, listChunks
def fresnel_criterion(W, z, wav): """ determine the frensel number of a wavefield propagated over some distance z :param W: approx. beam/aperture size [m] :param z: propagation distance [m] :param wav: source wavelength [m] :returns F: Fresnel number """ F = W**2/(z*wav) return F
def process(data, template_name_key, **kwargs): """ Function to process multitemplate data items. :param data: (list), data to process - list of dictionaries :param template_name_key: string, name of the template key """ ret = [] headers = tuple() previous_headers = tuple() headers_to_endings = {} # scan through data to split in multiple items for datum in data: headers = tuple(datum.keys()) # check if need to form headers_to_endings dictionary of {ending: [headers]} if headers != previous_headers: endings = tuple( [ h.replace(template_name_key, "") for h in headers if h.startswith(template_name_key) and h != template_name_key ] ) headers_without_endings = [h for h in headers if not h.endswith(endings)] headers_to_endings = { ending: headers_without_endings + [h for h in headers if h.endswith(ending)] for ending in endings } if template_name_key in headers_without_endings: headers_to_endings = {"": headers_without_endings, **headers_to_endings} # form data for ending, headers_item in headers_to_endings.items(): ret.append( { h[: -len(ending)] if h.endswith(ending) and ending else h: datum[h] for h in headers_item } ) previous_headers = headers return ret
def create_article_institute_links(article_id, institute_ids, score): """Creates data for the article/institutes association table. There will be multiple links if the institute is multinational, one for each country entity. Args: article_id (str): arxiv id of the article institute_ids (:obj:`list` of :obj:`str`): institute ids to link with the article score (numpy.float64): score for the match Returns: (:obj:`list` of :obj:`dict`): article institute links ready to load to database """ return [{'article_id': article_id, 'institute_id': institute_id, 'is_multinational': len(institute_ids) > 1, 'matching_score': float(score)} for institute_id in institute_ids]
def _byteshr(bytes): """Human-readable version of bytes count""" for x in ['bytes','KB','MB','GB','TB']: if bytes < 1024.0: return "%3.1f%s" % (bytes, x) bytes /= 1024.0 raise ValueError('cannot find human-readable version')
def __span_overlap__(span1, span2): """ """ if (span1[0] <= span2[1]) & (span2[0] <= span1[1]): return True else: return False
def get_colnames(main_colnames=None, error_colnames=None, corr_colnames=None, cartesian=True): """ Utility function for generating standard column names Parameters ---------- main_colnames: [6] str array_like {None} The column names of the measurements. If left as None then if `cartesian` is true: ['X', 'Y', 'Z', 'U', 'V', 'W'] if `cartesian` is false: ['ra', 'dec', 'parallax', 'pmra', 'pmdec', 'radial_velocity'] error_colnames: [6] str array_like {None} The column names of the measurements. If left as None then we try to infer the names by appending '_error' to the main column names. corr_colnames: [15] str array_like {None} The column names of the correlations between the errors of each measurement pair. If left as None we try to infer the names by pairing each measurmenet and appending '_corr', e.g.: 'X_Y_corr'. Notes ----- If all column names are provided as argument, this function does nothing. The default format for column names for errors and correlations is, e.g.: X_error, Y_error, ... X_Y_corr, X_Z_corr, X_U_corr, X_V_corr, X_W_corr, Y_Z_corr, ... The correlations are listed in the same way one would read the upper triangle of the correlation matrix, where the rows (and columns) of the matrix are in the same order as `main_colnames`. """ if main_colnames is None: if cartesian: # main_colnames = [el for el in 'XYZUVW'] main_colnames = ['X', 'Y', 'Z', 'U', 'V', 'W'] else: # provide astrometric column names main_colnames = [ 'ra', 'dec', 'parallax', 'pmra', 'pmdec', 'radial_velocity', ] if error_colnames is None: error_colnames = [el+'_error' for el in main_colnames] if corr_colnames is None: corr_colnames = [] for i, colname1 in enumerate(main_colnames): for colname2 in main_colnames[i + 1:]: corr_colnames.append('{}_{}_corr'.format( colname1, colname2 )) return main_colnames, error_colnames, corr_colnames
def find_dist(mol_1_x, mol_1_y, mol_1_z, mol_2_x, mol_2_y, mol_2_z): """Function to find the square distance between two points in 3D Takes two len=3 tuples Returns a float""" return ( pow((mol_1_x - mol_2_x), 2) + pow((mol_1_y - mol_2_y), 2) + pow((mol_1_z - mol_2_z), 2) )
def connected_components(edges): """ Computes the connected components. @param edges edges @return dictionary { vertex : id of connected components } """ res = {} for k in edges: for _ in k[:2]: if _ not in res: res[_] = _ modif = 1 while modif > 0: modif = 0 for k in edges: a, b = k[:2] r, s = res[a], res[b] if r != s: m = min(res[a], res[b]) res[a] = res[b] = m modif += 1 return res
def hard_dedupe(s): """Takes in a string, and returns a string where only the first occurrence of each letter is retained. So the string 'abccba' goes to 'abc'. The empty string returns the empty string.""" seen = set() ans = '' for char in s: if char in seen: continue seen.add(char) ans += char return ans
def is_blank_line(line, allow_spaces=0): """is_blank_line(line, allow_spaces=0) -> boolean Return whether a line is blank. allow_spaces specifies whether to allow whitespaces in a blank line. A true value signifies that a line containing whitespaces as well as end-of-line characters should be considered blank. """ if not line: return 1 if allow_spaces: return line.rstrip() == '' return line[0] == '\n' or line[0] == '\r'
def get_ids(patients): """the ids may be different for different trees, fix it""" ids = [] for name in patients: try: ids.append(name.split('|')[1]) except: ids.append(name) return ids
def error_porcentual(experimental: float, aceptado: float) -> str: """ Calcular error porcentual de un resultado experimental obtenido con respecto al aceptado """ porcentaje = abs(((aceptado - experimental) / aceptado) * 100) return "{:.8f}%".format(porcentaje)
def histogramm(values): """Compute the histogramm of all values: a dictionnary dict[v]=count""" hist = {} for v in values: if v in hist: hist[v]+=1 else: hist[v]=1 return hist
def is_in_container(device, container="undefined_container"): """ Check if device is attached to given container. Parameters ---------- device : dict Device information from cv_facts container : str, optional Container name to check if device is attached to, by default 'undefined_container' Returns ------- boolean True if attached to container, False if not. """ if "parentContainerKey" in device: if container == device["parentContainerKey"]: return True return False
def _get_haddock_path(package_id): """Get path to Haddock file of a package given its id. Args: package_id: string, package id. Returns: string: relative path to haddock file. """ return package_id + ".haddock"
def compute_best_test_losses(data, k, total_queries): """ Given full data from a completed nas algorithm, output the test error of the arch with the best val error after every multiple of k """ results = [] for query in range(k, total_queries + k, k): best_arch = sorted(data[:query], key=lambda i:i[3])[0] test_error = best_arch[3] results.append((query, test_error)) return results
def rgb2hex(r,g,b): """ Convert a RGB vector to hexadecimal values """ hexfmt = "#%02x%02x%02x"%(r,g,b) return hexfmt
def func_name(func): """ Return func's fully-qualified name """ if hasattr(func, "__module__"): return "{}.{}".format(func.__module__, func.__name__) return func.__name__
def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. val: float or int src: tuple dst: tuple example: print(scale(99, (0.0, 99.0), (-1.0, +1.0))) """ return (float(val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
def _text2int(text_num, num_words=None): """ Function that takes an input string of a written number (in English) to translate it to the respective integer. :param text_num: string of a written number (in English) :param num_words: optional dictionary to add containing text number (keys) and respective digit (values) pairs :return: integer of the respective number """ if num_words is None: num_words = dict() units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = [ "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", ] scales = ["hundred", "thousand", "million", "billion", "trillion"] num_words["and"] = (1, 0) for idx, word in enumerate(units): num_words[word] = (1, idx) for idx, word in enumerate(tens): num_words[word] = (1, idx * 10) for idx, word in enumerate(scales): num_words[word] = (10 ** (idx * 3 or 2), 0) current = result = 0 for word in text_num.split(): if word not in num_words: raise Exception("Illegal word: " + word) scale, increment = num_words[word] current = current * scale + increment if scale > 100: result += current current = 0 return result + current
def get_index(string, list): """ Return index of string in list. """ return [i for i, s in enumerate(list) if string in s][0]
def to_localstack_url(api_id: str, url: str): """ Converts a API GW url to localstack """ return url.replace("4566", f"4566/restapis/{api_id}").replace( "dev", "dev/_user_request_" )
def double_times_3(w): """ Check if two three consecutive double characters are present. Return False if otherwise. """ l = 0 if len(w) < 6: return False while l < len(w) - 5: if w[l] == w[l+1]: if w[l+2] == w[l+3]: if w[l+4] == w[l+5]: return True l += 1 return False
def _set_block_title(reaction): """ Update the string for the figure title """ side_lst = [] for side in reaction: side_lst.append('+'.join(side)) title = '{0:^60s}'.format( side_lst[0]+'='+side_lst[1]) return title
def validate1(recipe): """ @param recipe is a list from the list of lists (PBJSammies, GCSammies) @return whether this recipe is a SuperSammie """ # we don't want plain sandwiches! if len(recipe) <= 2: return False else: return True
def rotate(table, mod): """Rotate a list.""" return table[mod:] + table[:mod]
def is_sequence(argument): """Check if argument is a sequence.""" return ( not hasattr(argument, "strip") and not hasattr(argument, "shape") and (hasattr(argument, "__getitem__") or hasattr(argument, "__iter__")) )
def autoname(cls): """Decorator that automatically names class items with autoname properties An autoname property is made with the :func:`autoname_property` decorator, like this:: >>> @autoname_property('name') ... class MyDescriptor: ... def __get__(self, instance, owner=None): ... if instance is None: ... return self ... else: ... return '<{} of {}>'.format(self.name, instance) >>> @autoname ... class Spaceship: ... position = MyDescriptor() ... velocity = MyDescriptor() >>> Spaceship().position '<position of <...Spaceship object at ...>>' >>> Spaceship().velocity '<velocity of <...Spaceship object at ...>>' """ for name, value in cls.__dict__.items(): name_prop = getattr(type(value), '_gillcup_autoname_property', None) if name_prop is not None: setattr(value, name_prop, name) return cls
def _hamming_distance(x_param: int) -> int: """ Calculate the bit-wise Hamming distance of :code:`x_param` from 0. The Hamming distance is the number 1s in the integer :code:`x_param`. :param x_param: A non-negative integer. :return: The hamming distance of :code:`x_param` from 0. """ tot = 0 while x_param: tot += 1 x_param &= x_param - 1 return tot
def _tag_string_to_list(tag_string): """This is used to change tags from a sting to a list of dicts. """ out = [] for tag in tag_string.split(u','): tag = tag.strip() if tag: out.append({u'name': tag, u'state': u'active'}) return out
def format_entities(entities): """ formats entities to key value pairs """ ## Should be formatted to handle multiple entity values # e = {"day":None,"time":None,"place":None} e = {} for entity in entities: e[entity["entity"]] = entity["value"] return e
def _add_padding(data: str, width: int, padding_char: str = ' ') -> str: """Return data with added padding for tabulation using given width.""" return data + padding_char*(width - len(data))
def list_of_lines(s): """ A post-processor function that splits a string *s* (the stdout output of a) command in a list of lines (newlines are removed). :rtype: a list of lines (str) """ return s.split('\n')