content
stringlengths
42
6.51k
def _compute_scores(distances, i, n, f): """Compute scores for node i. Arguments: distances {dict} -- A dict of dict of distance. distances[i][j] = dist. i, j starts with 0. i {int} -- index of worker, starting from 0. n {int} -- total number of workers f {int} -- Total number of Byzantine workers. Returns: float -- krum distance score of i. """ s = [distances[j][i] ** 2 for j in range(i)] + [ distances[i][j] ** 2 for j in range(i + 1, n) ] _s = sorted(s)[: n - f - 2] return sum(_s)
def int_half(angle: float) -> int: """Assume angle is approximately an even integer, and return the half :param angle: Float angle :type angle: float :return: Integer half of angle :rtype: int """ # two_x = round(angle) assert not two_x % 2 return two_x // 2
def parse_entry(entry): """ Separates an entry into a numeric value and a tied/fixed flag, if present. Parameters ---------- entry : str An f26 parameter entry. Returns ------- value : float The entry value. flag : str The fitting flag associated with the entry. """ if entry.startswith('nan'): value = float(entry[:3]) flag = entry[3:] else: i = -1 while not entry[i].isdigit(): i -= 1 if i != -1: value = float(entry[:i + 1]) flag = entry[i + 1:] else: value = float(entry) flag = '' return value, flag
def __getILPResults(anchor2bin2var): """ interpret the ILP solving results. Map anchor to locations """ # get the mapping from anchor to bin anchor_to_selected_bin = {} for anchor, bin2var in anchor2bin2var.items(): for bin, var in bin2var.items(): var_value = round(var.x) assert abs(var.x - var_value) < 0.000001, var.x # check that we are correctly treating each ILP var as CONTINOUS if var_value == 1: anchor_to_selected_bin[anchor] = bin return anchor_to_selected_bin
def parse_tags_to_string(tags): """Create string representation of a dictionary of tags. :param tags: dictionary containing "tag" meta data of a variant. :returns: the string representation of the tags. """ str_tags = [] for key, value in sorted(tags.items()): # If key is of type 'Flag', print only key, else 'key=value' if value is True: str_tags.append(key) else: if isinstance(value, (tuple, list)): value = ','.join((str(x) for x in value)) str_tags.append('{}={}'.format(key, value)) return ';'.join(str_tags)
def convertToCamelCase(input): """ Converts a string into camel case :param input: string to be converted :return: camelCase version of string """ # split input splitWords = input.split(' ') # check if only one word, and if so, just return the input as is if len(splitWords) == 1: return input # convert words after first word to title titleCaseWords = [word.title() for word in splitWords[1:]] # combine all words together output = ''.join([splitWords[0]] + titleCaseWords) return output
def _justify(texts, max_len, mode='right'): """ Perform ljust, center, rjust against string or list-like """ if mode == 'left': return [x.ljust(max_len) for x in texts] elif mode == 'center': return [x.center(max_len) for x in texts] else: return [x.rjust(max_len) for x in texts]
def get_dot_product(first_vector, second_vector): """ (dict, dict) -> dict The function takes two dictionaries representing vectors as input. It returns the dot product between the two vectors. >>> v1 = {'a' : 3, 'b': 2} >>> v2 = {'a': 2, 'c': 1, 'b': 2} >>> get_dot_product(v1, v2) 10 >>> v3 = {'a' : 5, 'b': 3, 'c' : 3} >>> v4 = {'d': 1} >>> get_dot_product(v3, v4) 0 >>> v5 = {} >>> v6 = {} >>> get_dot_product(v5, v6) 0 >>> v7 = {'a' : 2, 'b' : -2, 'c' : -4} >>> v8 = {'a' : 1, 'b' : 3, 'c' : 2} >>> get_dot_product(v7, v8) -12 """ # initialize dot product variable dot_product = 0 # compute product for values whose key is in both vectors for key in first_vector: if key in second_vector: # add product to the sum product = first_vector[key] * second_vector[key] dot_product += product # return sum of products (dot product) return dot_product
def hcp_coord_test(x, y, z): """Test for coordinate in HCP grid""" m = x+y+z return m % 6 == 0 and (x-m//12) % 3 == 0 and (y-m//12) % 3 == 0
def level_to_xp(level: int): """ :type level: int :param level: Level :return: XP """ if level == 0: return 0 xp = (5 * (level ** 2)) + (60 * level) + 100 return xp
def add_index_to_pairs(ordered_pairs): """ Creates a dictionary where each KEY is a integer index and the VALUE is a dictionary of the x,y pairs Parameters ---------- ordered_pairs: dict dictionary that has been ordered Returns ------- dict this dictionary has OUTER_KEY = integer index INNER_KEY = x value VALUE = y value """ new_dict = {} for i, x in enumerate(ordered_pairs): new_dict[i] = {x: ordered_pairs[x]} return new_dict
def deenrich_list_with_image_json(enriched_image_list): """ De-enrich the image list :param enriched_image_list: List of enriched images :return: De-enriched image list """ # For each image delete image json for image in enriched_image_list: if "image_json" in image: del image["image_json"] return enriched_image_list
def sgn(value): """ Signum function """ if value < 0: return -1 if value > 0: return 1 return 0
def find_mmsi_in_message_type_5(transbordement_couple, messages_type5): """Add the ship types to a possible transhipment by using AIS message of type 5 """ for x in messages_type5: # message_types5 is a list of messages if x['mmsi'] == transbordement_couple[0][0]: transbordement_couple[0][0].append(x['shiptype']) if x['mmsi'] == transbordement_couple[1][0]: transbordement_couple[1][0].append(x['shiptype']) return None
def humanbytes(size): """Convert Bytes To Bytes So That Human Can Read It""" if not size: return "" power = 2 ** 10 raised_to_pow = 0 dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} while size > power: size /= power raised_to_pow += 1 return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
def plain_to_ssml(text): """ Incomplete. Returns inputted text. """ ssml_text = text return ssml_text
def retrieve_usernames(list_of_ids, dict_of_ids_to_names): """ For retrieving usernames when we've already gotten them from twitter. For saving on API requests """ usernames = [] for user_id in list_of_ids: usernames.append(dict_of_ids_to_names[user_id]) return usernames
def clear_mod_zeroes(modsdict): """Clear zeroes from dictionary of attributes and modifiers.""" for item in modsdict.keys(): if modsdict[item] == "0": modsdict[item] = "" return modsdict
def ArgumentStringToInt(arg_string): """ convert '1234' or '0x123' to int params: arg_string: str - typically string passed from commandline. ex '1234' or '0xA12CD' returns: int - integer representation of the string """ arg_string = arg_string.strip() if arg_string.find('0x') >=0: return int(arg_string, 16) else: return int(arg_string)
def _process_config(config): """ Make sure config object has required values """ required_fields = [ "api_key", "from_email", "to_email", ] for field in required_fields: if field not in config: raise ValueError("required field {} not found in config file".format(field)) return config
def elide_sequence(s, flank=5, elision="..."): """Trims the middle of the sequence, leaving the right and left flanks. Args: s (str): A sequence. flank (int, optional): The length of each flank. Defaults to five. elision (str, optional): The symbol used to represent the part trimmed. Defaults to '...'. Returns: str: The sequence with the middle replaced by ``elision``. Examples: >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ") 'ABCDE...VWXYZ' >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=3) 'ABC...XYZ' >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", elision="..") 'ABCDE..VWXYZ' >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12) 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=12, elision=".") 'ABCDEFGHIJKL.OPQRSTUVWXYZ' """ elided_sequence_len = flank + flank + len(elision) if len(s) <= elided_sequence_len: return s return s[:flank] + elision + s[-flank:]
def cipher(text, shift, encrypt=True): """ Shifts alphabetic characters in a string by a given amount such as with a Caesar cipher. Parameters ---------- text : str A string to be shifted. Non-alphabetic letters are unchanged. shift : int The number of positions to shift letters in the text. encrypt : bool Whether to shift in the positive direction rather than the negative direction (default True). Returns ------- str The shifted text. Examples -------- >>> cipher("Hi all!", 2) 'Jk cnn!' >>> cipher("Jk cnn!", 2, encrypt=False) 'Hi all!' """ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if index == -1: new_text += c else: new_index = index + shift if encrypt == True else index - shift new_index %= len(alphabet) new_text += alphabet[new_index:new_index+1] return new_text
def unreserve(item): """Removes trailing underscore from item if it has one. Useful for fixing mutations of Python reserved words, e.g. class. """ if hasattr(item, 'endswith') and item.endswith('_'): return item[:-1] else: return item
def derivativeSignsToExpressionTerms(valueLabels, signs, scaleFactorIdx=None): """ Return remap expression terms for summing derivative[i] * sign[i] * scaleFactor :param valueLabels: List of node value labels to possibly include. :param signs: List of 1 (no scaling), -1 (scale by scale factor 1) or 0 (no term). :param scaleFactorIdx: Optional index of local scale factor to scale all non-zero terms. Default None means no extra scaling. """ expressionTerms = [] for i in range(len(valueLabels)): if signs[i] == 1: expressionTerms.append((valueLabels[i], ([scaleFactorIdx] if scaleFactorIdx else []))) elif signs[i] == -1: expressionTerms.append((valueLabels[i], ([1, scaleFactorIdx] if scaleFactorIdx else [1]))) return expressionTerms
def clamp(mini, maxi, val): """Clamp the value between min and max""" return min(maxi, max(mini, val))
def code(text: str) -> str: """Make text to code.""" return f'`{text}`'
def make_obj_list(obj_or_objs): """This method will take an object or list of objects and ensure a list is returned. Example: >>> make_obj_list('hello') ['hello'] >>> make_obj_list(['hello', 'world']) ['hello', 'world'] >>> make_obj_list(None) [] """ if not obj_or_objs: return [] if not isinstance(obj_or_objs, (list, tuple)): return [obj_or_objs] return obj_or_objs
def output_as_percentage(num, fractional_digits=1): """Output a percentage neatly. Parameters ---------- num: float The number to make into a percentage. fractional_digits: int Number of digits to output as fractions of a percent. If not supplied, there is no reduction in precision. Returns ------- str The percentage. """ if (fractional_digits is not None): format_str = '%%.%.df' % (fractional_digits) # creates format string else: format_str = '%f' return('%s%%' % (format_str % (num)))
def count_non_zeros(*iterables): """Returns total number of non 0 elements in given iterables. Args: *iterables: Any number of the value None or iterables of numeric values. """ result = 0 for iterable in iterables: if iterable is not None: result += sum(1 for element in iterable if element != 0) return result
def assert_false(test, obj, msg=None): """ Raise an error if the test expression is true. The test can be a function that takes the context object. """ if (callable(test) and test(obj)) or test: raise AssertionError(msg) return obj
def deep_dictionary_check(dict1: dict, dict2: dict) -> bool: """Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict.""" if dict1.keys() != dict2.keys(): return False for key in dict1: if isinstance(dict1[key], dict) and not deep_dictionary_check(dict1[key], dict2[key]): return False elif dict1[key] != dict2[key]: return False return True
def copy_list(l): """generates a copy of a list """ if not isinstance(l, list): return None return l[:]
def amdahls(x, p): """ Computes Amdal's Law speed-up :param x: is the speedup of the part of the task that benefits from improved system resources :param p: is the proportion of execution time that the part benefiting from improved resources originally occupied :return: the computed speed-up """ return 1. / (1. - p + p/x)
def convert(x): """ >>> convert('0x10') (16, 'x') >>> convert('0b10') (2, 'b') >>> convert('0o7') (7, 'o') >>> convert('10') (10, 'd') >>> convert('0b11 & 0b10'), convert('0b11 | 0b10'), convert('0b11 ^ 0b10') ((2, 'b'), (3, 'b'), (1, 'b')) >>> convert('11 & 10'), convert('11 | 10'), convert('11 ^ 10') ((10, 'd'), (11, 'd'), (1, 'd')) """ if x.startswith('0x'): return (eval(x), 'x') elif x.startswith('0b'): return (eval(x), 'b') elif x.startswith('0o'): return (eval(x), 'o') else: return (eval(x), 'd')
def interval_intersection(min1, max1, min2, max2): """ Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval, or None if they do not overlap. """ left, right = max(min1, min2), min(max1, max2) if left < right: return left, right return None
def lin_model_single_ele(m, x, b): """ Returns a single y for a given x using a line """ return (m*x) + b
def get_class_name(obj): """ Get class name attribute. :param Any obj: Object for get class name. :return: Class name :rtype: str """ if isinstance(obj, type): return obj.__name__ return obj.__class__.__name__
def tabularize(rows, col_spacing=2): """*rows* should be a list of lists of strings: [[r1c1, r1c2], [r2c1, r2c2], ..]. Returns a list of formatted lines of text, with column values left justified.""" # Find the column widths: max_column_widths = [] for row in rows: while len(row) > len(max_column_widths): max_column_widths.append(0) for index, col in enumerate(row): if len(col) > max_column_widths[index]: max_column_widths[index] = len(col) # Now that we have the column widths, create the individual lines: output = [] for row in rows: line = '' for index, col in enumerate(row): line += col.ljust(max_column_widths[index]+col_spacing) output.append(line) return output
def get_resource_by_format(resources, format_type): """Searches an array of resources to find the resource that matches the file format type passed in. Returns the resource if found. Parameters: resources - An array of CKAN dataset resources For more information on the structure look at the web service JSON output, or reference: http://docs.ckan.org/en/latest/api-v2.html#model-api format_type - A string with the file format type to find (SHP, KML..) Returns: resource - A CKAN dataset resource if found. None if not found. For more information on the structure look at the web service JSON output, or reference: http://docs.ckan.org/en/latest/api-v2.html#model-api """ for resource in resources: current_format = resource['format'] if (str(current_format).strip().upper() == format_type.strip().upper()): return resource return None
def check_subtree(t1, t2): """ 4.1 O Check Subtree: T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree of T1. A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical. Args: t1, t2: BinaryTreeNode Returns: bool """ def traverse(haystack, needle): if haystack == None and needle == None: return True if haystack == None or needle == None: return False if haystack.value == needle.value and match(haystack, needle): return True return traverse(haystack.left, needle) or \ traverse(haystack.right, needle) def match(haystack, needle): if haystack == None or needle == None: return needle == haystack if haystack.value != needle.value: return False return match(haystack.left, needle.left) and \ match(haystack.right, needle.right) if t2 == None: return True return traverse(t1, t2)
def is_number(str_value): """ Checks if it is a valid float number """ try: float(str_value) return True except ValueError: return False
def simple_pos(arg): """ >>> result = jitii(simple_pos) """ if arg > 0: a = 1 else: a = 0 return a
def _remove_rewrite_frames(tb): """Remove stack frames containing the error rewriting logic.""" cleaned_tb = [] for f in tb: if 'ag__.rewrite_graph_construction_error' not in f[3]: cleaned_tb.append(f) return cleaned_tb
def conf_to_env_codename(cd): """ Args: cd: Config dict with the env. Returns: """ return f"{cd['env']['num_customers']}C{cd['env']['num_dcs']}W{cd['env']['num_commodities']}K{cd['env']['orders_per_day']}F{cd['env']['dcs_per_customer']}V"
def is_n_pandigital(n): """Tests if n is 1-len(n) pandigital.""" if len(str(n)) > 9: return False if len(str(n)) != len(set(str(n))): return False m = len(str(n)) digits = list(range(1, m+1)) filtered = [d for d in str(n) if int(d) in digits] return len(str(n)) == len(filtered)
def get_in(coll, path, default=None): """Returns a value at path in the given nested collection.""" for key in path: try: coll = coll[key] except (KeyError, IndexError): return default return coll
def dotProduct(vector1, vector2): """Returns the dot product of two vectors.""" if len(vector1) == len(vector2): return sum((vector1[i] * vector2[i] for i in range(len(vector1)))) return None
def score_alignment(identity, coverage, alpha=0.95): """T-score from the interactome3d paper.""" return alpha * (identity) * (coverage) + (1.0 - alpha) * (coverage)
def __to_float(val, digits): """Convert val into float with digits decimal.""" try: return round(float(val), digits) except (ValueError, TypeError): return float(0)
def fontawesomize(val): """Convert boolean to font awesome icon.""" if val: return '<i class="fa fa-check" style="color: green"></i>' return '<i class="fa fa-times" style="color: red"></i>'
def xor_hex_strings(str1, str2): """ Return xor of two hex strings. An XOR of two pieces of data will be as random as the input with the most randomness. We can thus combine two entropy sources in this way as a safeguard against one source being compromised in some way. For details, see http://crypto.stackexchange.com/a/17660 returns => <string> in hex format """ if len(str1) != len(str2): raise Exception("tried to xor strings of unequal length") str1_dec = int(str1, 16) str2_dec = int(str2, 16) xored = str1_dec ^ str2_dec return "{:0{}x}".format(xored, max(len(str1), len(str2)))
def process_input(values, puzzle_input, u_input): """Takes input from the user and records them in the location specified by the "value", and returns the resulting puzzle input """ puzzle_input[values[0]] = u_input return puzzle_input
def unnormalize_coefficients(n, D): """ Functional inverse of normalize_coefficients(n, D) :param n: integer dimension of the original space :param D: output from normalize_coefficients(n, D) :return: equivalent input D to normalize_coefficients(n, D) >>> D = forward_no_normalization([1,2,3,4]) >>> n = len(list(D.keys())) >>> Dnorm = normalize_coefficients(n, D) >>> D == Dnorm False >>> Dunnorm = unnormalize_coefficients(n, Dnorm) >>> D == Dunnorm True >>> Dnorm == Dunnorm False """ wold = n Dc = D.copy() while True: w = wold // 2 sq_norm = (n / (4 * w)) ** (1 / 2) if w > 0 else n ** (1 / 2) if w == 0: Dc[0, 0] = Dc[0, 0] / sq_norm break Dc.update({(w, i): Dc[(w, i)] / sq_norm for i in range(w)}) wold = w return Dc
def three_pad(s): """Pads a string, s, to length 3 with trailing X's""" if len(s) < 3: return three_pad(s + "X") return s
def biSearch(lista, el): """Necesita ser una lista ordenada""" ub = len(lista) -1 lb = 0 while(lb < ub+1): mid = (ub + lb) // 2 if lista[mid] == el: return True elif lista[mid] > el: ub = mid -1 elif lista[mid] < el: lb = mid +1 return False
def get_image_registry(image_name): """Extract registry host from Docker image name. Returns None if registry hostname is not found in the name, meaning that default Docker registry should be used. Docker image name is defined according to the following rules: - name := [hostname '/'] component ['/' component]* - hostname := hostcomponent ['.' hostcomponent]* [':' port-number] - hostcomponent := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ https://github.com/docker/distribution/blob/master/reference/reference.go """ components = image_name.split('/') if len(components) > 1 and any(sym in components[0] for sym in '.:'): return components[0]
def sphere_volume(r): """Return the volume of the sphere of radius 'r'. Use 3.14159 for pi in your computation. """ return (4 * 3.14159 / 3)*r**3
def isNumber(s: str) -> bool: """ Determines if a unicode string (that may include commas) is a number. :param s: Any unicode string. :return: True if s represents a number, False otherwise. """ s = s.replace(',', '') try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError) as e: pass return False
def main(stdin): """ Read in line. Parse line into list of words. Print word as a single count. """ for line in stdin: words = line.split() for word in words: print(("{word}\t{count}").format(word=word, count=1)) return None
def translate_aws_action_groups(groups): """ Problem - AWS provides the following five groups: - Permissions - ReadWrite - ListOnly - ReadOnly - Tagging The meaning of these groups was not immediately obvious to me. Permissions: ability to modify (create/update/remove) permissions. ReadWrite: Indicates a data-plane operation. ReadOnly: Always used with ReadWrite. Indicates a read-only data-plane operation. ListOnly: Always used with [ReadWrite, ReadOnly]. Indicates an action which lists resources, which is a subcategory of read-only data-plane operations. Tagging: Always used with ReadWrite. Indicates a permission that can mutate tags. So an action with ReadWrite, but without ReadOnly, is a mutating data-plane operation. An action with Permission never has any other groups. This method will take the AWS categories and translate them to one of the following: - List - Read - Tagging - ReadWrite - Permissions """ if "Permissions" in groups: return "Permissions" if "ListOnly" in groups: return "List" if "ReadOnly" in groups: return "Read" if "Tagging" in groups: return "Tagging" if "ReadWrite" in groups: return "Write" return "Unknown"
def is_prime(n): """returns True if n is prime, False otherwise""" for i in range(2, n): if n % i == 0: # not a prime number return False # if we reached so far, the number should be a prime number return True
def allocate_site_power_type(settlement, strategy): """ Shifts the site power type based onthe strategy. """ if strategy == 'baseline': return settlement elif strategy == 'smart_diesel_generators': return settlement elif strategy == 'smart_solar': return settlement elif strategy == 'pure_solar': settlement['on_grid'] = 'off_grid_solar' return settlement else: print('Did not recognize site power type strategy')
def get_last_n_letters(text, n): """ The below line is for unit tests >>> get_last_n_letters('This is for unit testing',4) 'ting' """ return text[-n:]
def _get_resource_type(attribute, root, type_, method): """Returns ``attribute`` defined in the resource type, or ``None``.""" if type_ and root.resource_types: types = root.resource_types r_type = [r for r in types if r.name == type_] r_type = [r for r in r_type if r.method == method] if r_type: if hasattr(r_type[0], attribute): if getattr(r_type[0], attribute) is not None: return getattr(r_type[0], attribute) return []
def split_attribute(input): """ properly split apart attribute strings, even when they have sub-attributes declated between []. :param input:the attribute string to split :return: dict containing the elements of the top level attribute string. Sub-attribute strings between '[]'s are appended to their parent, without processing, even if they contain '.' """ ret = [] # zero means we are not inside square brackets squareBrackets = 0 lastIndex = 0 for i in range(len(input)): if input[i] == '[': squareBrackets +=1 elif input[i] == ']': squareBrackets -=1 elif input[i] == '.' and squareBrackets == 0: ret.append(input[lastIndex:i]) lastIndex =i+1 #last element ret.append(input[lastIndex:]) return ret
def any_action_failed(results): """ Return `True` if some parallelized invocations threw exceptions """ return any(isinstance(res, Exception) for res in results)
def ind(x, a, b): """ Indicator function for a <= x <= b. Parameters ---------- x: int desired value a: int lower bound of interval b: upper bound of interval Returns ------- 1 if a <= x <= b and 0 otherwise. """ return (x >= a)*(x <= b)
def ksplit(key, mod_key=True): """ksplit takes a redis key of the form "label1:value1:label2:value2" and converts it into a dictionary for easy access""" item_list = key.split(':') items = iter(item_list) if mod_key: return {x.replace('-','_'):next(items) for x in items} else: return {x:next(items) for x in items}
def get_submission_variants(form_fields): """Extracts a list of variant ids from the clinvar submission form in blueprints/variants/clinvar.html (creation of a new clinvar submission). Args: form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and CASEDATA_HEADER Returns: clinvars: A list of variant IDs """ clinvars = [] # if the html checkbox named 'all_vars' is checked in the html form, then all pinned variants from a case should be included in the clinvar submission file, # otherwise just the selected one. if "all_vars" in form_fields: for field, value in form_fields.items(): if field.startswith("local_id"): clinvars.append(form_fields[field].replace("local_id@", "")) else: clinvars = [form_fields["main_var"]] # also a list, but has one element return clinvars
def parse_vec_files(vec_files_str: str): """ Examples -------- >>> parse_vec_files("w:123,c:456") {'w': '123', 'c': '456'} """ _ret = dict() vec_key_value = vec_files_str.split(",") for key_value in vec_key_value: key, value = key_value.split(":") _ret[key] = value return _ret
def unique_values_from_query(query_result): """Simplify Athena query results into a set of values. Useful for listing tables, partitions, databases, enable_metrics Args: query_result (dict): The result of run_athena_query Returns: set: Unique values from the query result """ return { value for row in query_result['ResultSet']['Rows'] for result in row['Data'] for value in list(result.values()) }
def circulo(raio): """calcula a area de um circulo""" area=3.14*(raio**2) return area
def Focal_length_eff(info_dict): """ Computes the effective focal length give the plate scale and the pixel size. Parameters ---------- info_dict: dictionary Returns --------- F_eff: float effective focal length in m """ # F_eff = 1./ (info_dict['pixelScale'] * # np.pi/(3600*180) / info_dict['pixelSize']) if isinstance(info_dict["focal_length"], dict): info_dict["foc_len"] = info_dict["focal_length"][info_dict["channel"]] else: info_dict["foc_len"] = info_dict["focal_length"] return info_dict
def get_cell_connection(cell, pin): """ Returns the name of the net connected to the given cell pin. Returns None if unconnected """ # Only for subckt assert cell["type"] == "subckt" # Find the connection and return it for i in range(1, len(cell["args"])): p, net = cell["args"][i].split("=") if p == pin: return net # Not found return None
def _collapse_results(parameters): """ When using cdp_run, parameters is a list of lists: [[Parameters], ...]. Make this just a list: [Parameters, ...]. """ output_parameters = [] for p1 in parameters: if isinstance(p1, list): for p2 in p1: output_parameters.append(p2) else: output_parameters.append(p1) return output_parameters
def _make_expr_time(param_name, param_val): """Generate query expression for a time-valued flight parameter.""" if param_val is None: return None, None # Summary attributes for each parameter... smmry_attr = {'time': ('time_coverage_start', 'time_coverage_end')} attr_min, attr_max = smmry_attr[param_name] if isinstance(param_val, list): oper = ('>=', '<=') elif isinstance(param_val, tuple): oper = ('>', '<') else: raise TypeError( f'{type(param_val)}: Invalid {param_name} value type') flight_expr = list() data_expr = list() for a, op, val in zip((attr_max, attr_min), oper, param_val): if val is None: continue data_expr.append(f'{param_name} {op} {val!r}') flight_expr.append(f'{a} {op} {val!r}') if len(flight_expr) > 1: flight_expr = '(' + ' AND '.join(filter(bool, flight_expr)) + ')' data_expr = '(' + ' and '.join(filter(bool, data_expr)) + ')' else: flight_expr = flight_expr[0] data_expr = data_expr[0] return (flight_expr, data_expr)
def location(text, index): """ Location of `index` in the `text`. Report row and column numbers when appropriate. """ if isinstance(text, str): line, start = text.count('\n', 0, index), text.rfind('\n', 0, index) column = index - (start + 1) return "{}:{}".format(line + 1, column + 1) else: return str(index + 1)
def calc_g(r, aa): """ DESCRIPTION TBD (FUNCTION USED IN GENERAL CONSTANTS). Parameters: r (float): radius aa (float): spin parameter (0, 1) Returns: g (float) """ return 2 * aa * r
def is_integer_like(val): """Returns validation of a value as an integer.""" try: value = int(val) return True except (TypeError, ValueError, AttributeError): return False
def normalize_wpsm_cost(raw_cost, highest, lowest): """ converts a raw_cost into the range (0,1), given the highest and lowest wpsm costs See: https://stackoverflow.com/questions/5294955/how-to-scale-down-a-range-of-numbers-with-a-known-min-and-max-value """ # print(raw_cost) # print("TURNED INTO") scaled_cost = ((1 - 0) * (raw_cost - lowest) / (highest - lowest)) # print(str(scaled_cost) + '\n') return scaled_cost
def get_input_addrs(tx): """ Takes tx object and returns the input addresses associated. """ addrs = [] # print("tx['inputs']: ", tx['inputs']) for x in tx['inputs']: try: addrs.append(x['prev_out']['addr']) except KeyError: continue return addrs #try: # return [x['prev_out']['addr'] for x in tx['inputs']] #except KeyError: # This happens when there's a coinbase transaction # return []
def intify(values: bytes, unsigned=False) -> int: """Convert bytes to int.""" return int.from_bytes(values, byteorder="little", signed=(not unsigned))
def formatCode(arg, type=""): """Converts formatting to one suited for discord "diff" = red; "css" = red-orange; "fix" = yellow; "ini" with [] = blue; "json" with "" = green; " " = none """ toSend = f"```{type}\n{arg}\n```" return toSend
def jet_power(F, m_dot): """Jet power of a rocket propulsion device. Compute the kinetic power of the jet for a given thrust level and mass flow. Reference: Goebel and Katz, equation 2.3-4. Arguments: F (scalar): Thrust force [units: newton]. m_dot (scalar): Jet mass flow rate [units: kilogram second**-1]. Returns: scalar: jet power [units: watt]. """ return F**2 / (2 * m_dot)
def translate_subset_type(subset_type): """Maps subset shortcut to full name. Args: subset_type (str): Subset shortcut. Returns: str: Subset full name. """ if subset_type == 'max': model = 'best' elif subset_type == 'random': model = 'random' elif subset_type == 'min': model = 'worst' else: raise ValueError('Undefined model version: "{}". Use "max", "min" or\ "random" instead.'.format(subset_type)) return model
def normRect(rect): """Normalize a bounding box rectangle. This function "turns the rectangle the right way up", so that the following holds:: xMin <= xMax and yMin <= yMax Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. Returns: A normalized bounding rectangle. """ (xMin, yMin, xMax, yMax) = rect return min(xMin, xMax), min(yMin, yMax), max(xMin, xMax), max(yMin, yMax)
def parse_cluster_pubsub_numpat(res, **options): """ Result callback, handles different return types switchable by the `aggregate` flag. """ aggregate = options.get('aggregate', True) if not aggregate: return res numpat = 0 for node_numpat in res.values(): numpat += node_numpat return numpat
def factorial_n(num): """ (int) -> float Computes num! Returns the factorial of <num> """ if isinstance(num, int) and num >= 0: product = 1 # Init while num: # As long as num is positive product *= num num -= 1 return product else: return 'Expected Positive integer'
def is_odd(n: int) -> bool: """ Checks whether n is an odd number. :param int n: number to check :returns bool: True if <n> is an odd number""" return bool(n & 1)
def loc_to_block_num(y, x): """ :param y: The y location of the cell. Precondition: 0 <= y < 9 :param x: The x location of the cell Precondition: 0 <= x < 9 :return: The number of the block the cell is located in """ return int(x/3)+int(y/3)*3
def inverted_list_index(l): """Given a list, return a list enumerating the indexes that gives the original list in order. Example: [3, 1, 2, 4] -> [1, 2, 0, 3] """ return [ i[0] for i in sorted(enumerate(l), key=lambda i: i[1]) ]
def sort_cards(cards): """Sort shuffled list of cards, sorted by rank. reference: http://pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/ """ card_order = {'A': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13} return sorted(cards, key=card_order.__getitem__)
def freeze(d): """Convert the value sets of a multi-valued mapping into frozensets. The use case is to make the value sets hashable once they no longer need to be edited. """ return {k: frozenset(v) for k, v in d.items()}
def insert_colon_break(words_list): """Doc.""" keys = ('case', 'default', 'private', 'public', 'protect') new_words_list = [] for words in words_list: if ':' in words and words[-1][:2] != '//' and words[0] in keys: index = words.index(':') + 1 new_words_list.append(words[:index]) new_words_list.append(words[index:]) else: new_words_list.append(words) return new_words_list
def _get_pymeos_path(package_name): """Takes a path starting with _pymeos.something and converts it into pymeos.something""" if package_name.startswith("_pymeos"): return package_name[1:] raise ValueError("Unsupported package name passed: " + package_name)
def find_nth_digit(n): """find the nth digit of given number. 1. find the length of the number where the nth digit is from. 2. find the actual number where the nth digit is from 3. find the nth digit and return ##------------------------------------------------------------------- """ length = 1 count = 9 start = 1 while n > length * count: n -= length * count length += 1 count *= 10 start *= 10 start += (n - 1) / length s = str(start) return int(s[(n - 1) % length])
def parse_purl(purl): """ Finds the purl in the body of the Eiffel event message and parses it :param purl: the purl from the Eiffel ArtC event :return: tuple: the artifact filename and the substring from the build path """ # pkg:<build_path>/<intermediate_directories>/ # <artifact_filename>@< build_number > # artifact_filename_and_build = purl.split('/')[-1] # artifact_filename = artifact_filename_and_build.split('@')[0] # build_path = purl.split('pkg:')[1].split('/artifacts')[0] # pkg:<intermediate_directories>/<artifact_filename>@<build_number>? # build_path=< build_path > # for when Eiffel Broadcaster is updated artifact_filename = purl.split('@')[0].split('/')[-1] build_path = purl.split('?build_path=')[-1] return artifact_filename, build_path
def GetNumberField(d: dict, item: str): """ Handles items not being present (lazy get) """ try: r = d[item] return r except: return 0.0
def check_alarm_input(alarm_time): """Checks to see if the user has entered in a valid alarm time""" if len(alarm_time) == 1: # [Hour] Format if alarm_time[0] < 24 and alarm_time[0] >= 0: return True if len(alarm_time) == 2: # [Hour:Minute] Format if alarm_time[0] < 24 and alarm_time[0] >= 0 and \ alarm_time[1] < 60 and alarm_time[1] >= 0: return True elif len(alarm_time) == 3: # [Hour:Minute:Second] Format if alarm_time[0] < 24 and alarm_time[0] >= 0 and \ alarm_time[1] < 60 and alarm_time[1] >= 0 and \ alarm_time[2] < 60 and alarm_time[2] >= 0: return True return False
def get_batch_size(batch): """ Returns the batch size in samples :param batch: List of input batches, if there is one input a batch can be either a numpy array or a list, for multiple inputs it can be tuple of lists or numpy arrays. """ if isinstance(batch, tuple): return get_batch_size(batch[0]) else: if isinstance(batch, list): return len(batch) else: return batch.shape[0]