content
stringlengths
42
6.51k
def factorial(letter_qty): """ :param letter_qty: how many letters are key in :return: total arrangement qty """ if letter_qty == 0: return 1 else: temp = letter_qty * factorial(letter_qty - 1) return temp
def bann(code): """ If banned return True else False """ ban_list = ['First Ride', 'New Customers', 'From SMU', 'From NTU', 'From NUS', 'From SUTD', 'From SIM', 'First GrabHitch', 'New GrabPay', 'First 2 Rides', 'First 4 Rides'] for word in ban_list: if code.find(wor...
def convert_to_ents_dict(tokens, tags): """ Handle the BIO-formatted data :param tokens: list of tokens :param tags: list of corresponding BIO tags :return: json-formatted result """ ent_type = None entities = [] start_char_offset = 0 end_char_offset = 0 start_char_entity =...
def nsf(num, n=1): #from StackOverflow: https://stackoverflow.com/questions/9415939/how-can-i-print-many-significant-figures-in-python """n-Significant Figures""" while n-1 < 0: n+=1 numstr = ("{0:.%ie}" % (n-1)).format(num) return float(numstr)
def get_outputs(job: dict, configuration: dict, data: dict) -> list: """ Get list of output Datareference """ outputs = [] if "outputs" in job: for data_name in job["outputs"]: data_object = data[data_name] outputs.append(data_object["pipelinedata_object"]) retu...
def weigher(r, method='hyperbolic'): """ The weigher function. Must map nonnegative integers (zero representing the most important element) to a nonnegative weight. The default method, 'hyperbolic', provides hyperbolic weighing, that is, rank r is mapped to weight 1/(r+1) Args: r: Integer valu...
def integer(value, numberbase=10): """OpenEmbedded 'integer' type Defaults to base 10, but this can be specified using the optional 'numberbase' flag.""" return int(value, int(numberbase))
def getPlayerID(playerOrID): """Returns the Player ID for the given player.""" if playerOrID is None or playerOrID == -1: return -1 if isinstance(playerOrID, int): return playerOrID return playerOrID.getID()
def elliptical_u(b, k, upsilon, l_tilde, n): """ Disutility of labor supply from the elliptical utility function Args: b (scalar): scale parameter of elliptical utility function k (scalar): shift parametr of elliptical utility function upsilon (scalar): curvature parameter of ell...
def get_value_with_field(model, field, null=None): """ Get value from a model or dict or list with field Field must be a string or number value usage: >>> model_value_with_field({"key1": "value1", "key2": "value2"}, "key1", "default") "value1" >>> model_value_with_field({"key1"...
def _apply_correction(tokens, correction, offset): """Apply a single correction to a list of tokens""" start_token_offset, end_token_offset, _, insertion = correction to_insert = insertion[0].split(" ") end_token_offset += (len(to_insert) - 1) to_insert_filtered = [t for t in to_insert if t != ""]...
def get_last_n_features(feature, current_words, idx, n=3): """For the purposes of timing info, get the timing, word or pos values of the last n words (default = 3). """ if feature == "words": position = 0 elif feature == "POS": position = 1 elif feature == "timings": pos...
def traffic_gen(flows: dict, flow_rates, num_bytes, K, skewness): """Generate the traffic configurations. Args: flows (dict): Dictionary of flows information (key, value) = (flowID, (flowID, (src, dst))). flow_rates (dict): Dictionary of flow rate information (key, value) = (flowID, flow rate). ...
def parsePort(port): """ Converts port in string format to an int :param port: a string or integer value :returns: an integer port number :rtype: int """ result = None try: result = int(port) except ValueError: import socket result = socket.getservbyname(port) return result
def _CreateAssetsList(path_tuples): """Returns a newline-separated list of asset paths for the given paths.""" dests = sorted(t[1] for t in path_tuples) return '\n'.join(dests) + '\n'
def checksum(data): """ Calculates the checksum, given a message without the STX and ETX. Returns a list with the ordered checksum bytes""" calc_sum = 0 for i in data: calc_sum += i low_sum = calc_sum >> 8 & 0xFF high_sum = calc_sum & 0xFF return bytearray([high_sum, low_sum])
def get_duplicates(iterable): """ Returns set of duplicated items from iterable. Item is duplicated if it appears at least two times. """ seen = set() seen2 = set() for item in iterable: if item in seen: seen2.add(item) else: seen.add(item) return ...
def find_workflow_uuid(galaxy_workflows,uuid): """ Finds a particular workflow with the given uuid. :param galaxy_workflows: The list of workflows to search through. :param uuid: The workflow uuid to search for. :return: The matching workflow. :throws: Exception if no such matching workflow....
def fill_point(x, y, z, _): """ Returns a string defining a set of minecraft fill coordinates relative to the actor. In minecraft, the y axis denotes the vertical (non-intuitively). """ return f'~{int(x)} ~{int(z)} ~{int(y)}'
def rbits_to_int(rbits): """Convert a list of bits (MSB first) to an int. l[0] == MSB l[-1] == LSB 0b10000 | | | \\--- LSB | \\------ MSB >>> rbits_to_int([1]) 1 >>> rbits_to_int([0]) 0 >>> bin(rbits_to_int([1, 0, 0])) '0b100' >>> bin(rbits_to...
def stick_to_bounds(box, bounds=(0,0,1,1)): """ Sticks the given `box`, which is a `(l, t, w, h)`-tuple to the given bounds which are also expressed as `(l, t, w, h)`-tuple. """ if bounds is None: return box l, t, w, h = box bl, bt, bw, bh = bounds l += max(bl - l, 0) l -= ...
def setup_path(project, test_data): """ Setting up project URL :param project: from pytest_addoption :return: project URL """ url = project if project == 'market': url = test_data[0]['url'] elif project == 'bank': url = test_data[0]['url'] elif project == 'intranet': ...
def get_project_host_names_local(): """" In tests and local projectnames are hardcoded """ return ['wiki', 'dewiki', 'enwiki']
def map_route_to_route_locations(vehicle_location, route, jobs): """ Maps route list, which includes job ids to route location list. :param vehicle_location: Vehicle location index. :param route: Job ids in route. :param jobs: Jobs information, which includes job ids, location indexes and delivery....
def post_data(data): """ Take a dictionary of test data (suitable for comparison to an instance) and return a dict suitable for POSTing. """ ret = {} for key, value in data.items(): if value is None: ret[key] = '' elif type(value) in (list, tuple): if value a...
def flatten(x): """flatten flatten 2d array to 1d array :param x: initial array :return: array after flatten """ x_flatten = [] for i in range(len(x)): for j in range(len(x[0])): x_flatten.append(x[i][j]) return x_flatten
def sanitize_plugin_class_name(plugin_name: str, config: bool = False) -> str: """ Converts a non-standard plugin package name into its respective class name. :param: plugin_name: String a plugins name :param: config: Boolean true if it should convert into a config name instead of a class name. For give...
def variance(x): """ Return the standard variance If ``x`` is an uncertain real number, return the standard variance. If ``x`` is an uncertain complex number, return a 4-element sequence containing elements of the variance-covariance matrix. Otherwise, return 0. ...
def int_to_roman(number: int) -> str: """ Given a integer, convert it to an roman numeral. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(int_to_roman(value) == key for key, value in tests.items()) True ""...
def dice_coefficient(a, b): """dice coefficient 2nt / (na + nb).""" if not len(a) or not len(b): return 0.0 if len(a) == 1: a = a + u'.' if len(b) == 1: b = b + u'.' a_bigram_list = [] for i in range(len(a) - 1): a_bigram_list.append(a[i:i + 2]) b_bigram_l...
def int_to_bytes(number: int) -> bytes: """Convert integer to byte array in big endian format""" return number.to_bytes((number.bit_length() + 7) // 8, byteorder='big')
def annotate_counts(node): """Recursive function to annotate each node with the count of all of it's descendants, as well as the count of all sibling comments plus their children, made after each node. """ # If no replies, this is a leaf node. Stop and return 1. node['reply_count'] = 0 if no...
def format_data(account): """Format account into printable format: name, description and country""" name = account["name"] description = account["description"] country = account["country"] return f"{name}, a {description}, from {country}"
def caption_from_metadata(metadata): """ converts metadata list-of-lists to caption string which is one antinode per line """ caption = "" for an in range(len(metadata)): [cx, cy, a, b, angle, rings] = metadata[an] #this_caption = "[{0}, {1}, {2}, {3}, {4}, {5}]".format(cx, cy, a, b,...
def smoothstep(x): """Polynomial transition from 0 to 1 with continuous first derivative""" return -2*x**3 + 3*x**2
def format_ctor_arguments(arguments, parent, id, size): """Format constructor arguments; returns a list arguments: Constructor arguments (list) parent: Parent widget (string or unicode) id: Widget ID e.g. wxID_ANY size: Widget size 'width, height'""" vSize = size.split(',') for i in range(l...
def reverse_reps(replacements): """Map from replacement to source and reverse each string also The string reverse is needed because the steps_to_molecule reverses the molecule string itself. """ return {b[::-1]: a[::-1] for a, b in replacements}
def obtenerBinario(numero): """ bin(numero) obtiene el valor binario de numero [2:] obtiene los elementos de del binario anterior excepto los primeros 2, por ejemplo 11000000[2:] regresa 000000 zfill(8) rellena con ceros a la izquiera el valor anterior hasta que este tenga longitud 8, por ejemplo 111111 regresa...
def _format_datetime_for_js(stamp): """Formats time stamp for Javascript.""" if not stamp: return None return stamp.strftime("%Y-%m-%d %H:%M:%S %Z")
def yaml_list_to_dict(yaml_list): """Converts a yaml list (volumes, configs etc) into a python dict :yaml_list: list of a yaml containing colon separated entries :return: python dict """ return {i.split(":")[0]: i.split(":")[1] for i in yaml_list}
def _linux_kernel_dso_name(kernel_build_target): """Given a build target, construct the dso name for linux.""" parts = kernel_build_target.split(":") return "%s:libtfkernel_%s.so" % (parts[0], parts[1])
def _set_name_and_type(param, infer_type, word_wrap): """ Sanitise the name and set the type (iff default and no existing type) for the param :param param: Name, dict with keys: 'typ', 'doc', 'default' :type param: ```Tuple[str, dict]``` :param infer_type: Whether to try inferring the typ (from th...
def _gen_alt_forms(term): """ Generate a list of alternate forms for a given term. """ if not isinstance(term, str) or len(term) == 0: return [None] alt_forms = [] # For one alternate form, put contents of parentheses at beginning of term if "(" in term: prefix = term[term.f...
def factorial(digit: int) -> int: """ >>> factorial(3) 6 >>> factorial(0) 1 >>> factorial(5) 120 """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1))
def nearest_neighbors_targets(x_train, y_train, x_new, k, distance): """Get the targets for the k nearest neighbors of a new sample, according to a distance metric. """ # Associate training data and targets in a list of tuples training_samples = list(zip(x_train, y_train)) # Sort samples by th...
def hierarchical_label(*names): """ Returns the XNAT label for the given hierarchical name, qualified by a prefix if necessary. Example: >>> from qixnat.helpers import hierarchical_label >>> hierarchical_label('Breast003', 'Session01') 'Breast003_Session01' >>> hierarchical_lab...
def get_word_from_derewo_line(line): """Processor for individual line from DeReWo textfile. Args: line: Single line from DeReWo text file Returns: Lowercase word, None if invalid """ line = line.split() # skip words with whitespace if len(line) > 2: return None ...
def date_facet_interval(facet_name): """Return the date histogram interval for the given facet name The default is "year". """ parts = facet_name.rpartition('.') interval = parts[2] if interval in ['month', 'year', 'decade', 'century']: return interval else: return 'year'
def is_palindrome(word): """Check if input is a palindrome.""" if len(word) <= 1: return True return word[0] == word[-1] and is_palindrome(word[1:-1])
def onek_encoding_unk(x, allowable_set): """One-hot embedding""" if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: int(x == s), allowable_set))
def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/n
def build_links_package_index(packages_by_package_name, base_url): """ Return an HTML document as string which is a links index of all packages """ document = [] header = f"""<!DOCTYPE html> <html> <head> <title>Links for all packages</title> </head> <body>""" document.append(header) ...
def get_eqn(p0, p1): """ Returns the equation of a line in the form mx+b as a tuple of (m, b) for two points. Does not check for vertical lines. """ m = (p0[1] - p1[1]) / (p0[0] - p1[0]) return (m, p0[1] - m * p0[0])
def find_min_cand(counts): """ return list of candidates who need to be eliminated this round WARNING: doesn't deal properly with ties in support for min candidates.... """ ans = [] if len(counts.keys()) == 0: return None curmin = min(list(counts.values())) for k in counts.keys...
def last(xs): """ last :: [a] -> a Extract the last element of a list, which must be finite and non-empty. """ return xs[-1]
def find_peak(A): """find pick element""" if A == []: return None def recursive(A, left=0, right=len(A) - 1): """helper recursive function""" mid = (left + right) // 2 # check if the middle element is greater than its neighbors if ((mid == 0 or A[mid - 1] <= A[mid]...
def Pad(ids, pad_id, length): """Pad or trim list to len length. Args: ids: list of ints to pad pad_id: what to pad with length: length to pad or trim to Returns: ids trimmed or padded with pad_id """ assert pad_id is not None assert length is not None if len(ids) < length: a = [pad...
def get_network_name_from_url(network_url): """Given a network URL, return the name of the network. Args: network_url: str - the fully qualified network url, such as (https://www.googleapis.com/compute/v1/projects/' 'my-proj/global/networks/my-network') Returns: str - the netwo...
def in_bisect(word_list, target): """ Takes a sorted word list and checks for presence of target word using bisection search""" split_point = (len(word_list) // 2) if target == word_list[split_point]: return True if len(word_list) <= 1: return False if target < word_list[sp...
def dotProduct(listA, listB): """ listA: a list of numbers listB: a list of numbers of the same length as listB Returns the dot product of all the numbers in the lists. """ dotProd = 0 for num in range(len(listA)): prod = listA[num] * listB[num] dotProd = dotPr...
def word_overlap(left_words, right_words): """Returns the Jaccard similarity between two sets. Note ---- The topics are considered sets of words, and not distributions. Parameters ---------- left_words : set The set of words for first topic right_words : set The set of...
def func(arg): """ :param arg: taking args :return: returning square """ x = arg*arg return x
def is_triangle_possible(triangle): """Check if triangle is possible.""" return sum(sorted(triangle)[:2]) > max(triangle)
def get_nr_dic1_keys_in_dic2(dic1, dic2): """ Return number of dic1 keys found in dic2. >>> d1 = {'hallo': 1, 'hello' : 1} >>> d2 = {'hallo': 1, 'hello' : 1, "bonjour" : 1} >>> get_nr_dic1_keys_in_dic2(d1, d2) 2 >>> d1 = {'hollo': 1, 'ciao' : 1} >>> get_nr_dic1_keys_in_dic2(d1, d2) ...
def find_largest_digit_helper(n, lar): """ This is the help function to find the largest digit :param n :(int) the number to find the largest digit :param lar:(int) found the largest digit :return :(int) the largest digit """ if n < lar: return lar else: if n % 10 > lar: lar = n % 10 return find_la...
def format_coord(x, y): """coordinate formatter replacement""" return 'x={x}, y={y:.2f}'.format(x=x, y=y)
def isolate_rightmost_0_bit(n: int) -> int: """ Isolate the rightmost 0-bit. >>> bin(isolate_rightmost_0_bit(0b10000111)) '0b1000' """ return ~n & (n + 1)
def convert(client, denomination, amount): """ Convert the amount from it's original precision to 18 decimals """ if denomination == 'nct': return client.to_wei(amount, 'ether') elif denomination == 'nct-gwei': return client.to_wei(amount, 'gwei') elif denomination == 'nct-wei': ...
def repeat_val (num:int, val): """ repeat a value several k times. """ return [val for _ in range(num - 1)]
def to_dependencies_of(g): """ Compute the dependencies of each path var. :param d: an adjacency list of dependency => [depends on, ...] :return: an adjacency list of the given data structure such that the k => [depends on, ...]. The vertices in the values are presorted to ensure reprod...
def _user_to_simple_dict(user: dict) -> dict: """Convert Notion User objects to a "simple" dictionary suitable for Pandas. This is suitable for objects that have `"object": "user"` """ record = { "notion_id": user["id"], "type": user["type"], "name": user["name"], "avata...
def duration(s): """Turn a duration in seconds into a human readable string""" m, s = divmod(s, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) parts = [] if d: parts.append('%dd' % d) if h: parts.append('%dh' % h) if m: parts.append('%dm' % m) if s: pa...
def is_discrete(num_records: int, cardinality: int, p=0.15): """ Estimate whether a feature is discrete given the number of records observed and the cardinality (number of unique values) The default assumption is that features are not discrete. Parameters ---------- num_records : int ...
def average(nums,n): """Find mean of a list of numbers.""" return sum(nums) / n
def find_str(string: str, pattern: str) -> list: """ Find all indices of patterns in a string Parameters ---------- string : str input string pattern : str string pattern to search Returns ------- ind : list list of starting indices """ import re ...
def _cons8_99(m8, L88, L89, d_gap, k, Cp, h_gap): """dz constrant for edge gap sc touching 2 corner gap sc""" term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts term2 = 2 * k * d_gap / m8 / Cp / L89 # cond to adj bypass corner return 1 / (term1 + term2)
def expand_brackets(text): """ Change a text with TEXT[ABC..] into a list with [TEXTA, TEXTB, TEXC, ... if no bracket is used it just return the a list with the single text It uses recursivity to allow several [] in the text :param text: :return: """ if text is None: return (None...
def tokenize(separators, seq): """tokenize(separators, seq) : Transforms any type of sequence into a list of words and a list of gap lengths seq : the sequence (any sequence type, e.g. a list, tuple, string, ...) [will not be modified] separators : a sequence of values to be used as separators between words. a...
def string_to_integer(word): """ Converts a string into the integer format expected by the neural network """ integer_list = list() for character in word: integer_list.append(character) for index in range(integer_list.__len__()): current_character = integer_list[index] integer_...
def shorten(x, length): """ Shorten string x to length, adding '..' if shortened """ if len(x) > (length): return x[:length - 2] + '..' return x
def Right(text, number): """Return the right most characters in the text""" return text[-number:]
def walk_line(strings, max_x, max_y, coordinates, direction, path_char): """ Given some starting points and a direction, find any connected corners in said direction. :param strings string - the text that may contain rectangles. :param max_x int - the boundary/width of the text. :param max_y int - ...
def _GetStepsAndTests(failed_steps): """Extracts failed steps and tests from failed_steps data structure. Args: failed_steps(TestFailedSteps): Failed steps and test information. Example of a serialized TestFailedSteps: { 'step_a': { 'last_pass': 4, 'tests': { ...
def listize(obj): """ If obj is iterable and not a string, returns a new list with the same contents. Otherwise, returns a new list with obj as its only element. """ if not isinstance(obj, str): try: return list(obj) except: pass return [obj]
def get_version(data): """ Parse version from changelog written in RST format. """ def all_same(s): return not any(filter(lambda x: x != s[0], s)) def has_digit(s): return any(char.isdigit() for char in s) data = data.splitlines() return next(( v for v, u in...
def string_distance(a: str, b: str): """ Returns the levenshtein distance between two strings, which can be used to compare their similarity [Code source](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py) """ if len(a) < len(b): return string_distance(b, a) ...
def strip_whitespace_from_data(data): """Recursively strips whitespace and removes empty items from lists""" if isinstance(data, str): return data.strip() elif isinstance(data, dict): return {key: strip_whitespace_from_data(value) for key, value in data.items()} elif isinstance(data, lis...
def how_many_namefellows(queue: list, person_name: str) -> int: """ :param queue: list - names in the queue. :param person_name: str - name you wish to count or track. :return: int - the number of times the name appears in the queue. """ cnt = 0 for name in queue: if name == person...
def year_list_to_cite_years(year_list,p_year): """convert year_list into cite_years :param year_list,p_year: :return: cite_years """ year_list_int = [] for s in year_list: try: year_list_int.append(int(s)) except: pass y = [p_year+i for i in range(2021...
def clean_string(string): """Clean a string. Trims whitespace. Parameters ---------- str : str String to be cleaned. Returns ------- string Cleaned string. """ assert isinstance(string, str) clean_str = string.strip() clean_str = clean_str.replace(" ...
def good_fibonacci(n): """Return pair of Fibonacci numbers, F(n) and F(n-1)""" if n <= 1: return n, 0 a, b = good_fibonacci(n - 1) return a + b, a
def step_forward(position, panel_r, panel_l, connection_map): """ When each character is read from the input, this function is sounded until it reaches the reflect board. This function specifies that at each step I have to go through the index of each page Of the routers to reach the reflect board. ...
def datetime_to_float(datetime): """ SOPC_DateTime* (the number of 100 nanosecond intervals since January 1, 1601) to Python time (the floating point number of seconds since 01/01/1970, see help(time)). """ nsec = datetime[0] # (datetime.date(1970,1,1) - datetime.date(1601,1,1)).total_seconds() ...
def readline_setup(exports): """setup readline completion, if available. :param exports: the namespace to be used for completion :return: True on success """ try: import readline except ImportError: # no completion for you. readline = None return False else:...
def is_bad_port(port): """ Bad port as per https://fetch.spec.whatwg.org/#port-blocking """ return port in [ 1, # tcpmux 7, # echo 9, # discard 11, # systat 13, # daytime 15, # netstat 17, # qotd 19, # chargen ...
def e_vect(n, i): """ get a vector of zeros with a one in the i-th position Parameters ---------- n: vector length i: position Returns ------- an array with zeros and 1 in the i-th position """ zeros = [0 for n_i in range(n)] zeros[i] = 1 return zeros
def zoo_om_re_ratio(carbon, d_carbon, ratio, d_ratio): """carbon and d_carbon im moles carbon, ratio - to be changed d_carbon, d_ratio - what changes the ratio""" return (carbon+d_carbon)/(carbon/ratio+d_carbon/d_ratio)
def sumNumber(num): """ Gives the sum of all the positive numbers before input number """ # Used for rank based selection sum_num = 0 for i in range(num+1): sum_num += i return sum_num
def filter_nodes(nodes, env='', roles=None, virt_roles=''): """Returns nodes which fulfill env, roles and virt_roles criteria""" retval = [] if not roles: roles = [] if virt_roles: virt_roles = virt_roles.split(',') for node in nodes: append = True if env and node.get...
def lower(low, temp): """ :param low: int, the lowest temperature data before :param temp: int, the new temperature data :return: int, the lower one between high and temp, which becomes the lowest temperature """ if temp < low: return temp return low