content
stringlengths
42
6.51k
def revision_list_to_obsoletes_dict(revision_list): """Args: revision_list: list of tuple tuple: PID, SID, OBSOLETES_PID, OBSOLETED_BY_PID. Returns: dict: Dict of obsoleted PID to obsoleting PID. """ return { pid: obsoletes_pid for pid, sid, obsoletes_pid, obsoleted_by_pid in rev...
def natural_key(string_): """ Allows human sorting. See Natural Sorting Algorithm.""" import re return [int(s) if s.isdigit() else s.lower() for s in re.split(r'(\d+)', string_)]
def rescale_read_counts(c0, c1, max_allowed_reads=100): """Ensures that n_total <= max_allowed_reads, rescaling if necessary.""" Total = c0 + c1 if Total > max_allowed_reads: c0 = int(max_allowed_reads * float(c0/Total)) c1 = max_allowed_reads - c0 return c0, c1
def are_lists_equal(list1, list2): """ :param list1: :param list2: :return: True if the lists contains the same values (even if not in the same order) :rtype: bool """ # count_of_shared_elements = len(set(list1) & set(list2)) # CHECKING BY SET OF SHARED ELEMENTS # if count_of_shared...
def typedef(object_to_type): """ An extension of the type function for custom class objects :param object_to_type: The object to type :return: A string """ return type(object_to_type).__name__
def find_value(keys, d, create=False): """Return a possibly deeply buried {key, value} with all parent keys. Given: keys = ['a', 'b'] d = {'a': {'b': 1, 'c': 3}, 'b': 4} returns: 1 """ default = {} if create else None value = d.get(keys[0], default) if len(keys) > 1 and ty...
def collate_fn(batch_data): """ Collation function to distribute data to samples :param batch_data: batch data """ graphs = [] mut, gexpr, met, Y = [], [], [], [] for g, mu, gex, me, y in batch_data: graphs.append(g) mut.append(mu) gexpr.append(gex) met.append...
def cleanId(input_id) : """ filter id so that it's safe to use as a pyflow indentifier """ import re return re.sub(r'([^a-zA-Z0-9_\-])', "_", input_id)
def one_loop(array: list) -> int: """ Uses one loop to get the max sum subarray """ lenght = len(array) max_sum = array[0] current_sum = array[0] for i in range(1, lenght): current_sum = max(current_sum + array[i], array[i]) max_sum = max(max_sum, current_sum) return max_...
def add_default_configs(configs: dict, default_configs: dict): """ Add default items to current configuration """ for key, value in default_configs.items(): if key not in configs: configs[key] = value elif isinstance(default_configs[key], dict) and isinstance(configs[key], di...
def comb(n, r): """n choose r combination function""" import operator as op from functools import reduce r = min(r, n-r) numer = reduce(op.mul, range(n, n-r, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer // denom
def add_url_scheme(url: str) -> str: """Add the scheme to an existing url. Args: url (str): The current url. """ if url.startswith("https://") or url.startswith("http://"): return url return "https://%s" % url
def dot_index(index, data): """Internal method for indexing dicts by dot-notation. Args: index: a string with the dot-index key. data: a dict with the index. Returns: A list with the result. Example: >>> data = {'apa': {'bepa': {'cepa': 'depa'}}} >>> list(dot_index('a...
def lower_case_underscore_to_camel_case(text): """ Converts string or unicdoe from lower case underscore to camel case :param text: str, string to convert :return: str """ # NOTE: We use string's class to work on the string to keep its type split_string = text.split('_') class_ = text._...
def calc_average_ig(path_nodes, node_values): """Helper function for SHSEL filter algorithm. It returns the average Infomation gain value of one existing path in pruning function. Args: path_nodes (list): Node in path whose node_availability is True. node_values (dict): Dictionary about eve...
def removeblanklines(astr): """remove the blank lines in astr""" lines = astr.splitlines() lines = [line for line in lines if line.strip() != ""] return "\n".join(lines)
def adjoined_candidates_from_sentence(s, stoplist, min_keywords, max_keywords): """ Funcao para extrair candidatos a partir de uma unica sentenca """ candidates = [] sl = s.lower().split() for num_keywords in range(min_keywords, max_keywords + 1): for i in range(0, len(sl) - num_keywords...
def _is_single_alert_rule_format(rules_dict: dict) -> bool: """Are alert rules in single rule format. The Prometheus charm library supports reading of alert rules in a custom format that consists of a single alert rule per file. This does not conform to the official Prometheus alert rule file format ...
def sorted_k_partitions(seq, k): """ Returns a list of all unique k-partitions of `seq`. Each partition is a list of parts, and each part is a tuple. """ n = len(seq) groups = [] def generate_partitions(i): if i >= n: yield list(map(tuple, groups)) else: ...
def get_coauthors_from_pubs(pubs, not_person): """Get co-authors' names from the publication. Not include the person itself.""" my_collabs = list() for pub in pubs: my_collabs.extend( [ collabs for collabs in (names for names in pub.get('author', [])) ...
def json_absent_or_false(json, key): """Checks if the key does not appear or maps to false in the JSON object. Our measure of false here is the same as Python. """ return key not in json or not json[key]
def suppress(D, threshold): """ :param D: representation of the vector with respect to the normalized basis :param threshold: test value :return: dictionary in the same form as D where every value whose absolute value is less than a threshold is replaced with zero >>> suppress(forward([1, 2,...
def _literal_bytes(b): """ convert bytes to printable text. backslash and double-quotes will be escaped by backslash. "hello\" -> \"hello\\\" we don't add outter double quotes here, since completer also need this function's return value to patch completers. b'hello' -> "hello" ...
def run_inferencing(filenames): """ run model in inferencing mode (predict) params: model file name and sample dataframe return: a file of predictions """ print(f"\ninferring using filenames: {filenames}") # stub - implement this when we have a model to train basename = "basename" ...
def valid_account(name, allow_empty=False): """Returns validated account name or throws Assert.""" assert isinstance(name, str), "account must be string; received: %s" % name if not (allow_empty and name == ''): assert len(name) >= 3 and len(name) <= 16, "invalid account: %s" % name return name
def convertRunOptionsToSEDict(options): """Converts tuflow command line options to scenario/event dict. Tuflow uses command line option (e.g. -s1 blah -e1 blah) to set scenario values which can either be provided on the command line or through the FMP run form. The TuflowLoader can use these argum...
def common_items_v2(seq1, seq2): """ Find common items between two sequences - optimized version (v2) """ # return set(seq1).intersection(set(seq2)) seq_dict1 = {item:1 for item in seq1} for item in seq2: try: seq_dict1[item] += 1 except KeyError: pass retur...
def adjust_to_step(value, step, increase=False): """ Rounds any number to a multiple of the specified step. https://bablofil.ru Arguments increase (bool): if True - rounding will occur to a larger step value. """ return ((int(value * 100000000) - int(value * 100000000) % int( ...
def score_left_justification(mapping: tuple, length: int): """ Gives an integer score which can be used to sort alignments of the same sequence by their justification, especially for choosing the minimum scoring (most leftward) alignment. The score is the sum of the distances of all insertions from the ...
def func_xy_args_pq(x, y, *args, p="p", q="q"): """func. Parameters ---------- x, y: float args: tuple p, q: str Returns ------- x, y: float args: tuple p, q: str """ return x, y, None, None, args, p, q, None
def sevenish_number(num): """Sevenish Number""" power_of_two = 0 sevenish = 0 while num > 0: val = pow(7, power_of_two) if num % 2 == 1 else 0 sevenish += val power_of_two += 1 num //= 2 return sevenish
def extract_uri_schema(uri): """ Extract schema of given uri """ if uri: try: schema, data = uri.split(':', 1) return schema except: pass return None
def cond_lt(val, colorformat): """helper function for returning xlsxwriter conditional formatting dicts for less than conditions """ formDict = {'type': 'cell', 'criteria': 'less than', 'value': val, 'format': colorformat} return formDict
def get_merge_request_chain(mrs): """Returns the MR dependency chain.""" if len(mrs) == 0: return [] source_branches = set([mr.source_branch for mr in mrs]) roots = [] for mr in mrs: if mr.target_branch not in source_branches: roots.append(mr) mrs_dict = {mr.target_br...
def time_str(s): """ Convert seconds to a nicer string showing days, hours, minutes and seconds """ days, remainder = divmod(s, 60 * 60 * 24) hours, remainder = divmod(remainder, 60 * 60) minutes, seconds = divmod(remainder, 60) string = "" if days > 0: string += f"{int(days):d} ...
def _first_largest(scores): """ Similar to max, but returns the first element achieving the high score If max receives a tuple, it will break a tie for the highest value of entry[i] with entry[i+1]. We don't want that here - to better match with the results of other tools, we want to be able to define w...
def split_list(list, split_symbol): """split list with string Args: list (list): the list need to be splited split_symbol (string): the symbol used for split Returns: list: splited list """ if(list == []): return [] else: return list[0].split(split_symbo...
def make_kmer_list(k, alphabet): """ Generate kmer list. """ if k < 0: print("Error, k must be an inter and larger than 0.") kmers = [] for i in range(1, k + 1): if len(kmers) == 0: kmers = list(alphabet) else: new_kmers = [] for kmer ...
def error_message(msg=None): """Builds a Gateway compataible error message for UI.""" error_msg = {'GatewayError': {'Message': 'An error occurred.'}} if msg is not None: error_msg['GatewayError']['Message'] = msg error_msg['GatewayError']['Exception'] = '' return error_msg
def application_error(e): """Return a custom 500 error.""" return "Sorry, unexpected error: {}".format(e), 500
def clean_chamber_input(chamber): """ Turns ambiguous chamber information into tuple (int, str) with chamber id and chamber name """ if type(chamber) == str: if chamber == '1': chamber = 1 elif chamber == '2': chamber = 2 elif chamber == 'GA': chamber ...
def scale_48vcurrent(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to Amps (if reverse=False), or convert a value in Amps to raw (if reverse=True). For now, raw values are hundredths of a...
def remove_redundant_ws(line: str) -> str: """Remove redundant white space from a line. Redundant being multiple spaces where only one is needed. >>> remove_redundant_ws(" a b c ") 'a b c' >>> remove_redundant_ws("a b c") 'a b c' >>> remove_redundant_ws(" ") '' Args: ...
def char_analyzer(text): """ This is used to split strings in small lots anttip saw this in an article so <talk> and <talking> would have <Tal> <alk> in common should be similar to russian I guess """ tokens = text.split() return [token[i: i + 3] for token in tokens for i in range(len(to...
def apply_plot_options(options, viewpoint, window): """Adjust viewpoint and window properties according to input options. Args: options (dict): Dictionary containing parsed or default option values viewpoint (dict): dictionary containing viewpoint properties (orientation, scale) window ...
def _turn_db_timezone_to_utc(original_uri: str) -> str: """ string operator that make any db into utc timezone Args: original_uri (str): original uri without set timezone Returns: str: uri with explicittly set utc timezone """ # Do set use `init_command` for sqlite, since it doesn'...
def is_there_overlap_wlimits(w1, w2): """Check if there is overlap between 2 consecutive telluric regions.""" ret = False for i in range(len(w1)-1): if w2[i] >= w1[i+1]: ret = True break return ret
def format_story(ticket): """ adds some information to the story. >>> format_story([23,'','','','','','','','','','','','','',u'My very own story']) u'My very own story (Trac Ticket #23)' """ return ticket[14] + u" (Trac Ticket #%s)" % ticket[0]
def get_chunk_type(tok, idx_to_tag): """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} """ tag_name = idx_to_tag[tok] tag_class = tag_name.split('-')[0] tag_type = tag_name.split('-')[-1] return tag_class, tag_type
def get_dial_qa_embeddings_file_path(data_dir: str, data_type: str, emb_type: str, split: str = '1.0', ext: str = 'h5') -> str: """ QA embeddings in dialog format ...
def _iou(box1, box2): """ Computes Intersection over Union value for 2 bounding boxes :param box1: array of 4 values (top left and bottom right coords): [x0, y0, x1, x2] :param box2: same as box1 :return: IoU """ b1_x0, b1_y0, b1_x1, b1_y1 = box1 b2_x0, b2_y0, b2_x1, b2_y1 = box2 i...
def is_digit(value): """ Check that value is digit. :param value: value to check :return: True if value is digit, otherwise False """ try: float(value) return True except ValueError: return False
def get_weight_update(previous_weight, weight): """ args: previous_weight: list""" deltas = [] for i, w in enumerate(weight): deltas.append(w - previous_weight[i]) return deltas
def remove_prefix_from_base64(base64_with_prefix): """ :param base64_with_prefix: base64-encoded image which has a special prefix. The last character of this prefix is ','. Here are some examples of the prefixes: 'data:image/png;base64,', 'data:image/gif;base6...
def first(iterable): """ Get the first item in the iterable. """ return next(iter(iterable))
def ema(avg, sample, weight=0.1): """Exponential moving average.""" return sample if avg is None else (avg * (1.0 - weight)) + (sample * weight)
def num_as_bytes(n): """ Encodes an integer in UTF-8 bytes. """ return str(n).encode("utf-8")
def beta_for_hw(hw_int,hw): """ beta_for_hw(hw_int,hw) -> beta returns the length scale factor to scale from hw_int to hw """ return (hw/hw_int)**(-0.5)
def filter_dict(dict_to_filter, target_value): """Filter a dictionary based on certain value """ filtered_dict = {} for key, value in dict_to_filter.items(): if target_value == value: filtered_dict[key] = value return filtered_dict
def sqrt(x): """Square root of x; support complex numbers Examples: ------------- >>> sqrt(4) 2.0 >>> sqrt(-1) 1j >>> sqrt(0) 0.0""" a = pow(x, 0.5) if isinstance(x, complex): return a elif x < 0: return complex(0, a.imag) else: return a.real
def split_by_thousand(n): """ parses integers up to billion down to sub thousand and returns remaining numbers list :param n: integer :return: res: list """ res = [] while n: n, r = divmod(n, 1000) res.append(r) return res
def RPL_NOWAWAY(sender, receipient, message): """ Reply Code 306 """ return "<" + sender + ">: " + message
def ArrayOfUTF16StreamCopyToStringTable(byte_stream, byte_stream_size=None): """Copies an array of UTF-16 formatted byte streams to a string table. The string table is a dict of strings with the byte offset as their key. The UTF-16 formatted byte stream should be terminated by an end-of-string character (\x00\...
def dist(p, q): """ Compute distance between two 3D vectors p: array Cartesian coordinates for one of the vectors q: array Cartesian coordinates for one of the vectors """ return ((p[0] - q[0])**2 + (p[1] - q[1])**2 + (p[2] - q[2])**2)**0.5
def model(x, a, b, c): """ Equation to be fitted to the data. The purpose of curve fitting is to find the coefficients a, b, c. """ return a * x ** 2 + b * x + c
def padding_size(length: int, block_size: int, ceil: bool = True) -> int: """Return minimum the multiple which is large or equal than the `length` Args: block_size (int): the length of bytes, no the length of bit """ remainder = length % block_size if ceil: return (block_size - rem...
def flip_ss(ss): """ Flips a secondary structure Only flips the unpaired bases e.g. (.((....))....( -> ).((....))....) """ bp_list = [] unmatch_list = [] ss = list(ss) for idx, c in enumerate(ss): if c == '(': bp_list.append(idx) elif c == ')': if len(bp_list): bp_lis...
def numlookup(x, y): """ Try to resolve y as a numberic, then try to look it up a key in dictionary x. """ try: return int(y) except ValueError: return x[y]
def fib(n): """ The following function determines the Fibonacci Sequence. Finding the Fibonacci sequence with seeds of 0 and 1. The sequence is 0,1,1,2,3,5,8,13,..., where the recursive relation is fib(n) = fib(n-1) + fib(n-2). param n: the index, starting from 0 return: the sequence """ if n <= 1: ...
def Mapping(metric: dict, pattern: str = "/", http_method: str = "GET", delta: int = 1, last: str = "false"): """Builder of parameters to create Mapping Args: :param metric: Metric to be mapped :param pattern: URL pattern to map; deafult: / :param http_method: Method to map; ...
def pipe(data, *functions): """ Pipe a value through a sequence of functions I.e. ``pipe(data, f, g, h)`` is equivalent to ``h(g(f(data)))`` We think of the value as progressing through a pipe of several transformations, much like pipes in UNIX ``$ cat data | f | g | h`` >>> double = lambda ...
def get_the_character(characters_list=[]): """ Allows you to find the number escaped or the other number. """ indice_character = 0 last_character = characters_list[0] for character in characters_list: if character != last_character: break else: l...
def get_query_param_value(query_param, key): """ Get query param based on provided key :param query_param: Query params from request :param key: query param key :return: query param value """ query_param_dict = dict(query_param) return query_param_dict.get(key)
def is_valid_key(user_key_input, chrom): """ Checks for valid user input. """ if len(user_key_input) != 1 and len(user_key_input) != 2: return False elif user_key_input not in chrom: return False else: return user_key_input
def is_dunder(name: str) -> bool: """ Check whether a given attribute name is a dunder, e.g. `__name__`. Arguments: name: The provided attribute name. Returns: `True` if `name` is a valid dunder, else `False`. """ if (name[:2] and name[-2:]) in ("__",): return True ...
def getOperands(inst): """ Get the inputs of the instruction Input: - inst: The instruction list Output: - Returns the inputs of the instruction """ if inst[0] == "00100": return inst[3], inst[4] else: return inst[2], inst[3]
def is_job_array(job): """ Check if the given job is an array. :param job: the job dictionary returned by AWS Batch api :return: true if the job is an array, false otherwise """ return "arrayProperties" in job and "size" in job["arrayProperties"]
def step(time, value, tstep): """" Implements vensim's STEP function Parameters ---------- value: float The height of the step tstep: float The time at and after which `result` equals `value` Returns ------- - In range [-inf, tstep) returns 0 - In range [tstep, ...
def string_concatenation(a: str, b: str, c: str) -> str: """ Concatenate the strings given as parameter and return the concatenation :param a: parameter :param b: parameter :param c: parameter :return: string concatenation """ return a + b + c
def utf8_encode(s: str) -> bytes: """Encodes a string with utf-8 and returns its byte sequence. Invalid surrogates will be replaced with U+FFFD. Args: s: A string to encode with utf-8. Returns: A utf-8 encoded byte sequence. """ s = s.encode("utf-16", "surrogatepass").decode("...
def directory_hash_id(id): """ >>> directory_hash_id( 100 ) ['000'] >>> directory_hash_id( "90000" ) ['090'] >>> directory_hash_id("777777777") ['000', '777', '777'] """ s = str(id) l = len(s) # Shortcut -- ids 0-999 go under ../000/ if l < 4: return ["000"] ...
def permissions_to_label_css(permissions): """Return Bootstrap label class qualifier corresponding to permissions. Return <this> in class="label label-<this>". """ if permissions.startswith('all_'): return 'success' elif permissions.startswith('restricted_'): return 'warning' el...
def simple_instruction(name, offset): # """ """ print("{}".format(name)) return offset + 1
def get_row_index_with_max_edges(d: int) -> int: """ Return the row index of any benchmark CSV file with given dimension. The number of nodes considered "inseresting" are: - 14 - 16 - 22 - 52 - 202 - 1000 :param d: graph dimension in term nodes :return: index of ...
def recovery_type_exists(payload): """recherche le type de pick up point""" recovery_type=payload.get('categorie') if recovery_type is None: return None else: recovery = { 'emballage': '1', 'verre': '2', 'textile': '3' } ...
def set_or_none(list_l): """Function to avoid list->set transformation to return set={None}.""" if list_l == [None]: res = None else: res = set(list_l) return res
def filter_payload(payload: str) -> str: """ Convert payload to text and search for not allowed symbols. """ import re # convert to string if not isinstance(payload, str): payload = str(payload) # search for not allowed characters if re.search(r'[^_A-z0-9-]', payload): message ...
def zero_date(*args): """ is zero date """ for ztime in args: if isinstance(ztime, str) and \ (ztime == '0000-00-00' or ztime == '0000-00-00 00:00:00'): return True return False
def convert_to_number(string): """ Tries to cast input into an integer number, returning the number if successful and returning False otherwise. """ try: number = int(string) return number except: return False
def mands(datum): """Combines minutes and seconds into seconds total""" result = datum['s'] if datum['m'] > 0: result += datum['m'] * 60 return result
def sanitize(s, strict=True): """ Sanitize a string. Spaces are converted to underscore; if strict=True they are then removed. Parameters ---------- s : str String to sanitize strict : bool If True, only alphanumeric characters are allowed. If False, a limited set ...
def bin_search(query, data): """ Query is a coordinate interval. Binary search for the query in sorted data, which is a list of coordinates. Finishes when an overlapping value of query and data exists and returns the index in data. """ i = int(round(len(data)/2)) # binary search prep lower, upper = 0, len(data)...
def typeOf(value): """ Get the type of value. :param value: What to get the type of. :type value: anything :returns: str """ return str(type(value))
def convert_length_to_km(length): """Convert length like 1000 to '1' or 30 to '30M'""" try: t_length = int(length) if t_length < 1000: length_str = str(t_length) + "M" else: length_str = "%g" % (float(t_length) / 1000.0) except ValueError: length_st...
def is_port_open(port): """Check if port is open Arguments: port {int} -- port Returns: bool """ import socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: port = int(port) return not s.connect_ex(('localhost', port)) == 0
def is_winner(bo, le): """ this funciton check if the input leads to a win :param bo: board (array len 10, first position is empty then the board starts) :param le: X or a O :return: true of a false (True for winner) """ return ((bo[7] == le and bo[8] == le and bo[9] == le) or (...
def ascending(list: list) -> bool: """ Check if a list is in ascending ordering :rtype: bool :param list: a non empty list to check :return: if the list is in ascending order """ for i in range(len(list) - 1): if list[i] < list[i + 1]: return True return False
def isInteger(value): """ Validate if a value is integer or not """ try: val = int(value) return True except ValueError: return False
def get_full_qualname(cls): """Return fully qualified class name""" return cls.__module__ + '.' + cls.__name__
def snips2top(snips_example, intent): """Converts Snips format to TOP format Args: snips_example: list, one example following snips format intent: str Returns: query_text, top_format_schema """ query_text = "" top_format_str = f"[IN:{intent.upper()}" for text_chunk...