content
stringlengths
42
6.51k
def _index_matching_predicate(seq, pred): """Return index of first item matching predicate. Args: seq - a list. pred - a function with one argument, returning True or False. Returns: index or None """ for i, v in enumerate(seq): if pred(v): return i return None
def RPL_STATSUPTIME(sender, receipient, message): """ Reply Code 242 """ return "<" + sender + ">: " + message
def set_underline(level: int, length: int) -> str: """Create an underline string of a certain length :param level: The underline level specifying the symbol to use :param length: The string length :return: Underline string """ underline_symbol = ["`", "#", "*", "-", "^", '"', "="] symbol_str = underline_symbol[level] * length return f"\n{symbol_str}\n"
def _ParseArgs(j2objc_args): """Separate arguments passed to J2ObjC into source files and J2ObjC flags. Args: j2objc_args: A list of args to pass to J2ObjC transpiler. Returns: A tuple containing source files and J2ObjC flags """ source_files = [] flags = [] is_next_flag_value = False for j2objc_arg in j2objc_args: if j2objc_arg.startswith('-'): flags.append(j2objc_arg) is_next_flag_value = True elif is_next_flag_value: flags.append(j2objc_arg) is_next_flag_value = False else: source_files.append(j2objc_arg) return (source_files, flags)
def axial_to_cubic(col, slant): """ Convert axial coordinate to its cubic equivalent. """ x = col z = slant y = -x - z return x, y, z
def strStr(haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ length_h = len(haystack) length_n = len(needle) for i in range(length_h - length_n + 1): if haystack[i:i + length_n] == needle: return i return -1
def rsa_ascii_decode(x:int,x_len:int) -> str: """ I2OSP aka RSA's standard ascii decoder. Decodes the integer X into multiple bytes and finally converts those ASCII codepoints into an ASCII string. :param x: Integer X to be converted to string. :param x_len: the length that the string will be. :return: A string which represents teh decoded value of X. """ X = [] string='' #max_len=len(x) if x>=pow(256,x_len): raise ValueError('Number is too large to fit in output string.') while x>0: X.append(int(x % 256)) x //=256 for i in range(x_len-len(X)): X.append(0) X=X[::-1] for i in range(len(X)): string+=chr(X[i]) return string
def _fix_structure(fields, seq): """Returns a string with correct # chars from db struct line. fields should be the result of line.split('\t') Implementation notes: Pairing line uses strange format: = is pair, * is GU pair, and nothing is unpaired. Cells are not padded out to the start or end of the sequence length, presumably to infuriate the unwary. I don't _think_ it's possible to convert these into ViennaStructures since we don't know where each helix starts and ends, and the lengths of each piece can vary. I'd be happy to be proven wrong on this... For some reason, _sometimes_ spaces are inserted, and _sometimes_ the cells are left entirely blank. Also, when there's a noncanonical pair in the helix, the helix is broken into two pieces, so counting pieces isn't going to work for figuring out the ViennaStructure. Expects as input the sequence and the raw structure line. """ num_blanks = 4 pieces = fields[num_blanks:] result = ['.'] * len(seq) for i, p in enumerate(pieces): if p and (p != ' '): result[i] = p return ''.join(result)
def Hllp(l, lp, x): """ Fiber collision effective window method auxiliary function """ if l == 2 and lp == 0: return x ** 2 - 1. if l == 4 and lp == 0: return 1.75 * x**4 - 2.5 * x**2 + 0.75 if l == 4 and lp == 2: return x**4 - x**2 if l == 6 and lp == 0: return 4.125 * x**6 - 7.875 * x**4 + 4.375 * x**2 - 0.625 if l == 6 and lp == 2: return 2.75 * x**6 - 4.5 * x**4 + 7. / 4. * x**2 if l == 6 and lp == 4: return x**6 - x**4 else: return x * 0.
def evaluateIdentifier(gold, pred): """ Performs an intrinsic evaluation of a Complex Word Identification approach. @param gold: A vector containing gold-standard labels. @param pred: A vector containing predicted labels. @return: Precision, Recall and F-1. """ #Initialize variables: precisionc = 0 precisiont = 0 recallc = 0 recallt = 0 #Calculate measures: for i in range(0, len(gold)): gold_label = gold[i] predicted_label = pred[i] if gold_label==predicted_label: precisionc += 1 if gold_label==1: recallc += 1 if gold_label==1: recallt += 1 precisiont += 1 precision = float(precisionc)/float(precisiont) recall = float(recallc)/float(recallt) fmean = 0.0 if precision==0.0 and recall==0.0: fmean = 0.0 else: fmean = 2*(precision*recall)/(precision+recall) #Return measures: return precision, recall, fmean
def file_path(name): """ Shortcut function to get the relative path to the directory which contains the data. """ return "./data/%s" % name
def get_center_coords(bounds): """ description: Return if center coords from bounds dict usage: ui_utils.get_center_coords(obj.info['bounds']) tags: ui, android, center, coords """ x = bounds['left'] + (bounds['right'] - bounds['left']) / 2 y = bounds['top'] + (bounds['bottom'] - bounds['top']) / 2 return (x, y)
def parse_list_result(match_list, raw_list): """Checks that a list of values matches the form specified in a format list. Entries in the match_list can either be tuples or single values. If a single value, e.g. a string or integer, then the corresponding entry in the raw_list must match exactly. For tuple items, the corresponding raw_list entry is converted and added to the results dictionary that is returned. Tuple entries consist of two elements: the key name to be used in the result and the function to call to convert the raw_list item. Example: parse_list_result( ['first:', ('1st', int), 'second:', ('2nd', float)], ['first:', '555', 'second:', '1.23'] ) would return {'1st': 555, '2nd': 1.23}. If elements 0 and 2 were not 'first:' and 'second:' respectively then an exception is thrown. Exceptions thrown by the conversion functions are not caught. """ if len(match_list) != len(raw_list): raise Exception('len("{}") != len("{}") ({}, {})'.format(match_list, raw_list, len(match_list), len(raw_list))) res = {} for idx, match in enumerate(match_list): data = raw_list[idx] if isinstance(match, tuple): key, conv_fn = match res[key] = conv_fn(data) else: if match != data: raise Exception('"{}" != "{}" ({})'.format(match, data, idx)) return res
def oct2hex(x): """ Convert octal string to hexadecimal string. For instance: '32' -> '1a' """ return hex(int(x, 8))[2:]
def set_view_timeout(config): """Set timeout duration for generating static images.""" return config["settings"].get("view_timeout", 60)
def all_permutations(options): """ Generates a list of all possible permutations of a list of options """ solutions = [[]] for option_set in options: solutions = [item + [option] for item in solutions for option in option_set] return solutions
def dump_datetime(value): """Deserialize datetime object into string form for JSON processing.""" if value is None: return None return value.strftime("%Y-%m-%d") + ' ' + value.strftime("%H:%M:%S")
def CombineImages(center, left, right, measurement, correction): """ Combine the image paths from `center`, `left` and `right` using the correction factor `correction` Returns ([imagePaths], [measurements]) """ imagePaths = [] imagePaths.extend(center) imagePaths.extend(left) imagePaths.extend(right) measurements = [] measurements.extend(measurement) measurements.extend([x + correction for x in measurement]) measurements.extend([x - correction for x in measurement]) return (imagePaths, measurements)
def my_square(y): """takes a value and return the squared value. uses the * operator """ return(y ** 2)
def to_byte(string): """ convert byte to string in pytohn2/3 """ return string.encode()
def distance(num1, num2, num3): """ CHECK IF ABSOLUTE DISTANCE IS CLOSE OR FAR AWAY {CLOSE = 1, FAR >=2} :param:num1:num2:num3 :type:int :return if absolute distance :rtype:bool """ if abs(num1 - num2) is 1 or abs(num1 - num3) is 1: return True elif abs(num1 - num2) >= 2: return True elif abs(num1 - num3) >= 2: return True elif abs(num2 - num3) >= 2: return True else: return False
def is_output(port): """Judge whether the port is an output port.""" try: return port.mode == 'w' except Exception: return False
def volumeFraction(concentration=1,molWeight=17,density=1.347): """ molWeight is kDa concentration in mM density g/ml """ concentration_mg_ml = concentration*molWeight volume_fraction = concentration_mg_ml/density/1e3 return volume_fraction
def log2(num: int) -> int: """ Integer-valued logarigthm with base 2. If ``n`` is not a power of 2, the result is rounded to the smallest number. """ return num.bit_length() - 1
def validate_distance(distance: float) -> float: """ Validates the distance of an object. :param distance: The distance of the object. :return: The validated distance. """ if distance < 0: raise ValueError("The distance must be zero or positive.") return distance
def sum_digits(s): """ assumes s a string Returns an int that is the sum of all of the digits in s. If there are no digits in s it raises a ValueError exception. For example, sum_digits("a;35d4") returns 12. """ ans = 0 ValueErrorCnt = 0 for element in s: try: ans += int(element) except ValueError: ValueErrorCnt += 1 if ValueErrorCnt == len(s): raise ValueError() else: continue return ans
def _format_explain_result(explain_result): """format output of an `explain` mongo command Return a dictionary with 2 properties: - 'details': the origin explain result without the `serverInfo` part to avoid leaing mongo server version number - 'summary': the list of execution statistics (i.e. drop the details of candidate plans) if `explain_result` is empty, return `None` """ if explain_result: explain_result.pop('serverInfo', None) if 'stages' in explain_result: stats = [ stage['$cursor']['executionStats'] for stage in explain_result['stages'] if '$cursor' in stage ] else: stats = [explain_result['executionStats']] return { 'details': explain_result, 'summary': stats, } return None
def make_file_safe_api_name(api_name): """Make an api name safe for use in a file name""" return "".join([c for c in api_name if c.isalpha() or c.isdigit() or c in (".", "_", "-")])
def RedFilter(c): """Returns True if color can be classified as a shade of red""" if (c[0] > c[1]) and (c[0] > c[2]) and (c[1] == c[2]): return True else: return False
def recursively_find_changes(s, token): """ method 2 recursively find the method # result: 73682 """ # line continuation token? \ or implicit without any token like C++ #stop of the recursive method if len(token) == 1: if s%token[0] == 0: # s=0 ? return 1; return 1 #token[-1] == 1, it must be true else: return 0 else: # len>1 count=0 #if(s%token[0] == 0): count = count +1 # all using one kind of change, #error: do NOT acount that s%token[0] != 0 #count = count + recursively_find_changes(s, token[1:])# do not use this kind of change for i in range( 0, int(s/token[0])+1 ): # count = count +recursively_find_changes(s-i*token[0], token[1:]) # all using one kine change return count
def _get_path(dir_name): """ Get path. """ if dir_name: path = dir_name + "/" else: path = "" return path
def remove_des(name): """ remove 'Class A Common Stock' and 'Common Stock' from listing names """ if name.endswith("Class A Common Stock"): name = name[:-21] if name.endswith("Common Stock"): name = name[:-13] return name
def pickdate(target, datelist): """ Pick the date from a list of tuples. target: an index > 1 """ return list( map( lambda x : (x[0], x[target]), datelist ) )
def collatz(number): """An algorithm that no matter what positive number you give, it will return 1.""" number = int(number) if number % 2 == 0: print(number // 2) return number // 2 elif number % 2 == 1: result = 3 * number + 1 print(result) return result
def calculate_dmr(delay_list: list, deadline: float) -> float: """Returns the node's deadline miss ratio (DMR).""" miss = 0 for delay in delay_list: if delay > deadline: miss += 1 return miss/len(delay_list)
def get_from_module(attrname): """ Returns the Python class/method of the specified |attrname|. Typical usage pattern: m = get_class("this.module.MyClass") my_class = m(**kwargs) """ parts = attrname.split('.') module = '.'.join(parts[:-1]) m = __import__(module) for comp in parts[1:]: m = getattr(m, comp) return m
def split(string, divider): """Splits a string according at the first instance of a divider.""" pieces = string.split(divider) return [pieces[0].strip(), divider.join(pieces[1:])]
def from_s3_input(slug, file): """ Returns the S3 URL for an input fiule required by the DAG. """ return ( '{{ conf.get("core", "reach_s3_prefix") }}' '/%s/%s' ) % (slug, file)
def forwardToName(fwdLambda): """Unwrap a 'forward definition' lambda to a name. Maps functions like 'lambda: X' to the string 'X'. """ if hasattr(fwdLambda, "__code__"): if fwdLambda.__code__.co_code == b't\x00S\x00': return fwdLambda.__code__.co_names[0] if fwdLambda.__code__.co_code == b'\x88\x00S\x00': return fwdLambda.__code__.co_freevars[0] if fwdLambda.__name__ == "<lambda>": return "UnknownForward" else: return fwdLambda.__name__
def hex2dec(inp,verbose=True): """This code has been converted from the IDL source code at http://www.astro.washington.edu/docs/idl/cgi-bin/getpro/library32.html?HEX2DEC Convert hexadecimal representation to decimal integer. Explanation : A hexadecimal string is converted to a decimal integer and can be displayed or returned or both or neither. Use : decimal = hex2dec.hex2dec(hex, verbose=True) Inputs : hex - hexadecimal string Opt. Inputs : None Outputs : See below Opt. Outputs: decimal - the decimal integer equivalent of the input. Keywords : verbose - if given the decimal number is printed to the terminal. Default = True. Calls : None Restrictions: Input must be a string. Side effects: None Category : Utils, Numerical Prev. Hist. : None Written : C D Pike, RAL, 7-Oct-93 Modified : Converted to Python, D. Jones, January 2014 Version : Version 1, 7-Oct-93 """ # # trap invalid input # # # initialise output etc # out = 0 n = len(inp) # # convert each character in turn # for i in range(n)[::-1]: try: c = (inp[i]).upper() except: c = inp[i] if c == 'A': c = 10 elif c == 'B': c = 11 elif c == 'C': c = 12 elif c == 'D': c = 13 elif c == 'E': c = 14 elif c == 'F': c = 15 else: if c != int(c): print('Invalid character **',c,'**') out = 0 return(out) out = out + int(c)*16**int(n-1-i) # # if not silenced, print result # if verbose: print(out) return(out)
def validate_fixed(datum, schema, **kwargs): """ Check that the data value is fixed width bytes, matching the schema['size'] exactly! Parameters ---------- datum: Any Data being validated schema: dict Schema kwargs: Any Unused kwargs """ return isinstance(datum, bytes) and len(datum) == schema["size"]
def find_sponsor(sponsorid, sponsor_dictionary): """ Given a sponsorid, find the org with that sponsor. Return True and URI if found. Return false and None if not found """ try: uri = sponsor_dictionary[sponsorid] found = True except: uri = None found = False return [found, uri]
def agg_across_entities(entity_lists_by_doc): """ Return aggregate entities in descending order by count. """ if not entity_lists_by_doc or len(entity_lists_by_doc) == 0: return [] result_set = {} for doc_id in entity_lists_by_doc.keys(): cur_list = entity_lists_by_doc[doc_id] for name, count in cur_list.items(): result_set[name] = result_set.get(name, 0) + count return [ it[0] for it in sorted(result_set.items(), key=lambda x: x[1], reverse=True) ]
def _obscure_email_part(part): """ For parts longer than three characters, we reveal the first two characters and obscure the rest. Parts up to three characters long are handled as special cases. We reveal no more than 50% of the characters for any part. :param part: :return: """ if not part: return part # If part is None or the empty string, there's nothing to obscure length = len(part) if length == 1: return '*' # 0% revealed, 100% obscured if length == 2: return part[:1] + '*' # 50% revealed, 50% obscured if length == 3: return part[:1] + '**' # 33% revealed, 66% obscured if length > 3: return part[:2] + '*' * (length - 2)
def isStateKey(key): """ :returns: C{True} iff this key refers to a state feature :rtype: bool """ return '\'s ' in key
def Cross3(a, b): """Return the cross product of two vectors, a x b.""" (ax, ay, az) = a (bx, by, bz) = b return (ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx)
def parse_file_string(filestring): """ >>> parse_file_string("File 123: ABC (X, Y) Z") ('ABC (X, Y) Z', '') >>> parse_file_string("File 123: ABC (X) Y (Z)") ('ABC (X) Y', 'Z') >>> parse_file_string("File: ABC") ('ABC', '') >>> parse_file_string("File 2: A, B, 1-2") ('A, B, 1-2', '') """ if filestring.strip()[-1] != ")": filestring=filestring.strip()+"()" if ':' in filestring: rhs = filestring.partition(":")[2] else: rhs = filestring chunks = rhs.split('(') indname = '('.join(chunks[:-1]) units = chunks[-1].replace(')','') return indname.strip(), units.strip()
def dmp_copy(f, u): """Create a new copy of a polynomial `f` in `K[X]`. """ if not u: return list(f) v = u-1 return [ dmp_copy(c, v) for c in f ]
def _format_training_params(params): """Convert dict pof parameters to the CLI format {"k": "v"} --> "--k v" Args: params (dict): Parameters Returns: str: Command line params """ outputs = [] for k, v in params.items(): if isinstance(v, bool): if v: outputs.append(f"--{k}") else: outputs.append(f"--{k} {v}") return " ".join(outputs)
def append_keys(results, search_key, keys): """ defaultdict(list) behaviour for keys record If search_key exists in results the keys list is appended to the list stored at that key. Otherwise a new list containing the keys is created and stored at that key. Args: results (dict): Results dictionary search_key (str): Key to use to access results keys (list): List of object store keys to access Returns: dict: Results dictionary """ if search_key in results: results[search_key]["keys"].extend(keys) else: results[search_key] = {"keys": keys} return results
def Kelvin_F(Fahrenheit): """Usage: Convert to Kelvin from Fahrenheit Kelvin_F(Fahrenheit)""" return (Fahrenheit-32) * 5/9 + 273.15
def _get_spec_for_keyword(t_spec, key): """Grabs the var tuple for a specific key. Needed since variable name is in tuple :param t_spec: Thrift spec for function/class :param key: Variable key name to get :return: None or spec tuple """ for _, arg_spec in t_spec.items(): if arg_spec[1] == key: return arg_spec return None
def generate_region_info(region_params): """Generate the region_params list in the tiling parameter dict Args: region_params (dict): A dictionary mapping each region-specific parameter to a list of values per fov Returns: list: The complete set of region_params sorted by run """ # define the region params list region_params_list = [] # iterate over all the region parameters, all parameter lists are the same length for i in range(len(region_params['region_start_x'])): # define a dict containing all the region info for the specific fov region_info = { rp: region_params[rp][i] for rp in region_params } # append info to region_params region_params_list.append(region_info) return region_params_list
def strformat_to_bytes(strformat): """ Convert a string (e.g. "5M") to number of bytes (int) """ suffixes = {'B': 1} suffixes['K'] = 1000*suffixes['B'] suffixes['M'] = 1000*suffixes['K'] suffixes['G'] = 1000*suffixes['M'] suffixes['T'] = 1000*suffixes['G'] suffix = strformat[-1] amount = int(strformat[:-1]) return amount*suffixes[suffix]
def is_anion_cation_bond(valences, ii, jj): """ Checks if two given sites are an anion and a cation. :param valences: list of site valences :param ii: index of a site :param jj: index of another site :return: True if one site is an anion and the other is a cation (from the valences) """ if valences == "undefined": return True if valences[ii] == 0 or valences[jj] == 0: return True return (valences[ii] > 0 > valences[jj]) or (valences[jj] > 0 > valences[ii])
def get_aligned_size(n: int) -> int: """ Return the smallest multiple of 4KiB not less than the total of the loadable segments. (In other words, the size will be returned as-is if it is an exact multiple of 4KiB, otherwise it is rounded up to the next higher multiple of 4KiB.) """ return n if n % 4096 == 0 else ((n // 4096) + 1) * 4096
def _year_number_to_string(year): """Converts year from number to string. :param year: Integer year. :return: year_string: String in format "yyyy" (with leading zeros if necessary). """ return '{0:04d}'.format(int(year))
def create_prof_dict(profs): """ Creates a dictionary of professors with key being their pid """ professors = {} for p in profs: if (p['pid'] not in professors.keys() and p['last_name'] != None): professors[p['pid']] = p professors[p['pid']]['reviews'] = [] return professors
def area_trapezium(base1: float, base2: float, height: float) -> float: """ Calculate the area of a trapezium. >>> area_trapezium(10, 20, 30) 450.0 >>> area_trapezium(-1, -2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, 2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, -2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, 2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, -2, 3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(1, -2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values >>> area_trapezium(-1, 2, -3) Traceback (most recent call last): ... ValueError: area_trapezium() only accepts non-negative values """ if base1 < 0 or base2 < 0 or height < 0: raise ValueError("area_trapezium() only accepts non-negative values") return 1 / 2 * (base1 + base2) * height
def create_node_instance_task_dependencies(graph, tasks_and_node_instances, reverse=False): """ Creates dependencies between tasks if there is an outbound relationship between their node instances. """ def get_task(node_instance_id): for task, node_instance in tasks_and_node_instances: if node_instance.id == node_instance_id: return task return None for task, node_instance in tasks_and_node_instances: dependencies = [] for relationship_instance in node_instance.outbound_relationship_instances: dependency = get_task(relationship_instance.target_node_instance.id) if dependency: dependencies.append(dependency) if dependencies: if reverse: for dependency in dependencies: graph.add_dependency(dependency, task) else: graph.add_dependency(task, dependencies)
def has_time_layer(layers): """Returns `True` if there is a time/torque layer in `layers. Returns `False` otherwise""" return any(layer.time for layer in layers if not layer.is_basemap)
def atof(text): """ This function is auxiliary for the natural sorting of the paths names""" try: retval = float(text) except ValueError: retval = text return retval
def htk_to_ms(htk_time): """ Convert time in HTK (100 ns) units to ms """ if type(htk_time)==type("string"): htk_time = float(htk_time) return htk_time / 10000.0
def iobes_iob(tags): """ IOBES -> IOB """ new_tags = [] for i, tag in enumerate(tags): if tag == 'rel': new_tags.append(tag) elif tag.split('-')[0] == 'B': new_tags.append(tag) elif tag.split('-')[0] == 'I': new_tags.append(tag) elif tag.split('-')[0] == 'S': new_tags.append(tag.replace('S-', 'B-')) elif tag.split('-')[0] == 'E': new_tags.append(tag.replace('E-', 'I-')) elif tag.split('-')[0] == 'O': new_tags.append(tag) else: raise Exception('Invalid format!') return new_tags
def is_end_of_file(fp): """ check if it is the end of file. """ read_size = 8 dummy = fp.read(8) if len(dummy) != read_size: return True else: fp.seek(-read_size, 1) return False
def benchmark_sort_key(benchmark): """Returns the key that may be used to sort benchmarks by label.""" if not "label" in benchmark: return "" return benchmark["label"]
def psi(alpha, t): """Evaluate Paul's wavelet""" return 1./(t+1J)**(alpha+1)
def to_number(X): """Convert the input to a number.""" try: return X.item() except AttributeError: return X
def isValidMove(x, y): """ Return True if the coordinates are on the board, otherwise False. """ return x >= 0 and x <= 59 and y >= 0 and y <= 14
def _build_jinja2_expr_tmp(jinja2_exprs): """Build a template to evaluate jinja2 expressions.""" exprs = [] tmpls = [] for var, expr in jinja2_exprs.items(): tmpl = f"{var}: >-\n {{{{ {var} }}}}" if tmpl not in tmpls: tmpls.append(tmpl) if expr.strip() not in exprs: exprs.append(expr.strip()) return "\n".join(exprs + tmpls)
def argtest(*args): """ Test filter: returns arguments as a concatenated string. """ return '|'.join(str(arg) for arg in args)
def dijkstra_path(graph, start): """ Find the shortest paths between nodes using dijkstra algorithm. :param list graph: List of lists(adjacency matrix), that represents the graph. :param int start: Starting vertex. Search runs from here. :returns: List with the shortest paths to all possible nodes from the provided start. """ graph_length = len(graph) is_visited = [False] * graph_length cost = [float("inf")] * graph_length cost[start] = 0 # We already in starting position, so the cost is zero min_cost = 0 # This will show us whether we move on by graph or not while min_cost < float("inf"): is_visited[start] = True for i, vertex in enumerate(graph[start]): if vertex != 0 and not is_visited[i]: if cost[i] > vertex + cost[start]: cost[i] = vertex + cost[start] min_cost = float("inf") for vertex_index in range(graph_length): if min_cost > cost[vertex_index] and not is_visited[vertex_index]: min_cost = cost[vertex_index] start = vertex_index return cost
def calcMeanSD(useme): """ A numerically stable algorithm is given below. It also computes the mean. This algorithm is due to Knuth,[1] who cites Welford.[2] n = 0 mean = 0 M2 = 0 foreach x in data: n = n + 1 delta = x - mean mean = mean + delta/n M2 = M2 + delta*(x - mean) // This expression uses the new value of mean end for variance_n = M2/n variance = M2/(n - 1) """ mean = 0.0 M2 = 0.0 sd = 0.0 n = len(useme) if n > 1: for i,x in enumerate(useme): delta = x - mean mean = mean + delta/(i+1) # knuth uses n+=1 at start M2 = M2 + delta*(x - mean) # This expression uses the new value of mean variance = M2/(n-1) # assume is sample so lose 1 DOF sd = pow(variance,0.5) return mean,sd
def grv(struct, position): """ This function helps to convert date information for showing proper filtering """ if position == "year": size = 4 else: size = 2 if struct[position][2]: rightnow = str(struct[position][0]).zfill(size) else: if position == "year": rightnow = "____" else: rightnow = "__" return rightnow
def join_bucket_paths(*items): """ Build bucket path :param items: list[str] -- path items :return: str -- path """ return '/'.join(item.strip('/ ') for item in items)
def sort_minio_node_candidates(nodes): """ to select a candidate node for minio install we sort by - amount of cpu: the node with the most cpu but least used - amount of sru: the node with the most sru but least used """ def key(node): return (-node['total_resources']['cru'], -node['total_resources']['sru'], node['used_resources']['cru'], node['used_resources']['sru']) return sorted(nodes, key=key)
def describe_stats(state_dict): """Describe and render a dictionary. Usually, this function is called on a ``Solver`` state dictionary, and merged with a progress bar. Args: state_dict (dict): the dictionary to showcase Returns: string: the dictionary to render. """ stats_display = "" for idx, (key, value) in enumerate(state_dict.items()): if type(value) == float: if idx > 0: stats_display += " | " stats_display += f"{str(key).capitalize()[:4]}.: {value:.4f}" return stats_display
def BigUnion(iter): """ :param iter: Iterable collection of sets :return: The union of all of the sets """ union = set() for s in iter: union.update(s) return union
def canonical_url(url): """Strip URL of protocol info and ending slashes """ url = url.lower() if url.startswith("http://"): url = url[7:] if url.startswith("https://"): url = url[8:] if url.startswith("www."): url = url[4:] if url.endswith("/"): url = url[:-1] return url
def group_mols_by_container_index(mol_lst): """Take a list of MyMol.MyMol objects, and place them in lists according to their associated contnr_idx values. These lists are accessed via a dictionary, where they keys are the contnr_idx values themselves. :param mol_lst: The list of MyMol.MyMol objects. :type mol_lst: list :return: A dictionary, where keys are contnr_idx values and values are lists of MyMol.MyMol objects :rtype: dict """ # Make the dictionary. grouped_results = {} for mol in mol_lst: if mol is None: # Ignore molecules that are None. continue idx = mol.contnr_idx if not idx in grouped_results: grouped_results[idx] = [] grouped_results[idx].append(mol) # Remove redundant entries. for key in list(grouped_results.keys()): grouped_results[key] = list(set(grouped_results[key])) return grouped_results
def _get_layer_name(name): """ Extracts the name of the layer, which is compared against the config values for `first_conv` and `classifier`. The input is, e.g., name="res_net/remove/fc/kernel:0". We want to extract "fc". """ name = name.replace(":0", "") # Remove device IDs name = name.replace("/remove/", "/") # Auxiliary intermediate levels name = name.split("/", 1)[-1] # Remove prefix, e.g., "res_net" name = name.rsplit("/", 1)[0] # Remove last part, e.g., "kernel" return name
def norm3d(x, y, z): """Calculate norm of vector [x, y, z].""" return (x * x + y * y + z * z) ** 0.5
def _split_vars(input_str: str) -> list: """Split variables into a list. This function ensures it splits variables based on commas not inside default values or annotations but those between variables only. Brackets, commas, and parentheses inside strings will not count. """ input_str = input_str.rstrip() parent_count = 0 bracket_count = 0 last_read = 0 str_count = 0 output = [] for i, char in enumerate(input_str): if char in "\"'": str_count = 0 if str_count == 1 else 1 if str_count == 0: if char == "(": parent_count += 1 elif char == ")": parent_count -= 1 elif char == ",": if bracket_count == 0 and parent_count == 0: output.append(input_str[last_read:i]) last_read = i + 1 elif char == "[": bracket_count += 1 elif char == "]": bracket_count -= 1 _last_var = input_str[last_read: len(input_str)] if _last_var: output.append(_last_var) return output
def performance_data(label, value, uom="", warn="", crit="", mini="", maxi=""): """ defined here: http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN201 """ formatted_string = "%(label)s=%(value)s%(uom)s;%(warn)s;%(crit)s;%(mini)s;%(maxi)s" % locals() # Get rid of spaces formatted_string = "".join(formatted_string.split()) return formatted_string
def int_tuple(arg): """Convert a string of comma separated numbers to a tuple of integers""" args = arg.split(',') try: return tuple([int(e) for e in args]) except ValueError: raise ValueError('Expected a comma separated list of integers, ' + 'found %s' % arg)
def preprocessing(Time): """Returns important range of time in which the celebrities enter the room params: Time {2D array containing entering and leaving time of each celebrity}""" impRange= Time.copy() impRange = list(set([a[0] for a in impRange])) impRange.sort() return impRange
def calc_tree_width(height, txcount): """Efficently calculates the number of nodes at given merkle tree height""" return (txcount + (1 << height) - 1) >> height
def square(number: int) -> int: """Calculate the number of grains. :param number: int - the number of square on the chessboard. :return: int - the number of grains on the given square number. """ if not 1 <= number <= 64: raise ValueError("square must be between 1 and 64") return 1 << (number - 1)
def parse_ndenovo_exac(info, clinSig): """Rm benign variants greater than 1% bc these were used to train mpc""" if clinSig == 'Benign': if 'ANN=' in info: if 'af_exac_all' in info: exac = info.split('af_exac_all=')[1].split(';')[0] if float(exac) > 0.01: return False return True
def lookup(list_dicts, key, val): """ Find key by value in list of dicts and return dict """ if val == "": return None r = next((d for d in list_dicts if d[key] == val), None) if r is None: raise(ValueError(val + " not found")) return r
def pipe(obj, func, *args, **kwargs): """ Apply a function ``func`` to object ``obj`` either by passing obj as the first argument to the function or, in the case that the func is a tuple, interpret the first element of the tuple as a function and pass the obj to that function as a keyword argument whose key is the value of the second element of the tuple. Parameters ---------- func : callable or tuple of (callable, str) Function to apply to this object or, alternatively, a ``(callable, data_keyword)`` tuple where ``data_keyword`` is a string indicating the keyword of `callable`` that expects the object. *args : iterable, optional Positional arguments passed into ``func``. **kwargs : dict, optional A dictionary of keyword arguments passed into ``func``. Returns ------- object : the return type of ``func``. """ if isinstance(func, tuple): func, target = func if target in kwargs: msg = f"{target} is both the pipe target and a keyword argument" raise ValueError(msg) kwargs[target] = obj return func(*args, **kwargs) else: return func(obj, *args, **kwargs)
def single_number(nums): """ :type nums: List[int] :rtype: int """ i = 0 for num in nums: i ^= num return i
def mel2hz(mel): """Convert Mel frequency to frequency. Args: mel:Mel frequency Returns: Frequency. """ return 700 * (10**(mel / 2595.0) - 1)
def _is_raster_path_band_formatted(raster_path_band): """Return true if raster path band is a (str, int) tuple/list.""" if not isinstance(raster_path_band, (list, tuple)): return False elif len(raster_path_band) != 2: return False elif not isinstance(raster_path_band[0], str): return False elif not isinstance(raster_path_band[1], int): return False else: return True
def insert_dash_between_odds_common(number: int) -> str: """Inserts dash between two odd numbers. Examples: >>> assert insert_dash_between_odds_common(113345566) == "1-1-3-345-566" """ index: int = 0 result: str = str() while index != len(str(number)): result += str(number)[index] if not index + 1 >= len(str(number)): if int(str(number)[index]) % 2 and int(str(number)[index + 1]) % 2: result += "-" index += 1 return result
def bubble_sort(seq): """ Implementation of bubble sort. O(n2) and thus highly ineffective. """ size = len(seq) -1 for num in range(size, 0, -1): for i in range(num): if seq[i] > seq[i+1]: temp = seq[i] seq[i] = seq[i+1] seq[i+1] = temp return seq
def padding_string(pad, pool_size): """Get string defining the border mode. Parameters ---------- pad: tuple[int] Zero-padding in x- and y-direction. pool_size: list[int] Size of kernel. Returns ------- padding: str Border mode identifier. """ if pad == (0, 0): padding = 'valid' elif pad == (pool_size[0] // 2, pool_size[1] // 2): padding = 'same' elif pad == (pool_size[0] - 1, pool_size[1] - 1): padding = 'full' else: raise NotImplementedError( "Padding {} could not be interpreted as any of the ".format(pad) + "supported border modes 'valid', 'same' or 'full'.") return padding
def getDetailsName(viewName): """ Return Details sheet name formatted with given view. """ return 'Details ({})'.format(viewName)
def dictcopy3( lev1, depth=3 ): """For a dictionary, makes a copy, to a depth of 3. Non-dictionaries are not copied unless they behave like dictionaries.""" if depth<1: return lev1 try: lev2 = dict().fromkeys(lev1) except: # Nothing to copy: lev1 isn't a dict or even a suitable list, etc. return lev1 try: for k1,v1 in lev1.iteritems(): lev2[k1] = dictcopy3( v1, depth-1 ) except: return lev1 return lev2
def is_zip(file_type) -> bool: """ Check if the given file is a ZIP Returns: bool: Whether it's a ZIP file or not """ mimes = { 'application/zip', 'application/octet-stream', 'application/x-zip-compressed', 'multipart/x-zip' } for v in mimes: if v == file_type: return True return False