content
stringlengths
42
6.51k
def round_channels(channels, divisor=8): """ Round weighted channel number (make divisible operation). Parameters: ---------- channels : int or float Original number of channels. divisor : int, default 8 Alignment value. Returns: ------- int Weighted number of channels. """ rounded_channels = max( int(channels + divisor / 2.0) // divisor * divisor, divisor) if float(rounded_channels) < 0.9 * channels: rounded_channels += divisor return rounded_channels
def parse_by_integration(sensors): """Returns a list of devices that can be integrated.""" can_integrate = [] for sensor in sensors.values(): if sensor.get('integrate'): can_integrate.append(sensor) return can_integrate
def process_results(results: dict, min_stars: int = 5) -> dict: """Sort and filer results Args: results: results to process min_stars: minimum amount of stars required to include a repository in results Returns: Processed results """ filtered_d = {k: v for k, v in results.items() if v >= min_stars} # Values in descending order sorted_d = dict(sorted(filtered_d.items(), key=lambda item: -item[1])) return sorted_d
def term_to_integer(term): """ Return an integer corresponding to the base-2 digits given by ``term``. Parameters ========== term : a string or list of ones and zeros Examples ======== >>> from sympy.logic.boolalg import term_to_integer >>> term_to_integer([1, 0, 0]) 4 >>> term_to_integer('100') 4 """ return int(''.join(list(map(str, list(term)))), 2)
def _is_public(name: str) -> bool: """Return true if the name is not private, i.e. is public. :param name: name of an attribute """ return not name.startswith('_')
def append_name_to_key(entities, name): """To append value to corrispondent key""" temp_result = [] for item in entities: temp_item = {} for key, value in item.items(): temp_item[f"[{name}]{key}"] = item[key] temp_result.append(temp_item) return temp_result
def get_result_dir(result_dir, substring="results/"): """ :param result_dir: :param substring: :return: """ pos = result_dir.find(substring) return result_dir[pos + len(substring):]
def object_dist_to_mag(efl, object_dist): """Compute the linear magnification from the object distance and focal length. Parameters ---------- efl : `float` focal length of the lens object_dist : `float` object distance Returns ------- `float` linear magnification. Also known as the lateral magnification """ return efl / (efl - object_dist)
def full_class(obj: object) -> str: """The full importable path to an object's class.""" return type(obj).__module__ + '.' + type(obj).__name__
def get_crowd_selection(selection_count, selection_map): """ Figure out what the crowd actually selected :param selection_count: number of responses per selection :type selection_count: dict :param selection_map: maps selections to output fields :type selection_map: dict :return: the response with the most selections or tied responses separated by | :rtype: str|None """ # Cache containers crowd_selection = None # Figure out what the maximum number of selections was max_selection = max(selection_count.values()) # Build the crowd_selection if max_selection is 0: crowd_selection = None else: for selection, count in selection_count.iteritems(): if count is max_selection: if crowd_selection is None: crowd_selection = selection_map[selection] else: crowd_selection += '|' + selection_map[selection] # Return to user return crowd_selection
def color565(r, g, b): """ Convert red, green, blue components to a 16-bit 565 RGB value. Components should be values 0 to 255. :param r: Red byte. :param g: Green byte. :param b: Blue byte. :returns pixel : 16-bit 565 RGB value """ return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
def c2hex(char): """Convert to HEX (2 bytes).""" return "{:02x}".format(ord(char))
def parse_time_to_seconds(time: str) -> int: """needs hour:minutes:seconds as paramter, returns time in seconds""" timelist = time.split(":") seconds = int(timelist[0]) * 60 * 60 + int(timelist[1]) * 60 + int(timelist[2]) return seconds
def sr3d_collate_fn(batch): """ Collate function for SR3D grounding. See sr3d_parser_collate_fn for most arguments. """ return { "utterances": [ex["utterance"] for ex in batch], "raw_utterances": [ex["raw_utterance"] for ex in batch], "tag_dicts": [ex["tag_dict"] for ex in batch], "program_list": [ex["program_list"] for ex in batch], "scan_ids": [ex["scan_id"] for ex in batch], "point_clouds": [ex["point_cloud"] for ex in batch], "obj_labels": [ex["obj_labels"] for ex in batch], "target_ids": [ex["target_id"] for ex in batch] }
def strip_py_ext(options, path): """Return path without its .py (or .pyc or .pyo) extension, or None. If options.usecompiled is false: If path ends with ".py", the path without the extension is returned. Else None is returned. If options.usecompiled is true: If Python is running with -O, a .pyo extension is also accepted. If Python is running without -O, a .pyc extension is also accepted. """ if path.endswith(".py"): return path[:-3] if options.usecompiled: if __debug__: # Python is running without -O. ext = ".pyc" else: # Python is running with -O. ext = ".pyo" if path.endswith(ext): return path[:-len(ext)] return None
def ordinal(n: int) -> str: """ from: https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712 """ result = "%d%s" % (n, "tsnrhtdd"[((n / 10 % 10 != 1) * (n % 10 < 4) * n % 10)::4]) return result.replace('11st', '11th').replace('12nd', '12th').replace('13rd', '13th')
def comment_part_of_string(line, comment_idx): """ checks if the symbol at comment_idx is part of a string """ if ( line[:comment_idx].count(b"'") % 2 == 1 and line[comment_idx:].count(b"'") % 2 == 1 ) or ( line[:comment_idx].count(b'"') % 2 == 1 and line[comment_idx:].count(b'"') % 2 == 1 ): return True return False
def convert_to_decimal(seat_code): """ Takes a seat code and converts it to a tuple containing seat row and column in decimal. :param seat_code: string with first seven letters: B, F and last 3 letters: L, R :return: decimal tuple """ # get row and column information row = seat_code[:7] column = seat_code[-3:] # replace letters with digits row = row.replace('F', '0') row = row.replace('B', '1') column = column.replace('L', '0') column = column.replace('R', '1') # convert to decimal return int(row, 2), int(column, 2)
def counting_sort(arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/countingsort2/problem Given an unsorted list of integers, use the counting sort method to sort the list and then print the sorted list. Args: arr (list): List of integers to sort Returns: list: The list of integers in sorted ascending order """ sorted_list = [] counted_list = [0] * 100 for i in arr: counted_list[i] += 1 for idx, num in enumerate(counted_list): for _ in range(num): sorted_list.append(idx) return sorted_list
def count_digit(value): """Count the number of digits in the number passed into this function""" digit_counter = 0 while value > 0: digit_counter = digit_counter + 1 value = value // 10 return digit_counter
def create_assume_role_policy_document(trusted_entity_list): """ Create assume role policy document for IAM role :type trusted_entity_list: typing.List[str] :rtype: dict Example:: create_assume_role_policy_document([ TrustedEntityList.aws_lambda ]) """ return { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "{}.amazonaws.com".format(service) }, "Action": "sts:AssumeRole" } for service in trusted_entity_list ] }
def bfs(graph, start): """ Implementation of Breadth-First-Search (BFS) using adjacency matrix. This returns nothing (yet), it is meant to be a template for whatever you want to do with it, e.g. finding the shortest path in a unweighted graph. This has a runtime of O(|V|^2) (|V| = number of Nodes), for a faster implementation see @see ../fast/BFS.java (using adjacency Lists) :param graph: an adjacency-matrix-representation of the graph where (x,y) is True if the the there is an edge between nodes x and y. :param start: the node to start from. :return: Array array containing the shortest distances from the given start node to each other node """ # A Queue to manage the nodes that have yet to be visited, intialized with the start node queue = [start] # A boolean array indicating whether we have already visited a node visited = [False] * len(graph) # (The start node is already visited) visited[start] = True # Keeping the distances (might not be necessary depending on your use case) distances = [float("inf")] * len( graph) # Technically no need to set initial values since every node is visted exactly once # (the distance to the start node is 0) distances[start] = 0 # While there are nodes left to visit... while len(queue) > 0: print("Visited nodes: " + str(visited)) print("Distances: " + str(distances)) node = queue.pop(0) print("Removing node " + str(node) + " from the queue...") # ...for all neighboring nodes that haven't been visited yet.... for i in range(len(graph[node])): if graph[node][i] and not visited[i]: # Do whatever you want to do with the node here. # Visit it, set the distance and add it to the queue visited[i] = True distances[i] = distances[node] + 1 queue.append(i) print("Visiting node " + str(i) + ", setting its distance to " + str( distances[i]) + " and adding it to the queue") print("No more nodes in the queue. Distances: " + str(distances)) return distances
def foldchange(origin, modified): """caculate the fold change between modified and origin outputs.""" return modified / origin # return np.square(modified - origin)
def pivot_median(seq, lo, hi): """Returns index to the median of seq[lo], seq[mid], seq[hi - 1]""" m = lo + (hi - lo) // 2 # middle element if seq[lo] < seq[m]: if seq[m] < seq[hi - 1]: return m elif seq[hi - 1] < seq[lo]: return lo else: if seq[hi - 1] < seq[m]: return m elif seq[lo] < seq[hi - 1]: return lo return hi - 1
def of_cmp(s1, s2): """Compare openflow messages except XIDs""" if (not s1 and s2) or (s1 and not s2): # what if one is None return False #pdb.set_trace() val= len(s1) == len(s2) and s1[0:8] == s2[0:8] and (len(s1) <= 16 or s1[16:] == s2[16:]) #print " of_cmp("+ s1 +" , "+ s2 + ") == "+ str(val) return val
def get_utxos(tx, address): """ Given a transaction, find all the outputs that were sent to an address returns => List<Dictionary> list of UTXOs in bitcoin core format tx - <Dictionary> in bitcoin core format address - <string> """ utxos = [] for output in tx["vout"]: if "addresses" not in output["scriptPubKey"]: # In Bitcoin Core versions older than v0.16, native segwit outputs have no address decoded continue out_addresses = output["scriptPubKey"]["addresses"] amount_btc = output["value"] if address in out_addresses: utxos.append(output) return utxos
def form_columns(board: list) -> list: """ Takes the game board as a list of rows, "rotates" it and returns a list of columns. >>> form_columns(["**** ****", "***1 ****", "** 3****", "* 4 1****",\ " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"]) ['**** 3 ', '*** 6 ', '** 4 82', '*1 ', ' 31 81 ',\ '****93 2*', '**** **', '****5 ***', '**** ****'] >>> form_columns(["****9****", "***98****", "**987****", "*9876****",\ "987654321", "87654321*", "7654321**", "654321***", "54321****"]) ['****98765', '***987654', '**9876543', '*98765432', '987654321',\ '****4321*', '****321**', '****21***', '****1****'] """ columns = [] for i in range(len(board)): col = [] for j in range(len(board[i])): col.append(board[j][i]) columns.append(''.join(col)) return columns
def is_duplicate_affix(affixes, affix): """ Check if the properties for an affix are already known. """ for properties in affixes['properties']: if properties == affix['properties']: return True return False
def descope_queue_name(scoped_name): """Returns the unscoped queue name, given a fully-scoped name.""" # NOTE(kgriffs): scoped_name can be either '/', '/global-queue-name', # or 'project-id/queue-name'. return scoped_name.partition('/')[2] or None
def is_vlanid_in_range(vid): """Check if vlan id is valid or not""" if vid >= 1 and vid <= 4094: return True return False
def check_list_elements(list): """Check if the list is made all by Trues Arguments: list {[bool]} -- list that stores old indexes choose by the random number Returns: bool -- if the list is made by all true returns true else false """ for i in range(0, len(list)): if list[i] == False: return False return True
def dispatch_strategy(declaration): """How are we going to call the underlying implementation of a declaration? There are two strategies: - use_derived: we want to call the implementation on CPUDoubleType (or a similar, derived Type instance). Because these derived instances deal in Tensors, not Variables (it's a completely different object, so it doesn't dispatch back to VariableType), code on this dispatch path needs to wrap/unwrap tensors. If the derived implementation takes and returns tensors, the implementation is usually differentiable (although we also use the derived dispatch path for non-differentiable functions that we still want to dispatch on the derived Type instance; e.g., size()) - use_type: we want to call the implementation on Type, because it is implemented concretely, and the functions it invokes will get dispatched back to VariableType (which will ensure that they are differentiable.) """ if (declaration['abstract'] or declaration['derivative'] is not None or any(arg.get('is_type_dispatched') for arg in declaration['arguments'])): # If the function is abstract (not implemented on at::Type), we must # call the implementation on the derived type with unpacked tensors. # If the function has a derivative specified and is concrete, we could # call either implementation. We prefer the calling the derived # type's implementation with unpacked tensors because it is more # performant in some cases: any internal calls to other ATen functions # won't have the history tracked. # If the function has a type dispatched argument (i.e. is a factory), # we prefer calling the derived type's implementation both because it is # more performant and to ensure factory functions return tensors with _version # of 0 (probably not strictly necessary, but nice to have to keeps versions simple # to understand. return 'use_derived' else: # If the function is concrete (we don't have to override it) and we # didn't declare it in derivatives.yaml, we'll assume that it is # actually implemented out of differentiable functions. (This # assumption might not hold, but then you'll see gradcheck fail.) return 'use_type'
def cumulative_allele_count(samples_obj): """Return cumulative allele count for each sample in a dictionary Accepts: samples_obj(dict) example: {sample1 : {call_count:1}, sample2:{call_count:2} } Returns: call_count(int) example: 3 """ allele_count = 0 for sampleid, value in samples_obj.items(): allele_count += value["allele_count"] return allele_count
def capabilities_to_dict(caps): """Convert the Node's capabilities into a dictionary.""" if not caps: return {} if isinstance(caps, dict): return caps return dict([key.split(':', 1) for key in caps.split(',')])
def expandmarker(text: str, marker: str = '', separator: str = '') -> str: """ Return a marker expanded whitespace and the separator. It searches for the first occurrence of the marker and gets the combination of the separator and whitespace directly before it. :param text: the text which will be searched. :param marker: the marker to be searched. :param separator: the separator string allowed before the marker. If empty it won't include whitespace too. :return: the marker with the separator and whitespace from the text in front of it. It'll be just the marker if the separator is empty. """ # set to remove any number of separator occurrences plus arbitrary # whitespace before, after, and between them, # by allowing to include them into marker. if separator: firstinmarker = text.find(marker) firstinseparator = firstinmarker lenseparator = len(separator) striploopcontinue = True while firstinseparator > 0 and striploopcontinue: striploopcontinue = False if (firstinseparator >= lenseparator and separator == text[firstinseparator - lenseparator:firstinseparator]): firstinseparator -= lenseparator striploopcontinue = True elif text[firstinseparator - 1] < ' ': firstinseparator -= 1 striploopcontinue = True marker = text[firstinseparator:firstinmarker] + marker return marker
def format_repeats(file): """ Deal with the repeating blocks in the model by keeping track of the encompassed rows and multiplying them before appending. """ ret = [] while True: try: l = next(file).lstrip().replace('\n','') except StopIteration: break if l.lower().startswith('repeat'): times = int(l.split('x')[1]) repeats = [] while True: l = next(file).lstrip().replace('\n','') if l.lower() == 'end': break repeats.append(l) ret += repeats*times else: if not l.startswith('#'): ret += [l] return ret
def _dict_to_kv(d): """Convert a dictionary to a space-joined list of key=value pairs.""" return " " + " ".join(["%s=%s" % (k, v) for k, v in d.items()])
def get_message_headers(message): """Get headers from message.""" headers = message["payload"]["headers"] return headers
def is_latin(name): """Check if a species name is Latin. Parameters ---------- name : str species name to check Returns ------- bool whether species name is Latin """ if name == '': return False elif name.count(' ') != 1: return False str_ = name.replace(' ', '') if not str_.istitle(): return False elif not str_.isalpha(): return False return True
def _get_range(val, multiplier): """Get range of values to sweep over.""" range_min = max(0, val - val * multiplier / 100.) range_max = val + val * multiplier / 100. ranges = {'initial': val, 'minval': range_min, 'maxval': range_max} return ranges
def _IsLink(args): """Determines whether we need to link rather than compile. A set of arguments is for linking if they contain -static, -shared, are adding adding library search paths through -L, or libraries via -l. Args: args: List of arguments Returns: Boolean whether this is a link operation or not. """ for arg in args: # Certain flags indicate we are linking. if (arg in ['-shared', '-static'] or arg[:2] in ['-l', '-L'] or arg[:3] == '-Wl'): return True return False
def make_service_domain_name(service, region=''): """ Helper function for creating proper service domain names. """ tld = ".com.cn" if region == "cn-north-1" else ".com" return "{}.amazonaws{}".format(service, tld)
def SkipNItems(iterable, n): """ Generator yielding all but the first n items of a stream. SkipNItems(iterable, n) -> iterator iterable -- a sequence, iterator, or some object which supports iteration, yielding items of any type. n -- an integer or None Example: # Read and print lines 5 and 6 of a file f = open(filename, 'r') for line in FirstNItems(SkipNItems(f, 4), 2): print line.rstrip() """ def SNI(iterable, n): source = iter(iterable) while n > 0: next(source) n -= 1 while True: yield next(source) if n and n > 0: iterable = SNI(iterable, n) return iterable
def _vsplitter(version): """Kernels from Calxeda are named ...ceph-<sha1>...highbank. Kernels that we generate are named ...-g<sha1>. This routine finds the text in front of the sha1 that is used by need_to_install() to extract information from the kernel name. :param version: Name of the kernel """ if version.endswith('highbank'): return 'ceph-' return '-g'
def recursive_glob(rootdir='.', pattern='*'): """Search recursively for files matching a specified patterns. Arguments --------- rootdir : str, optional Path to directory to search (default is '.') pattern : str, optional Glob-style pattern (default is '*') Returns ------- matches : list List of matching files. """ # Adapted from http://stackoverflow.com/questions/2186525/ import os import fnmatch matches = [] for root, dirnames, filenames in os.walk(rootdir): for filename in fnmatch.filter(filenames, pattern): matches.append(os.path.join(root, filename)) return matches
def unique(value): """ENsure that al values are unique.""" try: result = set(value) except TypeError: result = [] for x in value: if x not in result: result.append(x) return result
def xgcd(a,b): """ Extended euclidean algorithm: Iterative version http://anh.cs.luc.edu/331/notes/xgcd.pdf """ prevx, x = 1, 0; prevy, y = 0, 1 while b: q = a/b x, prevx = prevx - q*x, x y, prevy = prevy - q*y, y a, b = b, a % b return a, prevx, prevy
def filter_dense_annotation(image_paths_per_class): """ Returns dict containing label as the key and the list of image paths containing the class annotation as values after deleting the key:value pair, for the label that contains the highest number of annotations Args: image_paths_per_class: dict containing label as the key and the list of image paths containing the class annotation as values Returns: image_paths_per_class: dict containing label as the key and the list of image paths containing the class annotation as values after removing the key,value pair with dense annotation class """ # Get highest number of classes/labels/annotations in images max_class_count = max([len(value) for key, value in image_paths_per_class.items()]) max_class_count_name = [ key for key, value in image_paths_per_class.items() if len(value) == max_class_count ][0] # Remove the dense annotation class image_paths_per_class.pop(max_class_count_name) return image_paths_per_class
def base10toN(num, base): """Convert a decimal number (base-10) to a number of any base/radix from 2-36.""" digits = "0123456789abcdefghijklmnopqrstuvwxyz" if num == 0: return '0' if num < 0: return '-' + base10toN((-1) * num, base) left = num // base if left == 0: return digits[num % base] else: return base10toN(left, base) + digits[num % base]
def _format_parameter(parameter: object) -> str: """ Format the parameter depending on its type and return the string representation accepted by the API. :param parameter: parameter to format """ if isinstance(parameter, list): return ','.join(parameter) else: return str(parameter)
def fit_transform(*args): """ fit_transform(iterable) fit_transform(arg1, arg2, *args) """ if len(args) == 0: raise TypeError('expected at least 1 arguments, got 0') categories = args if isinstance(args[0], str) else list(args[0]) uniq_categories = set(categories) bin_format = f'{{0:0{len(uniq_categories)}b}}' seen_categories = dict() transformed_rows = [] for cat in categories: bin_view_cat = (int(b) for b in bin_format.format(1 << len(seen_categories))) seen_categories.setdefault(cat, list(bin_view_cat)) transformed_rows.append((cat, seen_categories[cat])) return transformed_rows
def unzip(l): """Unzips a list of tuples into a tuple of two lists e.g. [(1,2), (3, 4)] -> ([1, 3], [2, 4]) """ xs = [t[0] for t in l] ys = [t[1] for t in l] return xs, ys
def find_elf_header(fi, data, offset, output): """ Used by guess_multibyte_xor_keys() """ i = 0 pos = 0 found = 0 length = len(data) machine_dict = {0x02: "sparc", 0x03: "x86", 0x08: "mips", 0x14: "powerpc", 0x28: "arm", 0x2A: "superh", 0x32: "ia_64", 0x3E: "x86_64", 0xB7: "aarch64", 0xF3: "riscv", 0xF7: "bpf"} while i < length: pos = data.find("\x7fELF", i) if pos == -1: break else: bits = 0 if data[pos + 4] == "\x01": bits = 32 elif data[pos + 4] == "\x02": bits = 64 endian = "" if data[pos + 5] == "\x01": endian = "little" elif data[pos + 5] == "\x02": endian = "big" machine = "" if endian == "little": if ord(data[pos + 0x12]) in machine_dict.keys(): machine = machine_dict[ord(data[pos + 0x12])] elif endian == "big": if ord(data[pos + 0x13]) in machine_dict.keys(): machine = machine_dict[ord(data[pos + 0x13])] if bits != 0 and endian != "" and machine != "": file_type = "ELF%d (%s %s endian)" % (bits, machine, endian) output += "%s file found at offset %s.\n" % (file_type, hex(offset + pos)) fi.setBookmark(offset + pos, 4, hex(offset + pos) + " " + file_type, "#c8ffff") found += 1 i = pos + 4 return (found, output)
def generate_blade_tup_map(bladeTupList): """ Generates a mapping from blade tuple to linear index into multivector """ blade_map = {} for ind,blade in enumerate(bladeTupList): blade_map[blade] = ind return blade_map
def get_common_elements(list1, list2): """find the common elements in two lists. used to support auto align might be faster with sets Parameters ---------- list1 : list a list of objects list2 : list a list of objects Returns ------- list : list list of common objects shared by list1 and list2 """ #result = [] #for item in list1: # if item in list2: # result.append(item) #Return list(set(list1).intersection(set(list2))) set2 = set(list2) result = [item for item in list1 if item in set2] return result
def eval_where(pred, gold): """ Args: Returns: """ pred_conds = [unit for unit in pred['where'][::2]] gold_conds = [unit for unit in gold['where'][::2]] gold_wo_agg = [unit[2] for unit in gold_conds] pred_total = len(pred_conds) gold_total = len(gold_conds) cnt = 0 cnt_wo_agg = 0 for unit in pred_conds: if unit in gold_conds: cnt += 1 gold_conds.remove(unit) if unit[2] in gold_wo_agg: cnt_wo_agg += 1 gold_wo_agg.remove(unit[2]) return [gold_total, pred_total, cnt, cnt_wo_agg]
def _parse_arg_line(line): """ pull out the arg names from a line of CLI help text introducing args >>> _parse_arg_line(' -s, --sudo run operations with sudo (nopasswd) (deprecated, use') ['-s', '--sudo'] """ return [ part.strip().split(' ')[0].split('=')[0] for part in line.strip().split(' ')[0].split(',') ]
def create_array(rows, cols, value): """Creates and returns array of inputted size, fills with inputted value""" array = [[value for x in range(cols)] for y in range(rows)] return array
def buildAreaElement(shape, nodeString, x1, y1, x2, y2): """Build an AREA element for an imagemap shape -- typically either "rect" or "default" nodeString -- name of node to show/hide x1, y1, x2, y2 -- coordinates of the rectangle """ return """<area shape="%s" alt="" coords="%d,%d,%d,%d" href="javascript:;" onmouseout="javascript:hideNode('%s')" onmouseover="javascript:showNode('%s')" onclick="return false;" /> """ % (shape, x1, y1, x2, y2, nodeString, nodeString)
def list_terms(terms, arabic_column, english_column): """ list all terms in dict""" for term in terms: print( "\n\t", terms[term][english_column], " : ", terms[term][arabic_column], "\n" ) return None
def person_waistsize_uri(cleaned): """in cm unmarked waist < 60 is interpreted as in, >=60 as cm""" if cleaned: return "person_waistsize/" + str(cleaned) else: return None
def clean_comment(line): """ Clean up a comment, removing # , #! and starting space, and adding missing \n if necessary >>> clean_comment("#") '\n' >>> clean_comment("# This is ...") 'This is ...\n' >>> clean_comment("#! This is ...") 'This is ...\n' """ if line.startswith("#!"): line = line[2:] else: line = line[1:] if line.startswith(" "): line = line[1:] if not line.endswith('\n'): line += '\n' return line
def contains_alternate_node(json_resp): """Check for the existence of alternate node in the stack analysis.""" result = json_resp.get('result') return bool(result) and isinstance(result, list) \ and (result[0].get('recommendation', {}) or {}).get('alternate', None) is not None
def global_pct_id( segments ): """ Calculated like this: 10bp @ 50% id = 5 matching residues, 10 total residues 10bp @ 80% id = 8 matching residues, 10 total residues 13 matching residues, 20 total residues --------------------------------------- 13 / 20 * 100 = 65% """ match_length = 0 identical_residues = 0 for segment in segments: segment_length = abs(segment['contig_start'] - segment['contig_end']) + 1 match_length += segment_length matched_residues = segment_length * (segment['pct_id'] / 100) identical_residues += matched_residues return (identical_residues / match_length) * 100
def get_error_res(eval_id): """Creates a default error response based on the policy_evaluation_result structure Parameters: eval_id (String): Unique identifier for evaluation policy Returns: PolicyEvalResultStructure object: with the error state with the given id """ return { "id": eval_id, "result": { "message": f"No evaluation with the id {eval_id} ongoing", "status": "ERROR", "confidenceLevel": "0", }, }
def line_to_tensor(line, EOS_int=1): """Turns a line of text into a tensor Args: line (str): A single line of text. EOS_int (int, optional): End-of-sentence integer. Defaults to 1. Returns: list: a list of integers (unicode values) for the characters in the `line`. """ # Initialize the tensor as an empty list tensor = [] ### START CODE HERE (Replace instances of 'None' with your code) ### # for each character: for c in line: # convert to unicode int c_int = ord(c) # append the unicode integer to the tensor list tensor.append(c_int) # include the end-of-sentence integer tensor.append(EOS_int) ### END CODE HERE ### return tensor
def is_iterable(obj): """ Check if obj is iterable. """ try: iter(obj) except TypeError: return False else: return True
def reverse_lookup(d, value): """Return first key found with given value. Raise ValueError exception if no matches found. """ for (k,v) in d.items(): if v == value: return k
def findTrend(trend, trendList): """ Finds a specific trend tuple within a list of tuples """ # Assuming the lack of duplicates for tIndex in range(len(trendList)): if len(trendList[tIndex]) == 2: if trendList[tIndex][0] == trend: return tIndex, trendList[tIndex] return -1, ()
def pharse_experiments_input(experiments): """ Pharse experiments number input to valid list. ---------- experiments : use input Returns ------- experiments : TYPE DESCRIPTION. """ experiments = experiments.split(',') new_experiments = [] indeces_to_remove = [] for j in range(0, len(experiments)): if '-' in experiments[j]: new_experiments = new_experiments + list( range(int(experiments[j].split('-')[0]), int(experiments[j].split('-')[1]) + 1)) indeces_to_remove.append(j) for ele in sorted(indeces_to_remove, reverse=True): del experiments[ele] experiments = experiments + new_experiments if len(experiments) == 1: experiments = int(experiments[0]) return experiments
def multiline_test(line): """ test if the current line is a multiline with "=" at the end :param line: 'O1 3 -0.01453 1.66590 0.10966 11.00 0.05 =' :type line: string >>> line = 'C1 1 0.278062 0.552051 0.832431 11.00000 0.02895 0.02285 =' >>> multiline_test(line) True >>> line = 'C1 1 0.278062 0.552051 0.832431 11.00000 0.05 ' >>> multiline_test(line) False """ line = line.rpartition('=') # partition the line in before, sep, after line = ''.join(line[0:2]) # use all including separator line = line.rstrip() # strip spaces if line.endswith('='): return True else: return False
def pluralize( string ): """ Correctly convert singular noung to plural noun. """ if string.endswith('y'): plural = string[:-1] + 'ies' elif string.endswith('us'): plural = string[:-2] + 'i' else: plural = string + 's' return plural
def _crit(*args): """ return a dict of the criteria caracteristic. args need to be given in the keys order used to reduce duplicate code """ keys = ["tooltip", "layer", "header", "content"] return dict(zip(keys, args))
def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = dict(x) z.update(y) return z
def get_error_rate(predicted, actual): """Return the average error rate""" error = 0 for i in range(len(predicted)): error += abs(predicted[i][0] - actual[i][0]) return error/len(predicted)
def keyboard_data_signals_an_interrupt( keyboard_data, stop_signal_chars=frozenset(['\x03', '\x04', '\x1b']) ): """The function returns a positive stop signal (1) if the character is in the `stop_signal_chars` set. By default, the `stop_signal_chars` contains: * \x03: (ascii 3 - End of Text) * \x04: (ascii 4 - End of Trans) * \x1b: (ascii 27 - Escape) (See https://theasciicode.com.ar/ for ascii codes.) (1) in the form of a string specifying what the ascii code of the input character was :param keyboard_data: Input character :param stop_signal_chars: Set of stop characters :return: """ if keyboard_data is not None: # print(f"{type(keyboard_data)=}, {len(keyboard_data)=}") index, keyboard_timestamp, char = keyboard_data # print(f'[Keyboard] {keyboard_timestamp}: {char=} ({ord(char)=})', end='\n\r') if char in stop_signal_chars: return f'ascii code: {ord(char)} (See https://theasciicode.com.ar/)' else: return False
def show_user(username): """Some Comment""" return 'Welcome: %s' % username
def arrange_array_size(batch_size: int, array_size: tuple): """ Decide array size given batch size and array size [batch_size, height, width, channel]. :param batch_size: batch size :param array_size: array (img) size :return: final array size """ output = list(array_size) output.insert(0, batch_size) return output
def _check_func_names(selected, feature_funcs_names): """ Checks if the names of selected feature functions match the available feature functions. Parameters ---------- selected : list of str Names of the selected feature functions. feature_funcs_names : dict-keys or list Names of available feature functions. Returns ------- valid_func_names : list of str """ valid_func_names = list() for f in selected: if f in feature_funcs_names: valid_func_names.append(f) else: raise ValueError('The given alias (%s) is not valid. The valid ' 'aliases for feature functions are: %s.' % (f, feature_funcs_names)) if not valid_func_names: raise ValueError('No valid feature function names given.') else: return valid_func_names
def empty(data): """ @type data : can be a list, string, dict @rtype: boolean """ if data is None: return True if type(data) == list: return len(data) == 0 if type(data) == dict: return len(data.keys()) == 0 return '%s' % data == ''
def hailstone(n): """Print out the hailstone sequence starting at n, and return the number of elements in the sequence. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ "*** YOUR CODE HERE ***" print(n) if n <= 1: return 1 else: if n % 2 == 0: return hailstone(n // 2) + 1 else: return hailstone(n * 3 + 1) + 1
def func_bump(x, offset=0, amplitude=1, exponent=2): """ Function that looks like: __/\__ and which can be scaled. :param x: :param offset: :param amplitude: :param exponent: :return: """ return offset + amplitude/(1 + x**exponent)
def view_method(request): """Function that simulates a Django view. """ if hasattr(request, 'flash'): request.flash.update() return True return False
def get_custom_headers(manifest_resource): """Generates the X-TAXII-Date-Added headers based on a manifest resource""" headers = {} times = sorted(map(lambda x: x["date_added"], manifest_resource.get("objects", []))) if len(times) > 0: headers["X-TAXII-Date-Added-First"] = times[0] headers["X-TAXII-Date-Added-Last"] = times[-1] return headers
def _sec_to_str(t): """Format time in seconds. Parameters ---------- t : int Time in seconds. """ from functools import reduce return "%d:%02d:%02d.%02d" % \ reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(t*100,), 100, 60, 60])
def get_announcement(message, reminder_offset): """ Generates the announcement message :param str message: Message about the event :param number reminder_offset: Minutes in which event is about to happen """ pos = message.find(":") if pos == -1: activity = message.strip() message = f"{activity} in {reminder_offset} minutes." else: activity = message[pos + 1 :].strip() person = message[0:pos].strip() message = f"Hello {person}, you have {activity} in {reminder_offset} minutes." return message
def getLoopSize(key, subjectNumber): """Reverse engineers the loop size from the given key and subject number. This is done by continually dividing the key by the subject number until the result matches 1. If the result has decimal digits 20201227 gets added to the previous key, before it is divided again. By counting the divisions the loop size can be determined. Parameters ---------- key: int The key to get the loop size for. subjectNumber: int The subject number used to generate the key. Returns ------- int The loop size used to generate the given key. """ loopSize = 0 while key != 1: newKey = key / subjectNumber while newKey % 1 != 0: key += 20201227 newKey = key / subjectNumber key = newKey loopSize += 1 return loopSize
def clean_name(value): """ remove bad character from possible file name component """ deletechars = r"\/:*%?\"<>|'" for letter in deletechars: value = value.replace(letter, '') return value
def Int(value): """Return the int of a value""" n = float(value) if -32767 <= n <= 32767: return int(n) else: raise ValueError("Out of range in Int (%s)" % n)
def concat(s): """This function takes a more user friendly regex (E.g: 'abc'), and inserts '.' concat operators where appropriate. (E.g: 'a.b.c')""" my_list = list(s)[::-1] # convert regex string to a reverse ordered list # characters with special rules special_characters = ['*', '|', '(', ')', '+'] output = [] # the compiler friendly regular expression (E.g: 'a.b.c') while my_list: # iterate over the user friendly regex c = my_list.pop() if len(output) == 0: # always append the first character from the list output.append(c) elif c not in special_characters: # if c is a normal character # if the previous character is non-special, *, or + if output[-1] not in special_characters or output[-1] == '*' \ or output[-1] == '+': output.append('.') # preface c with a . operator output.append(c) else: output.append(c) elif c == '*' or c == '|' or c == '+': output.append(c) elif c == '(': if output[-1] != '|' and output[-1] != '(' and output[-1] != '.': output.append('.') output.append(c) else: output.append(c) else: output.append(c) return ''.join(output)
def allocate_receiver_properties(receivers, params, demand): """ Generate receiver locations as points within the site area. Sampling points can either be generated on a grid (grid=1) or more efficiently between the transmitter and the edge of the site (grid=0) area. Parameters ---------- site_area : polygon Shape of the site area we want to generate receivers within. params : dict Contains all necessary simulation parameters. Output ------ receivers : List of dicts Contains the quantity of desired receivers within the area boundary. """ output = [] for receiver in receivers: output.append({ 'type': receiver['type'], 'geometry': receiver['geometry'], 'properties': { "ue_id": receiver['properties']['ue_id'], "misc_losses": params['rx_misc_losses'], "gain": params['rx_gain'], "losses": params['rx_losses'], "ue_height": params['rx_height'], "indoor": receiver['properties']['indoor'], 'demand': demand, } }) return output
def rivers_with_station(stations): """ Args: stations: list of MonitoringStation objects Returns: A set of names (string) of rivers that have an associated monitoring station. """ rivers = set() for s in stations: rivers.add(s.river) return rivers
def _prefix_master(master): """Convert user-specified master name to full master name. Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket name, while the developers always use shortened master name (tryserver.chromium.linux) by stripping off the prefix 'master.'. This function does the conversion for buildbucket migration. """ prefix = 'master.' if master.startswith(prefix): return master return '%s%s' % (prefix, master)
def reformROIArray(data, x1, x2): """Loops through flat ROI array and turns into 2d ROI array""" counter = 0 arr = [] tempArr = [] length = x2-x1 for i in range(len(data)): if counter == length-1: tempArr.append(data[i]) arr.append(tempArr) tempArr = [] counter = 0 else: tempArr.append(data[i]) counter = counter + 1 return arr
def remove_list_characters(some_list: list): """ :param some_list: :return: The list as a string without the default list characters [, [, `, and ,. """ return str(some_list).replace('[', '').replace(']', '').replace(',', '').replace("'", "")
def get_table_id(current_page, objects_per_page, loop_counter): """ Calculate correct id for table in project page. This function is used only for pagination purposes. """ return ((current_page - 1) * objects_per_page) + loop_counter
def interval(f,a,b,dx): """f must be previously defined. Gives the y-values of f over interval (a,b) with distance dx between each point""" n = int((b-a)/dx) return [f(a+i*dx) for i in range(n+1)]
def spoiler(text): """Return text in a spoiler""" return f"||{text}||"
def _to_linear(x): """Converts a sRGB gamma-encoded value to linear""" if x <= 0.04045: return x/12.92 else: return ((x + 0.055)/1.055)**2.4
def tidy_path(path): """Helper function for formatting a path :param str path: path to be formatted :return: formatted path """ if (not path.startswith('/')): path = '/' + path if (not path.endswith('/')): path += '/' return path