content
stringlengths
42
6.51k
def read_optional_from_dict(input_dict, key, standard_val=None, typecast=None): """Tries to read an option from a dictionary. If not found, a standard value is returned instead. If no standard value is informed, None is returned. Data can also be converted by a type cast. The given standard value is not converted by typecast. WITH typecast=None, THIS CAN BE REPLACED BY dict.get() METHOD! """ try: val = input_dict[key] except KeyError: # if standard_val is None: # raise KeyError("Hey, parameter '{}' was not found on dict." # "".format(key)) # else: return standard_val # Data conversion. if typecast is None: return val else: return typecast(val)
def _get_process_times(process_times, requests): """Read in service_time values from requests.""" # loop over requests, see if they have service times. if so, set for req in requests: if 'service_time' in req: process_times[int(req['@node'])] = float(req['service_time']) return process_times
def check_argument_groups(parser, arg_dict, group, argument, required): """ Check for use of arguments. Raise an error if the parser uses an argument that belongs to an argument group (i.e. mode) but the group flag is not used or if the argument is required in the argument group and it's not used. Notes: - argument and group should be strings and should start with - or -- - group should be a flag with action 'store_true' - argument shouldn't be a flag, and should be None if it isn't used. >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--phylo', action='store_true') _StoreTrueAction(...) >>> parser.add_argument('--inseq') _StoreAction(...) >>> args = parser.parse_args(['--phylo', '--inseq', 'not_none']) >>> check_argument_groups(parser, vars(args), '--phylo', '--inseq', True) """ arg_name = argument.replace("-", "") group_name = group.replace("-", "") if not arg_dict[group_name]: if arg_dict[arg_name] is not None: parser.error("phylosofs requires " + group + " if " + argument + " is used.") else: if required and arg_dict[arg_name] is None: parser.error("phylosofs requires " + argument + " if " + group + " is used.") return None
def matscalarMul(mat, scalar): """Return matrix * scalar.""" dim = len(mat) return tuple( tuple( mat[i][j] * scalar for j in range(dim) ) for i in range(dim) )
def idecibel(x): """Calculates the inverse of input decibel values :math:`z=10^{x \\over 10}` Parameters ---------- x : a number or an array Examples -------- >>> from wradlib.trafo import idecibel >>> print(idecibel(10.)) 10.0 """ return 10.0 ** (x / 10.0)
def apply_rules(user, subscription, subscription_rules, rule_logic): """ Apply logic to rules set for each subscription. In a way this authorizes who can see the subscription. Rules can be applied in two ways: All rules must apply and some rules must apply. user: models.User() subscription: models.MeetingSubscription() subscription_rules: models.Rule() rule_logic: all(), any() """ rules = set() for rule in subscription_rules: user_rule = user.meta_data[rule.name] subscription_rule = rule.value if type(user_rule) is list: rules.add(subscription_rule in user_rule) else: rules.add(user_rule == subscription_rule) if rule_logic(rules): return subscription return None
def _gp_int(tok): """Get a int from a token, if it fails, returns the string (PRIVATE).""" try: return int(tok) except ValueError: return str(tok)
def radix_sort(lst, base=10): """ Sorts by using the radix sort. This version only works with positive integers. Sorts by creating buckets and putting each number in to its corresponding bucket by looking at each consecutive digit.""" if len(lst) < 2: return lst def lst_to_buckets(lst, base, iteration): # create buckets according to what is set as the base buckets = [[] for x in range(base)] for number in lst: # Find the proper digit depending on what iteration we are on digit = (number // (base ** iteration)) % base # Put the number in the proper bucket buckets[digit].append(number) return buckets # now sorted in buckets according to the digit def buckets_to_lst(buckets): new_lst = [] for bucket in buckets: # look at all the buckets for number in bucket: # look at each number in each bucket and append new_lst.append(number) return new_lst maxval = max(lst) itr = 0 # while the maxval is more than the iterations, keep sorting # meaning, until we have done an iteration for each digit in the max value of the list, keep calling these functions to sort while base ** itr <= maxval: lst = buckets_to_lst(lst_to_buckets(lst, base, itr)) itr += 1 return lst
def _type(obj): """Verb: No-op.""" print(type(obj)) return obj
def _extract_default_values(config_schema): """ :param config_schema: A json-schema describing configuration options. :type config_schema: dict :returns: a dictionary with the default specified by the schema :rtype: dict | None """ defaults = {} if 'properties' not in config_schema: return None for key, value in config_schema['properties'].items(): if isinstance(value, dict) and 'default' in value: defaults[key] = value['default'] elif isinstance(value, dict) and value.get('type', '') == 'object': # Generate the default value from the embedded schema defaults[key] = _extract_default_values(value) return defaults
def _refine_index_filename(filename): """ get the current file name for CSV index """ return f"{filename}.index"
def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. """ return int(((val - src[0]) / float(src[1] - src[0])) * (dst[1] - dst[0]) + dst[0])
def polyline2linesegments(polyline): """Convert a polyline to a sequence of lines""" if len(polyline) < 2: raise ValueError("A polyline must have at least length 2") result = [] for p0, p1 in zip(polyline, polyline[1:]): result.append((p0, p1)) return result
def convert_diagram_to_relative(diag, max_dim): """Convert the persistence diagram using duality. Here, add one to the dimension. :param diag: persistence diagram in the Gudhi format. :type diag: list of tuples (dim, (birth, death)). """ relative_betti = {} for p in diag: dim = p[0] if dim <= max_dim-1: relative_betti.update({dim + 1: relative_betti.get(dim + 1, 1)}) return diag
def sanitize_ap_name(input_name): """ Returns access_point name that begins with a number or lowercase letter, 3 to 50 chars long, no dash at begin or end, no underscores, uppercase letters, or periods :param input_name: """ output_name = input_name.translate( str.maketrans({'_': '', '.': ''}) ) if output_name.startswith('-'): output_name = output_name[1:] if output_name.endswith('-'): output_name = output_name[0:-1] return output_name[0:50].lower()
def dms2dd(degrees, minutes, seconds, quadrant): """ Convert degrees, minutes, seconds, quadrant to decimal degrees :param degrees: coordinate degrees :type degrees: int :param minutes: coordinate minutes :type minutes: int :param seconds: coordinate seconds :type seconds: int :param quadrant: coordinate quadrant (N, E, S, W) :type quadrant: str|unicode :return: decimal degrees :rtype: float """ illegal_vals = (None, '', u'') for iv in illegal_vals: if iv in (degrees, minutes, seconds, quadrant): raise ValueError("ERROR: Illegal value: %s" % iv) if quadrant.lower() not in ('n', 'e', 's', 'w'): raise ValueError("ERROR: Invalid quadrant: %s" % quadrant) output = int(degrees) + int(minutes) / 60 + int(seconds) / 3600 if quadrant.lower() in ('s', 'w'): output *= -1 return output
def isprime(n=936): """Write a function, is_prime, that takes a single integer argument and returns True when the argument is a prime number and False otherwise.""" if n < 3: return False for i in range(2, n): if n % i == 0: return False return True
def seconds_since_midnight( time_spec ): """ Interprets the argument as a time of day specification. The 'time_spec' can be a number between zero and 24 or a string containing am, pm, and colons (such as "3pm" or "21:30"). If the interpretation fails, an exception is raised. Returns the number of seconds since midnight. """ orig = time_spec try: if type(time_spec) == type(''): assert '-' not in time_spec ampm = None time_spec = time_spec.strip() if time_spec[-2:].lower() == 'am': ampm = "am" time_spec = time_spec[:-2] elif time_spec[-2:].lower() == 'pm': ampm = "pm" time_spec = time_spec[:-2] elif time_spec[-1:].lower() == 'a': ampm = "am" time_spec = time_spec[:-1] elif time_spec[-1:].lower() == 'p': ampm = "pm" time_spec = time_spec[:-1] L = [ s.strip() for s in time_spec.split(':') ] assert len(L) == 1 or len(L) == 2 or len(L) == 3 L2 = [ int(i) for i in L ] hr = L2[0] mn = 0 sc = 0 if ampm: if ampm == 'am': if hr == 12: hr = 0 else: assert hr < 12 else: if hr == 12: hr = 12 else: assert hr < 12 hr += 12 else: assert hr < 24 if len(L2) > 1: mn = L2[1] assert mn < 60 if len(L2) > 2: sc = L2[2] assert sc < 60 nsecs = hr*60*60 + mn*60 + sc else: # assume number of hours since midnight assert not time_spec < 0 and time_spec < 24 nsecs = int(time_spec)*60*60 except Exception: raise Exception( "invalid time-of-day specification: "+str(orig) ) return nsecs
def number(value, message_error=None, message_valid=None): """ value : value element DOM. Example : document['id].value message_error : str message message_valid: str message function return tuple """ if isinstance(value, (int, float, complex)): if message_valid: return(True, value, message_valid) else: return(True, value) else: return(False, value)
def trim_common_prefixes(strs, min_len=0): """trim common prefixes""" trimmed = 0 if len(strs) > 1: s1 = min(strs) s2 = max(strs) for i in range(len(s1) - min_len): if s1[i] != s2[i]: break trimmed = i + 1 if trimmed > 0: strs = [s[trimmed:] for s in strs] return trimmed, strs
def format_mobileconfig_fix(mobileconfig): """Takes a list of domains and setting from a mobileconfig, and reformats it for the output of the fix section of the guide. """ rulefix = "" for domain, settings in mobileconfig.items(): if domain == "com.apple.ManagedClient.preferences": rulefix = rulefix + \ (f"NOTE: The following settings are in the ({domain}) payload. This payload requires the additional settings to be sub-payloads within, containing their their defined payload types.\n\n") rulefix = rulefix + format_mobileconfig_fix(settings) else: rulefix = rulefix + ( f"Create a configuration profile containing the following keys in the ({domain}) payload type:\n\n") rulefix = rulefix + "[source,xml]\n----\n" for item in settings.items(): rulefix = rulefix + (f"<key>{item[0]}</key>\n") if type(item[1]) == bool: rulefix = rulefix + \ (f"<{str(item[1]).lower()}/>\n") elif type(item[1]) == list: rulefix = rulefix + "<array>\n" for setting in item[1]: rulefix = rulefix + \ (f" <string>{setting}</string>\n") rulefix = rulefix + "</array>\n" elif type(item[1]) == int: rulefix = rulefix + \ (f"<integer>{item[1]}</integer>\n") elif type(item[1]) == str: rulefix = rulefix + \ (f"<string>{item[1]}</string>\n") rulefix = rulefix + "----\n\n" return rulefix
def convert_booleans(kwargs): """Converts standard true/false/none values to bools and None""" for key, value in kwargs.items(): if not isinstance(value, str): continue if value.upper() == 'TRUE': value = True elif value.upper() == 'FALSE': value = False elif value.upper() == 'NONE': value = None kwargs[key] = value return kwargs
def _valid_source_node(node: str) -> bool: """Check if it is valid source node in BEL. :param node: string representing the node :return: boolean checking whether the node is a valid target in BEL """ # Check that it is an abundance if not node.startswith('a'): return False # check that the namespace is CHEBI and PUBMED if 'CHEBI' in node or 'PUBCHEM' in node: return True return False
def get_process_params(process_args, param_dict): """ Get parameters from a process, if they are in its definition. Arguments: process_args {dict} -- arguments sent by a process {'argument_name': value} e.g. {'data': {'from_node': 'dc_0'}, 'index': 2} param_dict {dict} -- parameters needed by a process {'parameter_name': 'parameter_type'} e.g. {'ignore_data': 'bool', 'p': 'int'} """ process_params = {} for param in param_dict: if param in process_args: if param in ('y', 'mask') and isinstance(process_args[param], dict) and 'from_node' in process_args[param]: # Mapping for openeo processes which havs f(x, y) input rather than f(data) # NB this is used in eodatareaders/pixel_functions/geo_process process_params[param] = 'set' + param_dict[param] + ';str' elif isinstance(param_dict[param], list): # NOTE some python processes have different param names compared to the openEO process # see e.g. "clip" # https://github.com/Open-EO/openeo-processes-python/blob/master/src/openeo_processes/math.py # https://processes.openeo.org/#clip process_params[param_dict[param][0]] = str(process_args[param]) + ';' + param_dict[param][1] else: process_params[param] = str(process_args[param]) + ';' + param_dict[param] elif param == 'extra_values': # Needed in "sum" and "product" process_params[param] = param_dict[param] return process_params
def _FindLatestMinorVersion(debuggees): """Given a list of debuggees, find the one with the highest minor version. Args: debuggees: A list of Debuggee objects. Returns: If all debuggees have the same name, return the one with the highest integer value in its 'minorversion' label. If any member of the list does not have a minor version, or if elements of the list have different names, returns None. """ if not debuggees: return None best = None best_version = None name = None for d in debuggees: if not name: name = d.name elif name != d.name: return None minor_version = d.labels.get('minorversion', 0) if not minor_version: return None try: minor_version = int(minor_version) if not best_version or minor_version > best_version: best_version = minor_version best = d except ValueError: # Got a bogus minor version. We can't determine which is best. return None return best
def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes): """Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max sample size, can be defined separately for src and tgt (then list or tuple) Returns: np.array: filtered sample array list: list of removed indices """ if max_sizes is None: return indices, [] if type(max_sizes) in (int, float): max_src_size, max_tgt_size = max_sizes, max_sizes else: max_src_size, max_tgt_size = max_sizes if tgt_sizes is None: ignored = indices[src_sizes[indices] > max_src_size] else: ignored = indices[ (src_sizes[indices] > max_src_size) | (tgt_sizes[indices] > max_tgt_size) ] if len(ignored) > 0: if tgt_sizes is None: indices = indices[src_sizes[indices] <= max_src_size] else: indices = indices[ (src_sizes[indices] <= max_src_size) & (tgt_sizes[indices] <= max_tgt_size) ] return indices, ignored.tolist()
def unique_name(key, name, name_dict, name_max=-1, clean_func=None, sep="."): """ Helper function for storing unique names which may have special characters stripped and restricted to a maximum length. :arg key: unique item this name belongs to, name_dict[key] will be reused when available. This can be the object, mesh, material, etc instance its self. :type key: any hashable object associated with the *name*. :arg name: The name used to create a unique value in *name_dict*. :type name: string :arg name_dict: This is used to cache namespace to ensure no collisions occur, this should be an empty dict initially and only modified by this function. :type name_dict: dict :arg clean_func: Function to call on *name* before creating a unique value. :type clean_func: function :arg sep: Separator to use when between the name and a number when a duplicate name is found. :type sep: string """ name_new = name_dict.get(key) if name_new is None: count = 1 name_dict_values = name_dict.values() name_new = name_new_orig = (name if clean_func is None else clean_func(name)) if name_max == -1: while name_new in name_dict_values: name_new = "%s%s%03d" % (name_new_orig, sep, count) count += 1 else: name_new = name_new[:name_max] while name_new in name_dict_values: count_str = "%03d" % count name_new = "%.*s%s%s" % (name_max - (len(count_str) + 1), name_new_orig, sep, count_str, ) count += 1 name_dict[key] = name_new return name_new
def resource_for_link(link, includes, resources=None, locale=None): """Returns the resource that matches the link""" if resources is not None: cache_key = "{0}:{1}:{2}".format( link['sys']['linkType'], link['sys']['id'], locale ) if cache_key in resources: return resources[cache_key] for i in includes: if (i['sys']['id'] == link['sys']['id'] and i['sys']['type'] == link['sys']['linkType']): return i return None
def i32(x): """Converts a long (for instance 0x80005000L) to a signed 32-bit-int. Python2.4 will convert numbers >= 0x80005000 to large numbers instead of negative ints. This is not what we want for typical win32 constants. Usage: >>> i32(0x80005000L) -2147363168 """ # x > 0x80000000L should be negative, such that: # i32(0x80000000L) -> -2147483648L # i32(0x80000001L) -> -2147483647L etc. return (x & 0x80000000 and -2 * 0x40000000 or 0) + int(x & 0x7fffffff)
def validateLabel(value): """Validate label for group/nodeset/pset. """ if 0 == len(value): raise ValueError("Label for boundary condition group/nodeset/pset in mesh not specified.") return value
def color_picker(total_items, current_item, palette): """ pick color for charge states""" if total_items < len(palette): return palette[current_item] if total_items >= len(palette): return palette[current_item % len(palette)]
def escape_csv_formula(value): """ Escapes formulae (strings that start with =) to prevent spreadsheet software vulnerabilities being exploited :param value: the value being added to a CSV cell """ if isinstance(value, str) and value.startswith('='): return "'" + value return value
def _unpack_proportions(values): """List of N-1 ratios from N proportions""" if len(values) == 1: return [] half = len(values) // 2 (num, denom) = (sum(values[half:]), sum(values[:half])) assert num > 0 and denom > 0 ratio = num / denom return ( [ratio] + _unpack_proportions(values[:half]) + _unpack_proportions(values[half:]) )
def _prepare_params(params): """return params as SmashGG friendly query string""" query_string = '' if len(params) == 0: return query_string prefix = '?expand[]=' query_string = prefix + '&expand[]='.join(params) return query_string
def _generateParams(param_dict): """ Will take a dictionary, where *potentially* some values are lists. Will return a list of dictionaries with no lists, where each possible list member combination is included. """ keys = param_dict.keys() list_key = None for key in keys: if isinstance(param_dict[key], list): list_key = key break if list_key is None: return [param_dict] new_dics = [] for list_val in param_dict[list_key]: new_dict = {} for key in keys: if key is not list_key: new_dict[key] = param_dict[key] else: new_dict[key] = list_val new_dics.append(new_dict) ret = [] for dic in new_dics: ret += _generateParams(dic) return ret
def jaccard(seq1, seq2): """ Obtained from: https://github.com/doukremt/distance/blob/master/distance/_simpledists.py on Sept 8 2015 Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. """ set1, set2 = set(seq1), set(seq2) return 1 - len(set1 & set2) / float(len(set1 | set2))
def lowercase(str): """ Function to convert a given string to lowercase Args: str: the string Return: Lowercase str """ return str.lower()
def interpolate(p1, p2, d_param, dist): """ interpolate between points """ alpha = min(max(d_param / dist, 0.), 1.) return (1. - alpha) * p1 + alpha * p2
def sum_square_difference(ceiling): """Compute the difference between the sum of squares and the square of the sum of the natural numbers up to and including the provided ceiling. """ numbers = range(ceiling + 1) sum_squares = sum(map(lambda number: number**2, numbers)) square_sum = sum(numbers)**2 sum_square_difference = square_sum - sum_squares return sum_square_difference
def make_plural(condition, value): """Stupidly makes value plural (adds s) if condition is True""" return str(value) + "s" if condition else str(value)
def arrange_lyrics(arrangement, song_data): """ Returns the lyrics of a song arranged by the song data. :param arrangement: A list of strings describing the arrangement of the lyrics. We do not do checking in this function, so the type must be correct. :type arrangement: `list(str)` :param song_data: Song information, conforming to the model sepecification in `datamodels.py`. One of the keys has to be `lyrics`. :type song_data: `dict` :returns: `arranged_lyrics`, the lyrics arranged according to the specified arrangement. :rtype: `str` """ # Now, we allow the default arrangement to be set. arranged_lyrics = "" for a in arrangement: arranged_lyrics += song_data["lyrics"][a] arranged_lyrics += "\n\n" # print(arranged_lyrics) return arranged_lyrics
def get_current_row(row_info, join_key_value): """check if key is in the csv""" if join_key_value in row_info: return row_info[join_key_value] return {}
def twos_complement_to_int(val, length=4): """ Two's complement representation to integer. We assume that the number is always negative. 1. Invert all the bits through the number 2. Add one """ invertor = int('1' * length, 2) return -((int(val, 2) ^ invertor) + 1)
def training_folds(fold, k=10): """ Return a tuple of all the training folds. >>> training_folds(7) (0, 1, 2, 3, 4, 5, 6, 8, 9) """ assert fold < k return tuple(num for num in range(10) if num != fold)
def get_csv(csv, type): """ Convert a comma separated string of values to list of given type :param csv: Comma separated string :type csv: str :param type: a type casting function, e.g. float, int, str :type type: function :returns: A list of values of type type :rtype: list[type] """ if type==str: return [str(itm).strip() for itm in csv.split(',')] else: return [type(itm) for itm in csv.split(',')]
def partition_set(elements, relation=None, innerset=False, reflexive=False, transitive=False): """Returns the equivlence classes from `elements`. Given `relation`, we test each element in `elements` against the other elements and form the equivalence classes induced by `relation`. By default, we assume the relation is symmetric. Optionally, the relation can be assumed to be reflexive and transitive as well. All three properties are required for `relation` to be an equivalence relation. However, there are times when a relation is not reflexive or transitive. For example, floating point comparisons do not have these properties. In this instance, it might be desirable to force reflexivity and transitivity on the elements and then, work with the resulting partition. Parameters ---------- elements : iterable The elements to be partitioned. relation : function, None A function accepting two elements, which returns `True` iff the two elements are related. The relation need not be an equivalence relation, but if `reflexive` and `transitive` are not set to `False`, then the resulting partition will not be unique. If `None`, then == is used. innerset : bool If `True`, then the equivalence classes will be returned as frozensets. This means that duplicate elements (according to __eq__ not `relation`) will appear only once in the equivalence class. If `False`, then the equivalence classes will be returned as lists. This means that duplicate elements will appear multiple times in an equivalence class. reflexive : bool If `True`, then `relation` is assumed to be reflexive. If `False`, then reflexivity will be enforced manually. Effectively, a new relation is considered: relation(a,b) AND relation(b,a). transitive : bool If `True`, then `relation` is assumed to be transitive. If `False`, then transitivity will be enforced manually. Effectively, a new relation is considered: relation(a,b) for all b in the class. Returns ------- eqclasses : list The collection of equivalence classes. lookup : list A list relating where lookup[i] contains the index of the eqclass that elements[i] was mapped to in `eqclasses`. """ if relation is None: from operator import eq relation = eq lookup = [] if reflexive and transitive: eqclasses = [] for _, element in enumerate(elements): for eqclass_idx, (representative, eqclass) in enumerate(eqclasses): if relation(representative, element): eqclass.append(element) lookup.append(eqclass_idx) # Each element can belong to *one* equivalence class break else: lookup.append(len(eqclasses)) eqclasses.append((element, [element])) eqclasses = [c for _, c in eqclasses] else: def belongs(element, eqclass): for representative in eqclass: if not relation(representative, element): return False if not reflexive: if not relation(element, representative): return False if transitive: return True else: # Test against all members # python optimizes away this line, so it never actually # gets executed during tests... continue # pragma: no cover # Then it equals all memembers symmetrically. return True eqclasses = [] for _, element in enumerate(elements): for eqclass_idx, eqclass in enumerate(eqclasses): if belongs(element, eqclass): eqclass.append(element) lookup.append(eqclass_idx) # Each element can belong to one equivalence class break else: lookup.append(len(eqclasses)) eqclasses.append([element]) if innerset: eqclasses = [frozenset(c) for c in eqclasses] else: eqclasses = [tuple(c) for c in eqclasses] return eqclasses, lookup
def cap_match_string(match): """ Attach beginning of line and end of line characters to the given string. Ensures that raw topics like /test do not match other topics containing the same string (e.g. /items/test would result in a regex match at char 7) regex goes through each position in the string to find matches - this forces it to consider only the first position :param match: a regex :return: """ return '^' + match + '$'
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1]) # computing the sum_area sum_area = S_rec1 + S_rec2 # find the each edge of intersect rectangle left_line = max(rec1[1], rec2[1]) right_line = min(rec1[3], rec2[3]) top_line = max(rec1[0], rec2[0]) bottom_line = min(rec1[2], rec2[2]) # judge if there is an intersect if left_line >= right_line or top_line >= bottom_line: return 0 else: intersect = (right_line - left_line) * (bottom_line - top_line) return intersect / (sum_area - intersect)
def get_single_pos(chunk_containing_pos): """Return only first pos and it's content.""" pos_char_end_idx = chunk_containing_pos.find(" ") pos = chunk_containing_pos[:pos_char_end_idx] pos_content = chunk_containing_pos[(pos_char_end_idx + 1) :] return pos, pos_content
def contains_any(haystack, needles): """Tests if any needle is a substring of haystack. Args: haystack: a string needles: list of strings Returns: True if any element of needles is a substring of haystack, False otherwise. """ for n in needles: if n in haystack: return True return False
def format_internal_tas(row): """Concatenate TAS components into a single field for internal use.""" # This formatting should match formatting in dataactcore.models.stagingModels concatTas tas = ''.join([ row['allocation_transfer_agency'] if row['allocation_transfer_agency'] else '000', row['agency_identifier'] if row['agency_identifier'] else '000', row['beginning_period_of_availa'] if row['beginning_period_of_availa'].strip() else '0000', row['ending_period_of_availabil'] if row['ending_period_of_availabil'].strip() else '0000', row['availability_type_code'].strip() if row['availability_type_code'].strip() else ' ', row['main_account_code'] if row['main_account_code'] else '0000', row['sub_account_code'] if row['sub_account_code'] else '000' ]) return tas
def signature_payload(headers, body = None): """Converts a message into a payload to be fed to the signature algorithm. The Checkout API requires every request and response to be signed. The first step in the signature process is to convert the request or response into a payload string. This function does that. Args: headers: A dictionary of headers in the message (must include all checkout- headers, others optional) body: (optional) A bytes object containing the body to be sent Returns: A string object ready for signature computation. """ hs = [] for hn, hd in headers.items(): hn = hn.lower() if hn.startswith("checkout-"): hs.append((hn, hd)) return b"\n".join([ hn.encode() + b":" + hd.encode() for hn, hd in sorted(hs, key=lambda x: x[0])] + ([body] if body is not None else [b""]))
def keep_comment(text, min_ascii_fraction=0.75, min_length=1): """ For purposes of vocabulary creation ignore non-ascii documents """ len_total = len(text) if len_total < min_length: return False len_ascii = sum(c.isalpha() for c in text) frac_ascii = float(len_ascii) / float(len_total) if frac_ascii < min_ascii_fraction: return False return True
def rep1(s): """REGEX: build repeat 1 or more.""" return s + '+'
def rshift(val, n): """ Implements signed right-shift. See: http://stackoverflow.com/a/5833119/15677 """ return (val % 0x100000000) >> n
def checkTrustline(asset :str, issuer:str, available_assets: list) -> bool: """ Check if in the balances of the account an asset like that alredy exists to establish a trustline """ for elem in available_assets: if elem["sponsor"] == asset: return True return False
def verse(bottle): """Sing a verse""" bottle_str = str(bottle) s1 = 's' if bottle > 1 else '' s2 = 's' if bottle != 2 else '' next_bottle = str(bottle - 1) if bottle > 1 else 'No more' return '\n'.join([ f'{bottle_str} bottle{s1} of beer on the wall,', f'{bottle_str} bottle{s1} of beer,', 'Take one down, pass it around,', # f'{str(bottle - 1)} bottle{s2} of beer on the wall!' if bottle > 1 else 'No more bottles of beer on the wall!' f'{next_bottle} bottle{s2} of beer on the wall!' ])
def sort_key(string): """e.g., sort 'INT8' before 'INT16'""" return string.replace("8", "08")
def param_to_string(parameters) -> str: """Convert a list / tuple of parameters returned from IE to a string""" if isinstance(parameters, (list, tuple)): return ', '.join([str(x) for x in parameters]) else: return str(parameters)
def str_to_var_name(verbose_name): """Convert a string to a variable compatible name. Examples: IP Addresses > ip_addresses """ return verbose_name.lower().replace(" ", "_").replace("-", "_")
def rebuild(expr): """ Rebuild a SymPy tree This function recursively calls constructors in the expression tree. This forces canonicalization and removes ugliness introduced by the use of Basic.__new__ """ try: return type(expr)(*list(map(rebuild, expr.args))) except Exception: return expr
def spike_height(x, x_old): """ Compute the size of a trending spike (normed - constant units). """ # Sign of trending spike sign = 1.0 if x < x_old: sign = -1.0 # Magnitude mag = abs(x**0.25 - x_old**0.25) # Minnow boost mag *= 1.0 + 2E4/(x + 100.0)**2 return sign*mag
def abaqus_to_meshio_type(element_type): """Map Abaqus elment type to meshio types. Parameters ---------- element_type : str Abaqus element type (e.g C3D8R) Returns ------- str Meshio element type (e.g. hexahedron) """ # trusss if "T2D2" in element_type or "T3D2" in element_type: return "line" if "T2D3" in element_type or "T3D3" in element_type: return "line3" # beams if "B21" in element_type or "B31" in element_type: return "line" if "B22" in element_type or "B32" in element_type or "B33" in element_type: return "line3" # surfaces if "S4" in element_type or "R3D4" in element_type: return "quad" if "S8" in element_type: return "quad8" if "S8" in element_type: return "quad9" if "S3" in element_type or "M3D3" in element_type or "R3D3" in element_type: return "triangle" if "STRIA6" in element_type: return "triangle6" # volumes if "C3D8" in element_type or "EC3D8" in element_type or "SC8" in element_type: return "hexahedron" if "C3D20" in element_type: return "hexahedron20" if "C3D4" in element_type: return "tetra" if "C3D4H" in element_type: return "tetra4" if "C3D10" in element_type: return "tetra10" if "C3D6" in element_type: return "wedge"
def checkio(list): """ sums even-indexes elements and multiply at the last """ soma=0 if len(list)>0: for pos, item in enumerate(list): if pos%2==0: soma=soma+item mult=soma*list[-1] return mult else: return 0
def _determine_levels(index): """Determine the correct levels argument to groupby.""" if isinstance(index, (tuple, list)) and len(index) > 1: return list(range(len(index))) else: return 0
def transform_input_ids(input_ids_0, input_ids_1, tokenizer_func): """ Take the input ids for sequences 0 and 1 (claim and evidence) and a tokenizer function. Apply function to tuples of claim-evidence. Return list of token type ids. """ transformed_ids = list(map( lambda ids_tuple: tokenizer_func(ids_tuple[0], ids_tuple[1]), zip(input_ids_0, input_ids_1) )) return transformed_ids
def split_with_spaces(sentence): """ Takes string with partial sentence and returns list of words with spaces included. Leading space is attached to first word. Later spaces attached to prior word. """ sentence_list = [] curr_word = "" for c in sentence: if c == " " and curr_word != "": # append space to end of non-empty words # assumed no more than 1 consecutive space. sentence_list.append(curr_word+" ") curr_word = "" else: curr_word += c # add trailing word that does not end with a space if len(curr_word) > 0: sentence_list.append(curr_word) return sentence_list
def appro(point: tuple, offset: tuple) -> tuple: """Add offset to point. point: tuple(x, y, z) offset: tuple(x, y, z) return: tuple(x, y, z) """ new_point = list() for p, o in zip(point, offset): new_point.append(p + o) return tuple(new_point)
def _tree_to_sequence(c): """ Converts a contraction tree to a contraction path as it has to be returned by path optimizers. A contraction tree can either be an int (=no contraction) or a tuple containing the terms to be contracted. An arbitrary number (>= 1) of terms can be contracted at once. Note that contractions are commutative, e.g. (j, k, l) = (k, l, j). Note that in general, solutions are not unique. Parameters ---------- c : tuple or int Contraction tree Returns ------- path : list[set[int]] Contraction path Examples -------- >>> _tree_to_sequence(((1,2),(0,(4,5,3)))) [(1, 2), (1, 2, 3), (0, 2), (0, 1)] """ # ((1,2),(0,(4,5,3))) --> [(1, 2), (1, 2, 3), (0, 2), (0, 1)] # # 0 0 0 (1,2) --> ((1,2),(0,(3,4,5))) # 1 3 (1,2) --> (0,(3,4,5)) # 2 --> 4 --> (3,4,5) # 3 5 # 4 (1,2) # 5 # # this function iterates through the table shown above from right to left; if type(c) == int: return [] c = [c] # list of remaining contractions (lower part of columns shown above) t = [] # list of elementary tensors (upper part of colums) s = [] # resulting contraction sequence while len(c) > 0: j = c.pop(-1) s.insert(0, tuple()) for i in sorted([i for i in j if type(i) == int]): s[0] += (sum(1 for q in t if q < i), ) t.insert(s[0][-1], i) for i in [i for i in j if type(i) != int]: s[0] += (len(t) + len(c), ) c.append(i) return s
def truncate_string(string, length=80, title=True): """ Returns a truncated string with '..' at the end if it is longer than the length parameter. If the title param is true a span with the original string as title (for mouse over) is added. """ if string is None: return '' # pragma: no cover if len(string) > length + 2: if title: title = string.replace('"', '') string = '<span title="' + title + '">' + string[:length] + '..' + '</span>' else: string = string[:length] + '..' return string
def add_bit_least_significant(pixel_part, bit): """Change least significant bit of a byte""" pixel_part_binary = bin(pixel_part) last_bit = int(pixel_part_binary[-1]) calculated_last_bit = last_bit & bit return int(pixel_part_binary[:-1]+str(calculated_last_bit), 2)
def fix_tags(tags): """ Handles the tags Checks if the tags are an array, if yes make them a comma-separated string """ if isinstance(tags, list): tags = ",".join(tags) return tags
def dict_to_device(data, device): """Move dict of tensors to device""" out = dict() for k in data.keys(): out[k] = data[k].to(device) return out
def get_list_of_primes_pre_calc(gen): """ Same as get list of primes, but used when prime sieve is already done :param gen: The prime sieve :return: A list containing only the prime numbers """ return [ind for ind, i in enumerate(gen) if i]
def get_line_cf(x0, y0, x1, y1): """ line y = ax + b. returns a,b """ sameX = abs(x1 - x0) < 1e-6 sameY = abs(y1 - y0) < 1e-6 if sameX and sameY: return None, None if sameX: a = None b = x0 elif sameY: a = 0 b = y0 else: a = (y1 - y0) / (x1 - x0) b = (y0 * x1 - x0 * y1) / (x1 - x0) return a, b
def get_colour_code(colour): """ This function returns the integer associated with the input string for the ARC problems. """ colour_mapping = {'black':0, 'blue':1, 'red':2, 'green':3, 'yellow':4, 'grey':5, 'pink':6, 'orange':7, 'babyblue':8, 'maroon':9} return colour_mapping[colour]
def parse_duration(row: str) -> int: """Parses duration value string 'Xhr', 'Ymin' or 'Zsec' and returns (X::Y::Z) as seconds""" import re def filter_digits(s): return "".join(re.findall('\d+', s)) seconds = 0 if 'hr' in row: hr, row = row.split('hr') seconds += int(filter_digits(hr)) * 3600 if 'min' in row: min, row = row.split('min') seconds += int(filter_digits(min)) * 60 if 'sec' in row: sec, _ = row.split('sec') seconds += int(filter_digits(sec)) return seconds
def flatten_list_of_lists(l): """ http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ return [item for sublist in l for item in sublist]
def get_api_request_dict(properties): """Build a resource based on a list of properties given as key-value pairs. Leave properties with empty values out of the inserted resource. :param properties: a dict :return: """ resource = {} for p in properties: # Given a key like "snippet.title", split into "snippet" and "title", where # "snippet" will be an object and "title" will be a property in that object. prop_array = p.split('.') ref = resource for pa in range(0, len(prop_array)): is_array = False key = prop_array[pa] # For properties that have array values, convert a name like # "snippet.tags[]" to snippet.tags, and set a flag to handle # the value as an array. if key[-2:] == '[]': key = key[0:len(key)-2:] is_array = True if pa == (len(prop_array) - 1): # Leave properties without values out of inserted resource. if properties[p]: if is_array: if isinstance(properties[p], str): ref[key] = properties[p].split(',') else: ref[key] = properties[p] else: ref[key] = properties[p] elif key not in ref: # For example, the property is "snippet.title", but the resource does # not yet have a "snippet" object. Create the snippet object here. # Setting "ref = ref[key]" means that in the next time through the # "for pa in range ..." loop, we will be setting a property in the # resource's "snippet" object. ref[key] = {} ref = ref[key] else: # For example, the property is "snippet.description", and the resource # already has a "snippet" object. ref = ref[key] return resource
def getRelationsAndRNByCharacter(cname: str, rn: int) -> str: """Return a query to get the relation and Ryu Number of a character. The query retrieves the character's name, as well as the title and Ryu Number of all games that the character appears in with a Ryu Number greater than or equal to the passed value. The resulting tuple takes the following form for appears_in as AI and game as G: `(AI.cname: str, AI.gtitle: str, G.ryu_number: int)` """ return (f"SELECT AI.cname, AI.gtitle, G.ryu_number " f"FROM appears_in AS AI " f"JOIN game AS G ON G.title=AI.gtitle " f"WHERE cname='{cname}' AND G.ryu_number>={rn};" )
def xd(t, L, StartTime): """ defines the input to the system """ # Pick your input as one of the xd definitions below # For an unshaped input xd = L * (t >= StartTime) # For a ZV shaped input, designed for 1HZ and no damping # xd = 0.5 * L * (t >= StartTime) + 0.5 * L * (t >= StartTime+0.5) return xd
def _translate(messages, language_code): """Helper function to assist in handling multiple translations of a message.""" try: the_message = messages[language_code] except KeyError: the_message = messages["en"] return the_message
def get_error(exception=None): """Gets errno from exception or returns one""" return getattr(exception, "errno", 1)
def build_html_component_with_html(html_string): """ This function builds the html string for a component. :param html_string: html_string of the component :param title: Title of the html component :return: html_string """ html = """ <div class="row"> <div class="col-md-12"> {0} </div> </div> """.format(html_string) return html
def makepath(dirname, basename): """ Create a full path given the directory name and the base name Args: dirname: path to directory basename: name of file or directory """ return dirname + "/" + basename
def makeSentenceLengths(s): """ use the text in the input string s to create the sentencelength dictionary.""" frequency = 0 length = 0 LoW = s.split() # splits the string into string of each word sl = [] # list of sentence lengths # create loop to iterate through all indices # check if word has .!?, if not add oen to length # if yes, check if length value is in dicitonary, if yest + 1 to frequency, if not add to dictionary, 1 frequency # continue for i in LoW: length += 1 if i[-1] in '?!.': sl += [length] length = 0 sentencelengths = {} for l in sl: # iterate through length (l) in the list if l not in sentencelengths: sentencelengths[l] = 1 elif l in sentencelengths: sentencelengths[l] += 1 return sentencelengths
def filter_empty_values(mapping_object: dict) -> dict: """Remove entries in the dict object where the value is `None`. >>> foobar = {'username': 'rafaelcaricio', 'team': None} >>> filter_empty_values(foobar) {'username': 'rafaelcaricio'} :param mapping_object: Dict object to be filtered """ return {key: val for key, val in mapping_object.items() if val is not None}
def extract_cluster_from_device_id(_id): """Parse cluster from device ID""" if not _id: return None parts = _id.split(".") if len(parts) != 2 or not parts[1]: return None node_details = parts[1].split("_") if len(node_details) != 2 or not node_details[0]: return None return node_details[0]
def stop(job_id, event, action, resource, _count): """App stop event type""" job_name = '{}:event={}:action={}'.format( resource, event, action ) func_kwargs = dict( job_id=job_id, app_name=resource, ) return job_name, func_kwargs
def Distance_modulus_to_distance(dm, absorption=0.0): """ Returns the distance in kpc for a distance modulus. dm (float): distance modulus. absorption (float): absorption to the source. """ distance = 10.**(((dm-absorption)+5.)/5.) / 1000. return distance
def truncate(x, d): """ Truncate a number to d decimal places Args: x: the number to truncate d: the number of decimal places; -ve to truncate to powers Returns: truncated number """ if d > 0: mult = 10.0 ** d return int(x * mult) / mult else: mult = 10 ** (-d) return int(x / mult) * mult
def next_code(value: int, mul: int = 252533, div: int = 33554393) -> int: """ Returns the value of the next code given the value of the current code The first code is `20151125`. After that, each code is generated by taking the previous one, multiplying it by `252533`, and then keeping the remainder from dividing that value by `33554393` """ return (value * mul) % div
def color_spot(htmlcolorcode, text=None): """ HTML snippet: span with class 'colorspot' and `htmlcolorcode` as background color """ if text is None: text = htmlcolorcode return u'<span class="colorspot" style="background-color:%s;">&nbsp;&nbsp;&nbsp;</span>&nbsp;%s' % (htmlcolorcode, text)
def url_Exomol_iso(molecule,isotope_full_name): """return URL for ExoMol for isotope """ url=u"https://exomol.com/data/molecules/"+str(molecule)+"/"+str(isotope_full_name) return url
def slice_1(x): """Given x return slice(x, x).""" return slice(x, x)
def get_typed_features(features, ftype="string", parents=None): """ Recursively get a list of all features of a certain dtype :param features: :param ftype: :param parents: :return: a list of tuples > e.g. ('A', 'B', 'C') for feature example['A']['B']['C'] """ if parents is None: parents = [] typed_features = [] for name, feat in features.items(): if isinstance(feat, dict): if feat.get("dtype", None) == ftype or feat.get("feature", {}).get( ("dtype", None) == ftype ): typed_features += [tuple(parents + [name])] elif "feature" in feat: if feat["feature"].get("dtype", None) == ftype: typed_features += [tuple(parents + [name])] elif isinstance(feat["feature"], dict): typed_features += get_typed_features( feat["feature"], ftype, parents + [name] ) else: for k, v in feat.items(): if isinstance(v, dict): typed_features += get_typed_features( v, ftype, parents + [name, k] ) elif name == "dtype" and feat == ftype: typed_features += [tuple(parents)] return typed_features
def scrap_middle_name(file): """ Getting folder name from the splitted file_name If the file_name is data_FXVOL_20130612.xml, then the folder name returned will be 'FXVOL' """ if file.startswith('data_') and file.endswith('.xml') and file.count('_') == 2: split_name = file.split('_') return split_name[1]
def convertWQElementsStatusToWFStatus(elementsStatusSet): """ Defined Workflow status from its WorkQeuueElement status. :param: elementsStatusSet - dictionary of {request_name: set of all WQE status of this request, ...} :returns: request status Here is the mapping between request status and it GQE status 1. acquired: if all the GQEs are either Available or Negotiating - Work is still in GQ but not LQ 2. running-open: if at least one of the GQEs are in Acquired status - at least some work is in LQ 3. running-closed: if all the GQEs are in Running or complted status no Available Negotiating or Acquired status. all the work is in WMBS db (in agents) 4. completed: if all the GQEs are in 'Done', 'Canceled' status. - all work is finsed in wmbs (excluding cleanup, logcollect) 5. failed: if all the GQEs are in Failed status. If the workflow has multiple GQEs and only a few are in Failed status, then just follow the usual request status. CancelRequest status treated as transient status. """ if len(elementsStatusSet) == 0: return None available = set(["Available", "Negotiating", "Failed"]) acquired = set(["Acquired"]) running = set(["Running"]) completed = set(['Done', 'Canceled', "Failed"]) failed = set(["Failed"]) if elementsStatusSet == acquired: return "running-open" elif elementsStatusSet == running: return "running-closed" elif elementsStatusSet == failed: return "failed" elif elementsStatusSet <= available: # if all the elements are Available status. return "acquired" elif elementsStatusSet <= completed: # if all the elements are Done or Canceled status return "completed" elif elementsStatusSet <= failed: # if all the elements are in Failed staus return "failed" elif acquired <= elementsStatusSet: # if one of the elements are in Acquired status return "running-open" elif running <= elementsStatusSet: # if one of the elements in running status but no elements are # Acquired or Assigned status return "running-closed" else: # transitional status. Negotiating status won't be changed. return None
def is_symmetrical(matrix): """Checks if a matrix is symmetrical""" result = True for i in range(8): row = matrix[i*8:(i+1)*8] result = result and (row[0:3] == row[4:]) return result
def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ # raise NotImplementedError possibleSet = set() # turn = player(board) for i in range(len(board)) : for j in range(len(board[i])): if board[i][j] == None : newBoard = (i,j) possibleSet.add(newBoard) return possibleSet