content
stringlengths
42
6.51k
def encode_allele(allele, encoding): """Encodes an allele according to encoding. Args: allele (str): the allele to encode encoding (dict): the allele encoding Returns: str: the encoded allele. Note ---- The function search for the allele and its complement. If none...
def signature_match(sig,*args,**kwargs): """Check if a function will accept a set of arguments.""" fail = False n_args = len(args) # we have to pop from kwargs to see if there are extrana but if not # then we need a full copy for testing the function call kwargs_popper = dict(kwargs) if n_args <= len(sig['args...
def _normalize(directory: str) -> str: """Make lowercase and replace spaces with underscores.""" directory = directory.lower() directory = directory.replace(' ', '_') if directory[-1] == '.': directory = directory[:-1] return directory
def set_compare(ref_res, output): """ Compares reference result to generated output. Args: ref_res: reference result in JSON representation output: string output when executing generated code Returns: true iff all tokens in reference appear in output """ for row in ...
def searchterm_match(term, string): """ returns 2 for perfect match, and 1 if term is substring """ if term.lower() in string.lower(): if term.lower() == string.lower(): return 2 else: return 1 else: return 0
def m2pType(name): """ Map MySQL types to python types. Parameters ---------- name : str A MySQL type name. Returns ------- kind : type A python type corresponding to name, or None if a corresponding type cannot be determined. """ if name[:7] == 'varchar...
def compare_dicts(dict1, dict2): """Compare two dictionaries and return a dictionary of added, deleted, and replaced items.""" if not isinstance(dict1, dict) or not isinstance(dict2, dict): return (dict1, dict2) deleted = { key: dict1[key] for key in dict1 if key not in dict2 } added = { key: di...
def extract_by_index(a_list, indices): """ Creates a list that consists of the elements at the given indices of the given list. :param a_list: The list to get elements from. :param indices: The indices to use to source elements. :return: The selected list. """ retur...
def g(x, a, b, c): """ Pickleable test function. """ return a + b * x + c * x ** 2
def _hard_light(a, b): """ :type a: ImageMath._Operand :type b: ImageMath._Operand :rtype: ImageMath._Operand """ _cl = 2 * a * b / 255 _ch = 2.0 * (a + b - a * b / 255.0) - 255.0 return _cl * (b < 128) + _ch * (b >= 128)
def first(seq): """ return the first element in a python sequence for graphs, use graph.value instead """ for result in seq: return result return None
def inv_transform(x,a,b): """Transforms points from the interval [a,b] to the interval [-1,1]. Parameters ---------- x : numpy array The points to be tranformed. a : float or numpy array The lower bound on the interval. Float if one-dimensional, numpy array if multi-dimensional ...
def int_to_string( x ): """Convert integer x into a string of bytes, as per X9.62.""" assert x >= 0 if x == 0: return bytearray([0]) result = bytearray() while x > 0: q, r = divmod( x, 256 ) result = bytearray([r]) + result x = q return result
def _subnet_max_func(x, r_fn, shortcut_weight=0.6): """The subnetwork maximizing function of the modified ResNet model.""" blocks_per_group = (3, 4, 23, 3) res_branch_subnetwork_x = r_fn(r_fn(r_fn(x))) for i in range(4): for j in range(blocks_per_group[i]): res_x = r_fn(r_fn(r_fn(x))) short...
def division_euclidienne_dichotomique(a, b): """Renvoie le quotient q et le reste r de la division euclidienne de a par b""" n = 0 while 2 ** n * b <= a: n += 1 inf = 2 ** (n - 1) sup = 2 ** n for i in range(1, n): mid = (inf + sup) / 2 if mid * b <= a: inf =...
def IsRotation(a,b): """ take strings a and b as an input and see if they are rotations of one another, returns boolean """ rotation = 0 rotate_max = len(a) while rotation < rotate_max: rotation += 1 if a == b: return True a = a[-1] + a[:-1] return False
def subtract_and_increment(a, b): """" Return a minus b, plus 1 """ c = a - b + 1 return c
def mass_diff(mz1, mz2, mode_is_da): """ Calculate the mass difference(s). Parameters ---------- mz1 First m/z value(s). mz2 Second m/z value(s). mode_is_da : bool Mass difference in Dalton (True) or in ppm (False). Returns ------- The mass differenc...
def split_into_formatters(compound): """Split a possibly compound format string into segments. >>> split_into_formatters('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] """ merged_segs = [] # These occur only as prefixes, so they can always be merged: me...
def is_same_width(w1, w2): """Return true if is the same width of images else return false""" if w1 == w2: return True return False
def init_crop_region(image_height, image_width): """Defines the default crop region. The function provides the initial crop region (pads the full image from both sides to make it a square image) when the algorithm cannot reliably determine the crop region from the previous frame. Args: ima...
def build_delete(table: str, where: list): """ Build a delete request. Parameters ---------- table : str Table where query will be directed. where: iterable The list of conditions to constrain the query. Returns ------- str Built query string. """ r...
def _parse_speed(speed_in_knots): """Convert speed in knots to km/h""" return float(speed_in_knots) * 1.852
def add_vector(vector1, vector2): """ Adds vector1 and vector2 component-wise """ summed = [x for x in vector1] for i in range(len(vector1)): summed[i] += vector2[i] return summed
def check_iters_equal_on_indices(iter1, iter2, iter_indices): """ Checks if any list's items are not equal with respect to given indices. """ return all([iter1[index] == iter2[index] for index in iter_indices])
def lp100k_from_mpg(mpg): """Convert miles per gallon to liters per 100 kilometers and return the converted value. Parameter mpg: A value in miles per gallon Return: The converted value in liters per 100km. """ lp100k = 235.215 / mpg return lp100k
def midi_pitch_to_f0(midi_pitch): """ Return a frequency given a midi pitch (in 0-127) """ return 440 * 2**((midi_pitch - 69) / 12)
def getAddress(address): """ Method returns the formed address :param address: raw address :return: formed address """ message = 'Address: ' + address return message
def clean_list(a_list): """ Apparently the only way to drop all of the unwanted characters """ # I don't want these in my title undesirables = [',', '``', '`', ' `', '` ', "'", '"', '""', "''", '/', '{', '}', '(', ')', '[', ']'] new_list = [x for x in a_list if x not in undesirables] return ...
def probabilities_to_weights(*args): """Scale a sequence of probabilities into integer weights. Locust's `@task` decorator takes integer weight rather than probability. """ # Rescale args such that the lowest arg becomes 1, then multiply by # 10 before casting to int, such that the first decimal wo...
def transpose(data): """ Transpose the data. In case the data are in rows, not columns """ return [*zip(*data)]
def box_normalized_to_raw(box, image_width, image_height): """Reformat box as needed for mm lib. :param list box: [x1, y1, x2, y2] :param int image_width: width of the total image in px :param int image_height: height of the total image in px :return: box as needed for the mm lib """ x1, y1...
def is_set(obj): """Helper method to see if the object is a Python set. >>> is_set(set()) True """ return type(obj) is set
def leaf_list(root): """ >>> left1 = BTNode('fun') >>> right = BTNode('is', left1) >>> left = BTNode('test') >>> tree = BTNode('this', left, right) >>> leaf_list(tree) """ result = [] if root is None: return result elif root.left is None and root.right is None: r...
def _set_alt_port(app_definition, alt_port): """Set the alt port on the provided app definition. This works for both Dockerised and non-Dockerised applications. """ app_definition['labels']['HAPROXY_DEPLOYMENT_ALT_PORT'] = str(alt_port) return app_definition
def filter_languages(languages, hints=None): """Filter languages. """ return languages.intersection(hints) if hints else languages
def balanced_transitions(N): """ Recursively creates a balanced binary tree with N leaves using shift reduce transitions. """ if N == 3: return [0, 0, 1, 0, 1] elif N == 2: return [0, 0, 1] elif N == 1: return [0] else: ...
def bizect(l, steps="a"): """ given a list, select the a/b n-th group plus the last element >>> l = list(range(10)) >>> bizect(l) [0, 1, 2, 3, 4, 9] >>> b...
def is_create(line): """ Returns true if the line begins a SQL create table statement. """ return line.startswith(b'CREATE TABLE') or False
def isIterator(obj): """ Returns True if obj is an iterator object, that is, has an __iter__ method has a __next__ method .__iter__ is callable and returns obj Otherwise returns False """ if (hasattr(obj, "__iter__") and hasattr(obj, "__next__") and callable(obj.__iter...
def moving_permutation(length, origin, goal): """ Returns a permutation moving the element at position origin to the position goal (in the format requested by torch.Tensor.permute) Parameters ---------- length : int length of the sequence to be permuted origin : int position...
def getClues(guess, secretNum): """Returns a string with the pico, fermi, bagels clues for a guess and a secret number pair.""" if guess == secretNum: return 'You got it!' clues = [] for i in range(len(guess)): if guess[i] == secretNum[i]: clues.append('Fermi') ...
def tupleize(dim, ndim): """Convert one or more dims to a tuple of non-negative indices""" if not isinstance(dim, tuple): if hasattr(dim, '__iter__'): dim = tuple(dim) else: dim = (dim,) return tuple((i if i >=0 else ndim+i) for i in dim)
def build_part_check(part, build_parts): """ check if only specific parts were specified to be build when parsing if the list build_parts is empty, then all parts will be parsed """ if not build_parts: return True return bool(part in build_parts)
def factorial(n): """Return the `n!`.""" acc = 1 for i in range(2, n + 1): acc *= i return acc
def attsiz(att: str) -> int: """ Helper function to return attribute size in bytes. :param str: attribute type e.g. 'U002' :return: size of attribute in bytes :rtype: int """ return int(att[1:4])
def plugin_init(config): """ Initialise the plugin. Args: config: JSON configuration document for the South plugin configuration category Returns: handle: JSON object to be used in future calls to the plugin Raises: """ handle = config return handle
def get_parameter_for_suite(suite_name): """Return a parameter for which suite to run the tests for. Args: suite_name: str. The suite name whose tests should be run. If the value is `full`, all tests will run. Returns: list(str). A list of command line parameters for the suite....
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() ...
def create_gitlab_header_anchor(header_title): """ Returns a Gitlab Markdown anchor to the header. """ return '[{}](#{})'.format(header_title, header_title.lower().strip().replace(' ', '-'))
def removeprefix(string: str, prefix: str) -> str: """ Removes a prefix from a given string if it exists. """ if string.startswith(prefix): return string[len(prefix):] return string[:]
def which(program): """ Search for the presence of an executable Found in: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python """ import os def is_exe(filep): return os.path.isfile(filep) and os.access(filep, os.X_OK) fpath, fname = os.path.split(program)...
def boolToString(value): """ converts a boolean value to a human readable string value @param value: boolean, the value to convert @return: A string of "Yes" or "No" """ if(value): return "Yes" else: return "No"
def pytest_funcarg__input_data(request): """Key or IV input is here""" data = 0x0 return data
def get_object_adjacency(cur,obj): """ Returns the adjacency of the object number Parameters ---------- cur : MySQLdb cursor obj : int Object number """ sql = ("select pre from adjacency2 " "where postObj = %s " "union " "select post from adjacen...
def isspace(text): """ Checks if there are only whitespace characters in ``text`` and there is at least one character. Whitespace characters are those characters defined in the Unicode character database as "Other" or "Separator". :param text: The string to check :type text: ``str``...
def hex2dec(s): """return the integer value of a hexadecimal string s""" return int(s, 16)
def stripStr(obj): """ # strip whatever and always return string """ if obj is None: return '' return str(obj).strip()
def colour_linear_interpolation(col_a, col_b, t): """ Linearly interpolates between two colours. """ col = tuple([a + (b - a) * t for a, b in zip(col_a, col_b)]) return col
def getkw(kw, name, default=None, nodefault=False, remove=True): """ convenience function for getting certain kwargs out of function """ if name in kw: ret = kw[name] if remove: del kw[name] else: if nodefault: raise Exception("kwarg {} must be specified (no d...
def number_of_friends(user): """how many friends does _user_ have?""" return len(user["friends"])
def get_iou(bb1, bb2): """ Gets the Intersection Over Area, aka how much they cross over Assumption 1: Each box is a dictionary with the following {"x1":top left top corner x coord,"y1": top left top corner y coord,"x2": bottom right corner x coord,"y2":bottomr right corner y coord} ...
def get_int(byte_array, signed=True): """ Gets the specified integer from its byte array. This should be used by this module alone, as it works with big endian. :param byte_array: the byte array representing th integer. :param signed: whether the number is signed or not. :return: the integer re...
def make_list_unc_val_string(id, luv): """ make_list_unc_val_string(id, luv) Make a formatted string from an ID string and a list of uncertain values. Input ----- id A number or a string that will be output as a string. luv A list of DTSA-II UncertainValue2 items. These will be printed as comma-delimited p...
def integers(value): """ :param value: input string :returns: non-empty list of integers >>> integers('1, 2') [1, 2] >>> integers(' ') Traceback (most recent call last): ... ValueError: Not a list of integers: ' ' """ if '.' in value: raise ValueError('There are d...
def _get_proper_torsion_canonical_order(i0, i1, i2, i3): """Create a unique order of the 4 atom indices of a proper torsion. The atom indices of a proper torsion are reordered so that the first atom is the smallest index. Parameters ---------- i0, i1, i2, i3 : int Atom indices of the p...
def test_is_palindrome(l1, l2): """Takes original list and reversed list as args. Returns False if any value does not match counterpart, True otherwise.""" # print(f'reversed list: {rev_list}') for i in range(int(len(l1) // 2) + 1): if l1[i] != l2[i]: # checks to see if a number matches...
def normalize(data, olow, ohigh, nlow, nhigh): """ olow old low ohigh old high nlow new low nhigh new hight """ percent = (data - olow) / (ohigh - olow) return percent * (nhigh - nlow) + nlow
def unique_key(old_key: str, collection: dict) -> str: """Create a old_key which is guaranteed to be unique in the collection""" counter = 2 new_key = old_key while new_key in collection: new_key = f"{old_key}{counter}" counter += 1 return new_key
def filter_empty_cases(element): """ Remove elements contained empty keys Receives a tuple ('CE-2015-12', {'chuvas': [7.6], 'dengue': [29.0]}) Returns the same tuple without empty keys """ key, data = element if all([ data['chuvas'], data['dengue'] ]): return True...
def _combine(lhs, rhs): """ Combines a list, tuple, or dict, with another list or tuple or dict Build mode struct attributes are tuples by default, but many consumers use the 'create_build_mode' function to initialize them to lists, or even dictionaries. When combining build modes using the 'extend...
def look_for_pathway_and_anat(paths): """ Given a set of paths, count the number of distinct labels, where pathways, and where anatomy occur :param paths: a list of paths (from node_name_and_label_in_path) :return: a list of number of distinct labels in the paths, a list of logicals indicating if that path has a pa...
def from_h(s): """Returns list of bytes corresponding to hex string `s`""" s = s.replace(' ', '') assert len(s) % 2 == 0 return [int(s[2 * i: 2 * i + 2], 16) for i in range(len(s) // 2)]
def tir(*args): """ The items of `*args` are rounded, converted to `int` and combined into a tuple. The primary use-case of this function is to pass point coordinates to certain OpenCV functions. >>> tir(1.24, -1.87) (1, -2) """ if (len(args) == 1) and (len(args[0]) == 2): ...
def get_D_runs(ex_stat): """Get D runs.""" d_inds = [n for n, v in enumerate(ex_stat) if v == "D" or v == "mD"] if len(d_inds) <= 1: # nothing we can do return [] result = [] curr_list = [d_inds[0], ] for elem in d_inds[1:]: prev_elem = curr_list[-1] if prev_elem ...
def scenario_to_distribution(scenario): """Takes a scenario, mapping numbers to triplets, and re-shapes the data. Returns an array of 4 arrays: [[x values], [min y values], [max y values], [average y values]].""" x_values = [] for k in scenario: x_values.append(k) x_values.sort() min...
def is_running(status, **_): """For when= function to test if a pod is running.""" return status.get('phase') == 'Running'
def is_container(node): """ Determine if an ASDF tree node is an instance of a "container" type (i.e., value may contain child nodes). Parameters ---------- node : object an ASDF tree node Returns ------- bool True if node is a container, False otherwise """ ...
def _convert_attribute_list_to_python_syntax_string(attr_list): """This converts the given attribute list to Python syntax. For example, calling this function with ['obj1', 'attr1', 7, 'attr2'] will output obj1.attr1[7].attr2. :param attr_list: the requested attributes/indices list. :return: string...
def read_region(region): """Return convenient region representation.""" chrom, grange = region.split(":") start = int(grange.split("-")[0]) end = int(grange.split("-")[1]) return {"chrom": chrom, "start": start, "end": end}
def humantime(ms): # Docstring """ Converts timespan in milliseconds to a humanly readable string. -------------- ms : int or float Time in milliseconds -------------- Examples : >>> humantime(194159) '3 min, 14 sec, 159 ms' """ time_dict = {'ms' : ...
def gather_stream_parameters(streams): """ Helper function for gathering the stream parameters into a datastructure and sticking the stream tag into the trace stats dictionaries. Args: streams (list): list of StationStream objects. Returns: dict. Dictionary of the strea...
def part1(firewall): """ >>> part1(read_input()) 2264 """ severity = sum(depth * range for (depth, range) in firewall.items() if depth % (range * 2 - 2) == 0) return severity
def getForwardreadpos(targetPos,queryStart,hitStart,hitStrand): """ This takes a nucleotide position which relates to the database hit (i.e the V region gene from IMGT) and identifies its position in the query sequence. It requires a target position (i.e. the first base of start codon, where the first b...
def get_msg(feat, mpnn, train_folder): """ Create a message telling the user what kind of model we're training. Args: feat (bool): whether this model is being trained with external features mpnn (bool): whether this model is being trained with an mpnn (vs. just with external features) ...
def as_int(num): """ Convert ``num`` to int if ``num`` is not an int and this would not lead to loss of information, e.g. when ``num`` is an int stored as a float type. """ if isinstance(num, str): num = float(num) if isinstance(num, float): n = int(num) if n == num: ...
def run_concat_lists(job, *args): """ Toil job to join all the given lists and return the merged list. """ concat = [] for input_list in args: concat += input_list return concat
def normalise_point(datapoint, mean, std): """ normalise a datapoint to zero mean and unit variance. :param datapoint: value as a float :param mean: mean of data vector x :param std: standard deviation of data vector x :return: normalised datapoint (float) """ return (datapoint - mean)/s...
def dlist2string(dlis): """Converts a list of dictionaries into a string sep by |""" st = '' for p, v, in dlis: s = '' s += (p + ' ' + v) st += (s + ' | ') return st
def cpl(mean, sigma, LSL): """Process capability index Cpl.""" return (mean - LSL) / (3 * sigma)
def _fromBinary( s ): """ s is a string of 0's and 1's """ if s == '': return 0 lowbit = ord(s[-1]) - ord('0') return lowbit + 2*_fromBinary( s[:-1] )
def get_host_from_metadata(metadata, name): """ Get host definition from job metadata base on name. Returns: (host, domain) """ domains = metadata.get("domains", []) for domain in domains: for host in domain.get("hosts", []): if host["name"] == name: retu...
def strip_prefix(prefix, string): """Strip prefix from a string if it exists. :param prefix: The prefix to strip. :param string: The string to process. """ if string.startswith(prefix): return string[len(prefix):] return string
def booleanize(value): """ Convert a string to a boolean. :raises: ValueError if unable to convert. :param str value: String to convert. :return: True if value in lowercase matches "true" or "yes"; False if value in lowercase matches "false"or "no". :rtype: bool """ valuemap = { ...
def make_IOB_tag(ttag, ttype): """Inverse of parse_IOB_tag.""" if ttype is None: return ttag else: return ttag+'-'+ttype
def latest(scores: list) -> int: """get latest score. Args: scores (list): Returns: int: """ return scores[-1]
def flatten_dict(a_dict, parent_keys=None, current_parent_key=None): """Given a dict as input, return a version of the dict where the keys are no longer nested, and instead flattened. EG: >>> flatten_dict({"a": {"b": 1}}) {"a.b": 1} NB: The kwargs are only for internal use of the functi...
def time_formatter(milliseconds: int) -> str: """Inputs time in milliseconds, to get beautified time, as string""" seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ...
def rows2cols(iterable): """takes an iterable of row sequences and returns a list of lists of columnar data.""" #checks widths = (len(row) for row in iterable) try: width = next(widths) except StopIteration as e: raise ValueError('function received zero length input') if not all(w ==...
def show_square(number): """View that shows the square of the number passed by URL""" return f"Square of {str(number)} is: {(number * number)}"