content
stringlengths
42
6.51k
def relative_class_counts(data): """input: a dict mapping class keys to their absolute counts output: a dict mapping class keys to their relative counts""" counts_items = sum(data.values()) return {k: 1.0 * v / counts_items for k, v in data.items()}
def split_message(message: str, limit: int=2000): """Splits a message into a list of messages if it exceeds limit. Messages are only split at new lines. Discord message limits: Normal message: 2000 Embed description: 2048 Embed field name: 256 Embed field value: 1024""" if len(message) <= limit: return [message] else: lines = message.splitlines() message_list = [] while len(lines) > 0: new_message = "" while len(lines) > 0 and len(new_message+lines[0]+"\r\n") <= limit: new_message += lines[0]+"\r\n" lines.remove(lines[0]) message_list.append(new_message) return message_list
def list_union(lst1, lst2): """ Combines two lists by the union of their values Parameters ---------- lst1, lst2 : list lists to combine Returns ------- final_list : list union of values in lst1 and lst2 """ final_list = set(lst1).union(set(lst2)) return final_list
def get_arg_to_class(class_names): """Constructs dictionary from argument to class names. # Arguments class_names: List of strings containing the class names. # Returns Dictionary mapping integer to class name. """ return dict(zip(list(range(len(class_names))), class_names))
def _gc(seq: str) -> float: """Return the GC ratio of a sequence.""" return float(seq.count("G") + seq.count("C")) / float(len(seq))
def quote_text(text, markup, username=""): """ Quote message using selected markup. """ if markup == 'markdown': return '>'+text.replace('\n','\n>').replace('\r','\n>') + '\n' elif markup == 'bbcode': if username is not "": username = '="%s"' % username return '[quote%s]%s[/quote]\n' % (username, text) else: return text
def sanitize_email(user_email: str) -> str: """ Given a formatted email like "Jordan M <remailable@getneutrality.org>", return just the "remailable@getneutrality.org" part. """ email_part = user_email.split()[-1] if email_part.startswith("<"): email_part = email_part[1:] if email_part.endswith(">"): email_part = email_part[:-1] return email_part
def get_del_bino_type(ita): """ This function will take a ita value and return the Fitzpatrick skin tone scale https://journals.plos.org/plosone/article/file?id=10.1371/journal.pone.0241843&type=printable :param ita: :return: """ if ita < -30: return "dark" elif -30 < ita <= 10: return "brown" elif 10 < ita <= 28: return "tan" elif 28 < ita <= 41: return "intermediate" elif 41 < ita <= 55: return "light" elif 55 < ita: return "very light" else: print(f"None cat: {ita}")
def x(bytes_obj): """ Convenience function to convert bytes object to even-length hex string (excluding 0x) """ assert type(bytes_obj) is bytes return bytes_obj.hex()
def get_switchport_config_commands(name, existing, proposed, module): """Gets commands required to config a given switchport interface """ proposed_mode = proposed.get("mode") existing_mode = existing.get("mode") commands = [] command = None if proposed_mode != existing_mode: if proposed_mode == "trunk": command = "switchport mode trunk" elif proposed_mode == "access": command = "switchport mode access" if command: commands.append(command) if proposed_mode == "access": av_check = str(existing.get("access_vlan")) == str( proposed.get("access_vlan") ) if not av_check: command = "switchport access vlan {0}".format( proposed.get("access_vlan") ) commands.append(command) elif proposed_mode == "trunk": tv_check = existing.get("trunk_vlans_list") == proposed.get( "trunk_vlans_list" ) if not tv_check: if proposed.get("allowed"): command = "switchport trunk allowed vlan {0}".format( proposed.get("trunk_allowed_vlans") ) commands.append(command) else: existing_vlans = existing.get("trunk_vlans_list") proposed_vlans = proposed.get("trunk_vlans_list") vlans_to_add = set(proposed_vlans).difference(existing_vlans) if vlans_to_add: command = "switchport trunk allowed vlan add {0}".format( proposed.get("trunk_vlans") ) commands.append(command) native_check = str(existing.get("native_vlan")) == str( proposed.get("native_vlan") ) if not native_check and proposed.get("native_vlan"): command = "switchport trunk native vlan {0}".format( proposed.get("native_vlan") ) commands.append(command) if commands: commands.insert(0, "interface " + name) return commands
def find_epsilon(epsilon, epoch, update_epsilon, start_updates=499): """ Updates epsilon ("random guessing rate") based on epoch. """ if epsilon <= 0.1: epsilon = 0.1 elif (not (epoch % update_epsilon)) and epoch > start_updates: epsilon -= 0.1 return epsilon
def convert_list_of_strings_to_list_of_tuples(x: list) -> list: """Convert e.g. ['(12, 5)', '(5, 12)'] to [(12, 5), (5, 12)] :param x: list of strings :return: list of tuples """ return [tuple(int(s) for s in i[1:-1].split(',')) for i in x]
def left_to_right_check(input_line: str, pivot: int) -> bool: """ Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hint of the input_line. >>> left_to_right_check("412453*", 4) True >>> left_to_right_check("452453*", 5) False """ row = input_line[1:-1] max_height = row[0] visibility = 1 for skyscraper in row: if skyscraper > max_height: max_height = skyscraper visibility += 1 if visibility != pivot: return False return True
def generate_spider(start_url, template_names): """Generate an slybot spider""" return { 'start_urls': [start_url], 'links_to_follow': 'none', 'follow_patterns': [], 'exclude_patterns': [], 'template_names': template_names }
def find_neighbors(faces, npoints): """ Generate the list of unique, sorted indices of neighboring vertices for all vertices in the faces of a triangular mesh. Parameters ---------- faces : list of lists of three integers the integers for each face are indices to vertices, starting from zero npoints: integer number of vertices on the mesh Returns ------- neighbor_lists : list of lists of integers each list contains indices to neighboring vertices for each vertex Examples -------- >>> # Simple example: >>> from mindboggle.guts.mesh import find_neighbors >>> faces = [[0,1,2],[0,2,3],[0,3,4],[0,1,4],[4,3,1]] >>> npoints = 5 >>> neighbor_lists = find_neighbors(faces, npoints) >>> neighbor_lists [[1, 2, 3, 4], [0, 2, 4, 3], [0, 1, 3], [0, 2, 4, 1], [0, 3, 1]] Real example: >>> import numpy as np >>> from mindboggle.guts.mesh import find_neighbors >>> from mindboggle.mio.vtks import read_faces_points >>> from mindboggle.mio.fetch_data import prep_tests >>> urls, fetch_data = prep_tests() >>> vtk_file = fetch_data(urls['left_mean_curvature'], '', '.vtk') >>> faces, points, npoints = read_faces_points(vtk_file) >>> neighbor_lists = find_neighbors(faces, npoints) >>> neighbor_lists[0:3] [[1, 4, 48, 49], [0, 4, 5, 49, 2], [1, 5, 6, 49, 50, 54]] Write results to vtk file and view (skip test): >>> from mindboggle.mio.vtks import rewrite_scalars # doctest: +SKIP >>> index = 100 # doctest: +SKIP >>> IDs = -1 * np.ones(len(neighbor_lists)) # doctest: +SKIP >>> IDs[index] = 1 # doctest: +SKIP >>> IDs[neighbor_lists[index]] = 2 # doctest: +SKIP >>> rewrite_scalars(vtk_file, 'find_neighbors.vtk', IDs, 'neighbors', IDs) # doctest: +SKIP >>> from mindboggle.mio.plots import plot_surfaces # doctest: +SKIP >>> plot_surfaces('find_neighbors.vtk') # doctest: +SKIP """ neighbor_lists = [[] for x in range(npoints)] for face in faces: [v0, v1, v2] = face if v1 not in neighbor_lists[v0]: neighbor_lists[v0].append(v1) if v2 not in neighbor_lists[v0]: neighbor_lists[v0].append(v2) if v0 not in neighbor_lists[v1]: neighbor_lists[v1].append(v0) if v2 not in neighbor_lists[v1]: neighbor_lists[v1].append(v2) if v0 not in neighbor_lists[v2]: neighbor_lists[v2].append(v0) if v1 not in neighbor_lists[v2]: neighbor_lists[v2].append(v1) return neighbor_lists
def plural(quantity, one, plural): """ >>> plural(1, '%d dead frog', '%d dead frogs') '1 dead frog' >>> plural(2, '%d dead frog', '%d dead frogs') '2 dead frogs' """ if quantity == 1: return one.replace("%d", "%d" % quantity) return plural.replace("%d", "%d" % quantity)
def solution(numerator: int = 1, digit: int = 1000) -> int: """ Considering any range can be provided, because as per the problem, the digit d < 1000 >>> solution(1, 10) 7 >>> solution(10, 100) 97 >>> solution(10, 1000) 983 """ the_digit = 1 longest_list_length = 0 for divide_by_number in range(numerator, digit + 1): has_been_divided = [] now_divide = numerator for division_cycle in range(1, digit + 1): if now_divide in has_been_divided: if longest_list_length < len(has_been_divided): longest_list_length = len(has_been_divided) the_digit = divide_by_number else: has_been_divided.append(now_divide) now_divide = now_divide * 10 % divide_by_number return the_digit
def bx_2_dec(VALUE, ALPHABET, BASE): """ Converts from base X to decimal """ POSITION = 0 TOTAL_DEC_VALUE = 0 # Loop over string reversed for PLACE in VALUE[::-1]: TOTAL_DEC_VALUE += pow(BASE, POSITION) * ALPHABET.index(PLACE) POSITION += 1 return TOTAL_DEC_VALUE
def getVecIndex(msb: int, lsb: int, index: int) -> int: """Get the index in the list of [msb, ..., index, ... , lsb] index -> index in verilog slicing """ if lsb > msb: return index - msb return msb - index
def make_partitions(items, test): """ Partitions items into sets based on the outcome of ``test(item1, item2)``. Pairs of items for which `test` returns `True` end up in the same set. Parameters ---------- items : collections.abc.Iterable[collections.abc.Hashable] Items to partition test : collections.abc.Callable[collections.abc.Hashable, collections.abc.Hashable] A function that will be called with 2 arguments, taken from items. Should return `True` if those 2 items need to end up in the same partition, and `False` otherwise. Returns ------- list[set] A list of sets, with each set containing part of the items in `items`, such that ``all(test(*pair) for pair in itertools.combinations(set, 2)) == True`` Notes ----- The function `test` is assumed to be transitive: if ``test(a, b)`` and ``test(b, c)`` return ``True``, then ``test(a, c)`` must also be ``True``. """ partitions = [] for item in items: for partition in partitions: p_item = next(iter(partition)) if test(item, p_item): partition.add(item) break else: # No break partitions.append({item}) return partitions
def states_hash(states): """Generate a hash of a list of states.""" return "|".join(sorted(states))
def be32toh(buf): # named after the c library function """Convert big-endian 4byte int to a python numeric value.""" out = (ord(buf[0]) << 24) + (ord(buf[1]) << 16) + \ (ord(buf[2]) << 8) + ord(buf[3]) return out
def java_string(text): """Transforms string output for java, cs, and objective-c code """ text = "%s" % text return text.replace("&quot;", "\"").replace("\"", "\\\"")
def eval_filter(y_true, y_pred, threshold=0.5): """ Args: y_true (list): true execution labels y_pred (list): predicted execution probabilities threshold (float): if p<threshold: skip the execution Return: label_acc (float): inference accuracy, only punishes False Negative cases filtered_rate (float): ratio of filtered data """ wrong_count = 0 filtered_count = 0 for y1, y2 in zip(y_true, y_pred): # FN case brings wrong label if y1[0] == 1 and y2[0] <= threshold: wrong_count += 1 if y2[0] <= threshold: filtered_count += 1 total_num = len(y_true) filtered_rate = filtered_count / total_num inference_acc = 1. - wrong_count / total_num return inference_acc, filtered_rate
def _convert_name(list_of_names, mapping_dict): """ returns a (copy) of the list var where all recognized variable names are converted to a standardized name specified by the keys of the mapping_dict """ if isinstance(list_of_names,str): type_of_input_list = 'string' list_of_names = [x.strip() for x in list_of_names.split(',')] else: if not isinstance(list_of_names, list): list(list_of_names) type_of_input_list = 'list' list_of_names = list(list_of_names) # a copy of var # else: # raise TypeError("input must be a comma separated string or a list") for vi, v in enumerate(list_of_names): for key, value in mapping_dict.items(): if v in value: list_of_names[vi] = key continue if type_of_input_list == 'list': return list_of_names else: # assuming type_of_input_list was a string return ', '.join(list_of_names)
def genomic_del4_abs_37(genomic_del4_37_loc): """Create test fixture absolute copy number variation""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.gXM6rRlCid3C1DmUGT2XynmGXDvt80P6", "subject": genomic_del4_37_loc, "copies": {"type": "Number", "value": 4} }
def slurp(text, offset, test): """Starting at offset in text, find a substring where all characters pass test. Return the begin and end position and the substring.""" begin = offset end = offset length = len(text) while offset < length: char = text[offset] if test(char): offset += 1 end = offset else: return begin, end, text[begin:end] return begin, end, text[begin:end]
def get_model_name(config: dict) -> str: """Return model name or `Unnamed`.""" return config['model']['name'] if 'model' in config and 'name' in config['model'] else 'Unnamed'
def getManagedObjectTypeName(mo): """ Returns the short type name of the passed managed object e.g. VirtualMachine Args: mo (vim.ManagedEntity) """ return mo.__class__.__name__.rpartition(".")[2]
def merge(a, b): """ Merging 2 lists """ i = 0 k = 0 c = [] while i < len(a) and k < len(b): if a[i] <= b[k]: c.append(a[i]) i += 1 else: c.append(b[k]) k += 1 while i < len(a): c.append(a[i]) i += 1 while k < len(b): c.append(b[k]) k += 1 return c
def get_max_words_with_ngrams(max_words, word_ngrams): """ Calculate the length of the longest possible sentence :param max_words: int, the length of the longest sentence :param word_ngrams: int :return: int, the length of the longest sentence with word n-grams """ max_words_with_ng = 1 for ng in range(word_ngrams): max_words_with_ng += max_words - ng return max_words_with_ng
def f(x): """ >>> f(4.5) 7.25 >>> f(-4.5) -5.25 >>> f(1) -0.5 """ if x <= -2: return 1 - (x + 2)**2 if x > 2: return 1 + (x - 2)**2 return -x/2
def isClose(float1, float2): """ Helper function - are two floating point values close? """ return abs(float1 - float2) < .01
def extract_uris(data): """Convert a text/uri-list to a python list of (still escaped) URIs""" lines = data.split('\r\n') out = [] for l in lines: if l == chr(0): continue # (gmc adds a '\0' line) if l and l[0] != '#': out.append(l) return out
def rem_num(num, lis): """ Removes all instances of a number 'num', from list lis. """ return [ele for ele in lis if ele != num]
def input_incorrectness_test(user_input, range_of_answers, case_matters=False): """ This function returns True if user_input NOT in range_of_answers. """ error_msg = "That wasn't a correct input. Try two letters." user_incorrect = True if case_matters == False: user_input = user_input.lower() for i in range(len(range_of_answers)): range_of_answers[i] = range_of_answers[i].lower() if user_input in range_of_answers: user_incorrect = False return user_incorrect, error_msg
def is_prime(n: int) -> bool: """ Primality test using 6k+-1 optimization. See https://en.wikipedia.org/wiki/Primality_test for explanation and details. Returns True if n is prime, False otherwise.""" if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True
def get_html_xml_path(path, build_name): """Parse and replace $BUILD_NAME variable in the path. Args: path(str): path to html report build_name(str): software build number Returns: str: modified path to html report """ try: return path.replace("__BUILD_NAME__", build_name) except AttributeError: return "undetermined"
def _attributes_equal(new_attributes, old_attributes): """ Compare attributes (dict) by value to determine if a state is changed :param new_attributes: dict containing attributes :param old_attributes: dict containing attributes :return bool: result of the comparison between new_attributes and old attributes """ for key in new_attributes: if key not in old_attributes: return False elif new_attributes[key] != old_attributes[key]: return False return True
def sumfunc(x): """ Incremental function This function increments input value. It returns the value that the input value added one. """ x = x + 1 return x
def unique_from_array(array): """takes an array and removes duplicates @param array: array object, the array to evaluate @returns: an array with unique values >>> unique_from_array([1, 23, 32, 1, 23, 44, 2, 1]) [1, 23, 32, 44, 2] >>> unique_from_array(["uno", "dos", "uno", 2, 1]) ["uno", "dos", 2, 1] """ u = [] for x in array: if x not in u: if x != '': u.append(x) return u
def get_name(obj, _=None): """Dictionary function for getting name and dob from dict""" return "{} is born on {}".format(obj.get('name'), obj.get('dob'))
def strike_through(text: str) -> str: """Returns a strike-through version of the input text""" result = '' for c in text: result = result + c + '\u0336' return result
def digit(n, base=10): """ >>> digit(1234) [4, 3, 2, 1] """ lst = [] while n > 0: lst.append(n % base) n //= base return lst
def height_fun(x, x0, A, xt): """ Model the height of a cantilevered microubule. The MT is fixed at x0 and pulled up. A is the shape giving/ scaling factor, equal to F/EI, where F ist the forc acting on the MT at xt, and EI is the flexural regidity of the mictotubule. """ def heaviside(x, x0): return 1 * (x >= x0) return heaviside(x, x0) * A * ((xt - x0) / 2 * (x - x0)**2 - ((x - x0)**3) / 6)
def get_maxprofits(legs, classes): """Loops through each leg and gets the maximum profit of that leg The max profit is added as key to the legs dictionary Parameters ---------- legs : list of dictionaries List of dictionaries, where each dictionary represents a leg classes : dictionary Dictionary that will contain the existing airplane classes Returns ------- legs : list of dictionaries Same list as input, but each leg now has a key named maxprofit with the corresponding max profit """ if legs: classes = list(classes.keys()) for leg in legs: profits = [leg[c] for c in classes] leg['maxprofit'] = max(profits) return legs
def _num_columns(data): """Find the number of columns in a raw data source. Args: data: 2D numpy array, 1D record array, or list of lists representing the contents of the source dataframe. Returns: num_columns: number of columns in the data. """ if hasattr(data, 'shape'): # True for numpy arrays if data.ndim == 1: # 1D record array; number of columns is length of compound dtype. return len(data.dtype) elif data.ndim == 2: # 2D array of values: number of columns is in the shape. return data.shape[1] else: raise ValueError('data expected to be a 2D array or 1D record array.') elif data: # List of lists: first entry is first row. return len(data[0]) else: # Empty list has zero columns return 0
def type_casting(number): """take the text input and type cast them into floating numbers""" try: number = float(number) except Exception: # exception occurs from comma utilization for decimal points number = float(number.replace(',', '.')) return number
def _int_endf(s): """Convert string to int. Used for INTG records where blank entries indicate a 0. Parameters ---------- s : str Integer or spaces Returns ------- integer The number or 0 """ s = s.strip() return int(s) if s else 0
def station_coordinates(stations): """Build and return the lists of latitudes, longitudes and station names respectively""" latitudes = [] longitudes = [] texts = [] for station in stations: latitudes.append(station.coord[0]) longitudes.append(station.coord[1]) texts.append(station.name) return latitudes, longitudes, texts
def _tzoffset2iso8601zone(seconds): """Takes an offset, such as from _tzoffset(), and returns an ISO 8601 compliant zone specification. Please note that the result of _tzoffset() is the negative of what time.localzone and time.altzone is. """ return "%+03d:%02d" % divmod((seconds // 60), 60)
def get_solution_file_name(file_name): """ Return the name of the file in which save the solution :param file_name: the name of the file. :return: A .sol filename :rtype: str """ if file_name is None: return None if file_name.endswith('.sol'): return file_name else: return f"{file_name}.sol"
def cmd_exists(cmd): """Check whether cmd exists on system.""" # https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python import subprocess return subprocess.call(['type ' + cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
def get_next_cursor(res): """Extract the next_cursor field from a message object. This is used by all Web API calls which get paginated results. """ metadata = res.get('response_metadata') if not metadata: return None return metadata.get('next_cursor', None)
def xpath_literal(s): """ http://stackoverflow.com/questions/6937525/escaping-xpath-literal-with-python """ if "'" not in s: return "'%s'" % s if '"' not in s: return '"%s"' % s return "concat('%s')" % s.replace("'", "',\"'\",'")
def none_of(*words: str) -> str: """ Format words to query results containing none of the undesired words. This also works with the **on_site** restriction to exclude undesired domains. :param words: List of undesired words :return: String in the format google understands """ return " ".join("-{}".format(word) for word in words)
def divide_into_chunks(array, chunk_size): """Divide a given iterable into pieces of a given size Args: array (list or str or tuple): Subscriptable datatypes (containers) chunk_size (int): Size of each piece (except possibly the last one) Returns: list or str or tuple: List of chunks """ return [array[i:i + chunk_size] for i in range(0, len(array), chunk_size)]
def assert_subclass(objs, subclass): """ Assert there is a object of subclass. """ for obj in objs: if issubclass(subclass, type(obj)): return True return False
def calc_probs(wordList): """ Creates a dictionary of all the words and their associated word count. Parameters: wordlist (list[str]): list containing all of the words of the chosen text Returns: list[str]: a list of all the words probs (list[float]): a list of corresponding probabilites of all the words """ totalWords = len(wordList) wordCount = {word:0 for word in wordList} for word in wordList: wordCount[word] += 1 probs = [freq/totalWords for freq in wordCount.values()] return list(wordCount.keys()), probs
def ct_bytes_compare(a, b): """ Constant-time string compare. http://codahale.com/a-lesson-in-timing-attacks/ """ if not isinstance(a, bytes): a = a.decode('utf8') if not isinstance(b, bytes): b = b.decode('utf8') if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= x ^ y return (result == 0)
def parse_server_name(server_name): """Split a server name into host/port parts. Args: server_name (str): server name to parse Returns: Tuple[str, int|None]: host/port parts. Raises: ValueError if the server name could not be parsed. """ try: if server_name[-1] == ']': # ipv6 literal, hopefully return server_name, None domain_port = server_name.rsplit(":", 1) domain = domain_port[0] port = int(domain_port[1]) if domain_port[1:] else None return domain, port except Exception: raise ValueError("Invalid server name '%s'" % server_name)
def texnum(x, mfmt='{}', noone=False): """ Convert number into latex """ m, e = "{:e}".format(x).split('e') m, e = float(m), int(e) mx = mfmt.format(m) if e == 0: if m == 1: return "" if noone else "1" return mx ex = r"10^{{{}}}".format(e) if m == 1: return ex return r"{}\;{}".format(mx, ex)
def fib_rec(n): """ Series - 1, 1, 2, 3, 5, 8, 13 `n` starts from 0. :param n: :return: """ if n < 2: return 1 return fib_rec(n-1) + fib_rec(n-2)
def get_intercept(args): """ if args are something that should be handled by terrapy, not terraform, indicate and yield cmd name """ is_intercept = False mod_args = None if len(args) > 0 and args[0] == 'clean': is_intercept = True mod_args = ['clean'] return is_intercept, mod_args
def append_hostname(machine_name, num_list): """ Helper method to append the hostname to node numbers. :param machine_name: The name of the cluster. :param num_list: The list of nodes to be appended to the cluster name. :return: A hostlist string with the hostname and node numbers. """ hostlist = [] for elem in num_list: hostlist.append(machine_name + str(elem)) return '%s' % ','.join(map(str, hostlist))
def parse_model_http(model_metadata, model_config): """ Check the configuration of a model to make sure it meets the requirements for an image classification network (as expected by this client) """ if len(model_metadata['inputs']) != 1: raise Exception("expecting 1 input, got {}".format( len(model_metadata['inputs']))) if len(model_metadata['outputs']) != 1: raise Exception("expecting 1 output, got {}".format( len(model_metadata['outputs']))) if len(model_config['input']) != 1: raise Exception( "expecting 1 input in model configuration, got {}".format( len(model_config['input']))) input_metadata = model_metadata['inputs'][0] output_metadata = model_metadata['outputs'][0] return (input_metadata['name'], output_metadata['name'], model_config['max_batch_size'])
def get_voigt_mapping(n): """ Get the voigt index to true index mapping for a given number of indices. """ voigt_indices = [[0,0],[1,1],[2,2],[1,2],[0,2],[0,1],[2,1],[2,0],[1,0]] if (n%2): indices = [[0],[1],[2]] n-=1 else: indices = [[]] for _ in range(int(n/2)): temp = [] for indx,i in enumerate(indices): for v in voigt_indices: temp.append(i+v) indices = temp return indices
def major_element(arr, n): """ major element is nothing but which occurs in array >= n/2 times :param arr: list :param n: len of array :return: major ele we can use Moore Voting algorithm -->Explore """ count_dict = dict() majority = n // 2 for ele in arr: if ele in count_dict: count_dict[ele] += 1 if count_dict[ele] >= majority: return ele else: count_dict[ele] = 1 return -1
def color2int(red, green, blue, magic): """Convert rgb-tuple to an int value.""" return -((magic << 24) + (red << 16) + (green << 8) + blue) & 0xffffffff
def batch_files(pool_size, limit): """ Create batches of files to process by a multiprocessing Pool """ batch_size = limit // pool_size filenames = [] for i in range(pool_size): batch = [] for j in range(i * batch_size, (i + 1) * batch_size): filename = 'numbers/numbers_%d.txt' % j batch.append(filename) filenames.append(batch) return filenames
def to_string(b): """Return the parameter as type 'str', possibly encoding it. In Python2, the 'str' type is the same as 'bytes'. In Python3, the 'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is distinct. """ if isinstance(b, str): # In Python2, this branch is taken for types 'str' and 'bytes'. # In Python3, this branch is taken only for 'str'. return b if isinstance(b, bytes): # In Python2, this branch is never taken ('bytes' is handled as 'str'). # In Python3, this is true only for 'bytes'. try: return b.decode('utf-8') except UnicodeDecodeError: # If the value is not valid Unicode, return the default # repr-line encoding. return str(b) # By this point, here's what we *don't* have: # # - In Python2: # - 'str' or 'bytes' (1st branch above) # - In Python3: # - 'str' (1st branch above) # - 'bytes' (2nd branch above) # # The last type we might expect is the Python2 'unicode' type. There is no # 'unicode' type in Python3 (all the Python3 cases were already handled). In # order to get a 'str' object, we need to encode the 'unicode' object. try: return b.encode('utf-8') except AttributeError: raise TypeError('not sure how to convert %s to %s' % (type(b), str))
def createVskDataDict(labels,data): """Creates a dictionary of vsk file values from labels and data. Parameters ---------- labels : array List of label names for vsk file values. data : array List of subject measurement values corresponding to the label names in `labels`. Returns ------- vsk : dict Dictionary of vsk file values. Dictionary keys correspond to names in `labels` and dictionary values correspond to values in `data`. Examples -------- This example tests for dictionary equality through python instead of doctest since python does not guarantee the order in which dictionary elements are printed. >>> labels = ['MeanLegLength', 'LeftKneeWidth', 'RightAnkleWidth'] >>> data = [940.0, 105.0, 70.0] >>> res = createVskDataDict(labels, data) >>> res == {'MeanLegLength':940.0, 'LeftKneeWidth':105.0, 'RightAnkleWidth':70.0} True """ vsk={} for key,data in zip(labels,data): vsk[key]=data return vsk
def flip(a): """ >>> flip([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [[7, 8, 9], [4, 5, 6], [1, 2, 3]] """ # n = len(a) # for x in range(n // 2): # for y in range(n): # a[n-x-1][y], a[x][y] = a[x][y], a[n-x-1][y] return a[::-1]
def power_level(serial: int, x: int, y: int) -> int: """Compute the power level of the fuel cell at x, y. """ rack_id = x + 10 p = rack_id * y + serial p *= rack_id p = (p // 100) % 10 return p - 5
def merge_sort(L): """ Sorts a list in increasing order. This algorithm uses merge sort. @param L: a list (in general unsorted) @return: a reference containing an ascending order sorted version of L """ def merge_lists(L1, L2): """ Merge two sorted list in a new sorted list which length is len(L1) + len(L2) @param L1: a sorted list @param L2: a sorted list @return: result of merging L1 and L2 """ # list containing L1 and L2 merged and sorted merged_list = [] i = j = 0 # repeat while i or j is less than len(L1) # and len(L2) respectively, # i.e., until one of two list have been # completed added to merged list while (i < len(L1) and j < len(L2)): # compare index i (L1) and index j (L2) # and add smaller element of the comparison if L2[j] < L1[i]: merged_list.append(L2[j]) # increase j by 1 (i.e., go to the next # element of L2) j += 1 else: merged_list.append(L1[i]) # increase i by 1 (i.e., go to the next # element of L1) i += 1 # at this point one of the elements of one list has # been completed added, while the other list need to # add its remaining elements. if i < len(L1): # if elements of L1 have not been completely added # add the remaining, but sorted elements, to the merged list merged_list += L1[i:] # being here means that all elements of L1 have been added, # but not all elements of L2, so they should be added # at the end of merged_list. Again, remaining elements of # L2 are already sorted. else: merged_list += L2[j:] # pass reference of merged_list to L return merged_list # check if the list contains no elements or just one # i.e. list is already sorted if len(L) < 2: return L # divide L in two smaller lists L1 = L[:len(L) // 2] L2 = L[len(L) // 2:] # sort first half of L (i.e. L1) L1 = merge_sort(L1) # sort second half of L (i.e. L2) L2 = merge_sort(L2) # merge sorted lists (L1 and L2) in L return merge_lists(L1, L2)
def vbc(vb=0,vc=0): """ Parameters ---------- vb : TYPE, optional DESCRIPTION. The default is 0. vc : TYPE, optional DESCRIPTION. The default is 0. Returns ------- None. """ voltage = vb - vc return voltage
def t_area_eff(t_str: str) -> float: """Calculate area of a triangle (efficient). Args: t_str: <str> triangle shape as a string. Returns: <float> triangle area. """ return (t_str.count('\n') - 2) ** 2 / 2
def tetra_clean(instr: str) -> bool: """Return True if string contains only unambiguous IUPAC nucleotide symbols. :param instr: str, nucleotide sequence We are assuming that a low frequency of IUPAC ambiguity symbols doesn't affect our calculation. """ if set(instr) - set("ACGT"): return False return True
def url_last(url, exclude_params=False): """ Gets the last segment of a url. Example: url = "https://www.bad-actor.services/some/thing" == "thing" :param url: Url to parse. :type url: str :param exclude_params: Exludes paramters from the last segment of the url. :type exclude_params: Bool :returns: The last segment of a url. :rtype: str """ url = url[url.rfind("/") + 1:] if exclude_params and "?" in url: url = url[:url.find("?")] return url
def visibility(vis): """Function to format visibility""" if vis == 'None': return {'parsed' : 'None', 'value' : 'None', 'unit' : 'None', 'string': 'N/A'} if 'VV' not in vis: value = vis[:-2] unit = 'SM' unit_english = 'Statute Miles' else: value = f'Vertical Visibility: {int(vis[2:]) * 100}' unit = 'ft' unit_english = 'Feet' return {'parsed' : vis, 'value' : value, 'unit' : unit, 'string' : f'{value} {unit_english}'}
def compare_version(version, pair_version): """ Args: version (str): The first version string needed to be compared. The format of version string should be as follow : "xxx.yyy.zzz". pair_version (str): The second version string needed to be compared. The format of version string should be as follow : "xxx.yyy.zzz". Returns: int: The result of comparasion. 1 means version > pair_version; 0 means version = pair_version; -1 means version < pair_version. Examples: >>> compare_version("2.2.1", "2.2.0") >>> 1 >>> compare_version("2.2.0", "2.2.0") >>> 0 >>> compare_version("2.2.0-rc0", "2.2.0") >>> -1 >>> compare_version("2.3.0-rc0", "2.2.0") >>> 1 """ version = version.strip() pair_version = pair_version.strip() if version == pair_version: return 0 version_list = version.split(".") pair_version_list = pair_version.split(".") for version_code, pair_version_code in zip(version_list, pair_version_list): if not version_code.isnumeric(): return -1 if not pair_version_code.isnumeric(): return 1 if int(version_code) > int(pair_version_code): return 1 elif int(version_code) < int(pair_version_code): return -1 return 0
def calculate_number_of_castles(land): """Returns number of castles that can be built on input land array.""" print(land) direction = 0 # 0 represents start, 1 means up, -1 means down previous_plot = None castles = 0 for index, plot in enumerate(land): output_string = 'Index: %s Value: %s' % (index, plot) if index > 0: if plot > previous_plot and direction != 1: direction = 1 castles += 1 output_string += ' Castles: %s - Preceding Valley Found' % castles elif plot < previous_plot and direction != -1: direction = -1 castles += 1 output_string += ' Castles: %s - Preceding Peak Found' % castles else: output_string += ' Castles: %s' % castles else: output_string += ' Castles: %s' % castles previous_plot = plot print(output_string) return castles
def complete_record_ids(record, domain): """Ensures that a record's record_id fields are prefixed with a domain.""" def complete(record, field): id = record.get(field) if id and '/' not in id: record[field] = '%s/%s' % (domain, id) complete(record, 'person_record_id') complete(record, 'note_record_id') return record
def string_to_dict(string): """Return dictionary from string "key1=value1, key2=value2".""" if string: pairs = [s.strip() for s in string.split(",")] return dict(pair.split("=") for pair in pairs)
def get_grams(str): """ Return a set of tri-grams (each tri-gram is a tuple) given a string: Ex: 'Dekel' --> {('d', 'e', 'k'), ('k', 'e', 'l'), ('e', 'k', 'e')} """ lstr = str.lower() return set(zip(lstr, lstr[1:], lstr[2:]))
def check_band_below_faint_limits(bands, mags): """ Check if a star's magnitude for a certain band is below the the faint limit for that band. Parameters ---------- bands : str or list Band(s) to check (e.g. ['SDSSgMag', 'SDSSiMag']. mags : float or list Magnitude(s) of the band(s) corresponding to the band(s) in the bands variable Returns ------- bool : True if the band if below the faint limit. False if it is not """ if isinstance(bands, str): bands = [bands] if isinstance(mags, float): mags = [mags] for band, mag in zip(bands, mags): if 'SDSSgMag' in band and mag >= 24: return True elif 'SDSSrMag' in band and mag >= 24: return True elif 'SDSSiMag' in band and mag >= 23: return True elif 'SDSSzMag' in band and mag >= 22: return True return False
def get_container_port_ip(server_pid, port_name): """ Get the container port IP. Input: - The container pid. - The name of the port (e.g, as shown in ifconfig) """ return "ip netns exec {} ifconfig {} | grep \"inet \" | xargs | cut -d \' \' -f 2".format(server_pid, port_name)
def round_base(x, base=.05): """"rounds the value up to the nearest base""" return base * round(float(x) / base)
def compare( data_a: list, data_b: list ): """ Compares two sets of evaluated data with the same Args: data_a (list): data set A data_b (list): data set B Returns: A String "Correct/Total Answers" and the percentage """ # asserts the number of questions is the same assert len(data_a) == len(data_b) cnt = 0 for i in range(len(data_a)): if data_a[i] == data_b[i]: cnt += 1 return (f"{cnt}/{len(data_a)}", cnt / len(data_a) * 100)
def fuzzy_not(arg): """ Not in fuzzy logic will return Not if arg is a boolean value, and None if argument is None >>> from sympy.logic.boolalg import fuzzy_not >>> fuzzy_not(True) False >>> fuzzy_not(None) >>> fuzzy_not(False) True """ if arg is None: return return not arg
def Fence(Token,Fence1='\"',Fence2='\"'): """ This function takes token and returns it with Fence1 leading and Fence2 trailing it. By default the function fences with quotations, but it doesn't have to. For example: A = Fence("hi there") B = Fence("hi there","'","'") C = Fence("hi there","(",")") D = Fence("hi there","[","]") yields the following: A -> "hi there" B -> 'hi there' C -> (hi there) D -> [hi there] """ return Fence1+Token+Fence2
def __assert_sorted(collection): """Check if collection is ascending sorted, if not - raises :py:class:`ValueError` :param collection: collection :return: True if collection is ascending sorted :raise: :py:class:`ValueError` if collection is not ascending sorted Examples: >>> __assert_sorted([0, 1, 2, 4]) True >>> __assert_sorted([10, -1, 5]) Traceback (most recent call last): ... ValueError: Collection must be ascending sorted """ if collection != sorted(collection): raise ValueError("Collection must be ascending sorted") return True
def countBits(n): """ Consider a number x and half of the number (x//2). The binary representation of x has all the digits as the binary representation of x//2 followed by an additional digit at the last position. Therefore, we can find the number of set bits in x by finding the number of set bits in x//2 and determining whether the last digit in x is 0 or 1. """ res = [0] * (n+1) for i in range(1, n+1): res[i] = res[i//2] + (i & 1) return sum(res)
def rapmap_pseudo_paired(job, config, name, samples, flags): """Run RapMap Pseudo-Mapping procedure on paired-end sequencing data :param config: The configuration dictionary. :type config: dict. :param name: sample name. :type name: str. :param samples: The samples info and config dictionary. :type samples: dict. :returns: str -- The output vcf file name. """ output = "{}".format(name) logfile = "{}".format(name) command = [] # job.fileStore.logToMaster("RapMap Command: {}\n".format(command)) # pipeline.run_and_log_command(" ".join(command), logfile) return NotImplementedError
def check_same_keys(d1, d2): """Check if dictionaries have same keys or not. Args: d1: The first dict. d2: The second dict. Raises: ValueError if both keys do not match. """ if d1.keys() == d2.keys(): return True raise ValueError("Keys for both the dictionaries should be the same.")
def sanitize(rev, sep='\t'): """Converts a for-each-ref line to a name/value pair. """ splitrev = rev.split(sep) branchval = splitrev[0] branchname = splitrev[1].strip() if branchname.startswith("refs/heads/"): branchname = branchname[11:] return branchname, branchval
def compute_line_intersection_point(x1, y1, x2, y2, x3, y3, x4, y4): """Compute the intersection point of two lines. Taken from https://stackoverflow.com/a/20679579 . Parameters ---------- x1 : number x coordinate of the first point on line 1. (The lines extends beyond this point.) y1 : number y coordinate of the first point on line 1. (The lines extends beyond this point.) x2 : number x coordinate of the second point on line 1. (The lines extends beyond this point.) y2 : number y coordinate of the second point on line 1. (The lines extends beyond this point.) x3 : number x coordinate of the first point on line 2. (The lines extends beyond this point.) y3 : number y coordinate of the first point on line 2. (The lines extends beyond this point.) x4 : number x coordinate of the second point on line 2. (The lines extends beyond this point.) y4 : number y coordinate of the second point on line 2. (The lines extends beyond this point.) Returns ------- tuple of number or bool The coordinate of the intersection point as a ``tuple`` ``(x, y)``. If the lines are parallel (no intersection point or an infinite number of them), the result is ``False``. """ # pylint: disable=invalid-name def _make_line(point1, point2): line_y = point1[1] - point2[1] line_x = point2[0] - point1[0] slope = point1[0] * point2[1] - point2[0] * point1[1] return line_y, line_x, -slope line1 = _make_line((x1, y1), (x2, y2)) line2 = _make_line((x3, y3), (x4, y4)) D = line1[0] * line2[1] - line1[1] * line2[0] Dx = line1[2] * line2[1] - line1[1] * line2[2] Dy = line1[0] * line2[2] - line1[2] * line2[0] if D != 0: x = Dx / D y = Dy / D return x, y return False
def validate_input_version(input_version): """Check that an input id is a number without spaces""" if ' ' in input_version: return False # create a set of invalid characters return str(input_version).isdigit()
def _int_formatter(val, chars, delta, left=False): """ Format float to int. Usage of this is shown here: https://github.com/tammoippen/plotille/issues/11 """ align = "<" if left else "" return "{:{}{}d}".format(int(val), align, chars)
def schema_url(base_url): """URL of the schema of the running application.""" return f"{base_url}/swagger.yaml"