content
stringlengths
42
6.51k
def quasi_criterion(indifference_threshold, distance): """ implements quasi criterion """ if distance > indifference_threshold: return 1 else: return 0
def get_gff_ends(gff_dict, contig): """ Get gff ends. gff_dict is composed of the line and the fl of the gff file Work in the same way as get_fast_fasta Yield the gff stop according the frame Then return a dictionary composed of the orfs by frame """ gff_ends = {'+': [], '-': []} li...
def convert_coordinates(hpos, vpos, width, height, x_res, y_res): """ x = (coordinate['xResolution']/254.0) * coordinate['hpos'] y = (coordinate['yResolution']/254.0) * coordinate['vpos'] w = (coordinate['xResolution']/254.0) * coordinate['width'] h = (coordinate['yResolution']/254.0) * coo...
def _transfer_style(source, target): """Copy over class names from source to target for all special classes. Used if a node is highlighted and merged with another node.""" clazzes = source.get("class", "") special_classes = {"dashed", "active"} if "class" not in target: target["class"] =...
def _path_from_name(name, type): """ Expand a 'design/foo' style name to its full path as a list of segments. >>> _path_from_name("_design/test", '_view') ['_design', 'test'] >>> _path_from_name("design/test", '_view') ['_design', 'design', '_view', 'test'] """ if name.startswith('_...
def euler_pentagonal_num(n): """ Returns n'th euler pentagonal number (1-indexed) Parameters ---------- n : int denotes positive integer return : int returns n'th euler pentagonal number """ if(n!=int(n) or n<1): raise ValueError( "n must be positive...
def merge_sorted_cookie_lists(listA, listB): """Takes in two order lists of cookies and merges them together""" if type(listA) != list or type(listB) != list: raise TypeError( "Both arguments for merge_sorted_cookie_lists must be of type list.") final_list = [] listA_length = len(li...
def normalize_mapping_line(mapping_line, previous_source_column=0): """ Often times the position will remain stable, such that the naive process will end up with many redundant values; this function will iterate through the line and remove all extra values. """ if not mapping_line: retu...
def filter_frame(frame, predicates, select=None): """Filter frame using given predicates. """ f = {} columns = select or frame.keys() for col in columns: f[col] = [v for p,v in zip(predicates,frame[col]) if p] return f
def convert_params_to_inputs(params): """ Collates all the inputs once the user has hit Run. Args: params: The set of parameters specified by the user Returns: Unprocessed inputs for use by the inputs module """ # replacing iteritems with items for py3 return {key: param['v...
def make_filename(params, run): """Generate a filename based on params and run. params: (net, seed, freq, weight)""" nets = ['net_tuneddynamics', 'net_ppdynamicsoff'] return(f"time-stamps_{nets[int(params[0])]}.TunedNetwork_{params[2]}_{str(run).zfill(3)}_02000_00060" f"_00024_00...
def node_value(node, input_values, neuron_outputs): # PROVIDED BY THE STAFF """ Given * a node (as an input or as a neuron), * a dictionary mapping input names to their values, and * a dictionary mapping neuron names to their outputs returns the output value of the node. This function d...
def run_if_true(function, boolean, data): """ Run the given function if the boolean is true. Else return the data. """ if boolean: return function(data) return data
def clean_dist(A): """ Clean a distribution to accelerate further computation (drop element of the support with proba less than 2^-300) :param A: input law (dictionnary) """ B = {} for (x, y) in A.items(): if y>2**(-300): B[x] = y return B
def navigation(request): """Fetches data required to render navigation menu. The main menu contains the list of user categories to choose. Here is the query to fetch them. """ context = {} if hasattr(request, "user_categories"): context.update( { "user_categ...
def _dtype_to_str(dtype): """Cast dtype to string, such as "float32", or "float64".""" if isinstance(dtype, str): return dtype elif hasattr(dtype, "name"): # works for numpy and cupy return dtype.name elif "torch." in str(dtype): # works for torch return str(dtype)[6:] elif...
def bbox_center(bbox, fmt="xyxy"): """ fmt: xyxy or xywh ------- return: x_ctr, y_ctr """ if fmt == "xyxy": x1, y1, x2, y2 = bbox return 0.5 * (x1 + x2), 0.5 * (y1 + y2) elif fmt == "xywh": x1, y1, w, h = bbox return x1 + 0.5 * (w - 1), y1 + 0.5 * (h -...
def is_signed_int(num_str): """ Args: num_str (str): The string that is checked to see if it represents a number Returns: bool Examples: >>> is_signed_int("25.6") False >>> is_signed_int("-25.6") False >>> is_signed_int("0") True ...
def _str_list(l): """Return a string representing list of strings.""" return " ".join(sorted(l, key=str.lower)) if l else "[none]"
def isArgumentlessJavaOption(line): """ Determine whether a given line contains a command line option that does not take arguments. Parameters ---------- line : str A line of the build output Returns ------- bool True if the line contains an option that doesn't take...
def normalize(cv): """ :param cv: A map containing integer values :return: A copy of that map with same keys and float values, normalized """ pct = {} cvsum = sum(cv.values()) for k, v in cv.items(): if cvsum == 0: x = 0 else: x = v * 1.0 / cvsum ...
def get_data_byte_at_index(data, byte_index): """ Get the data at a given byte position. Given a data value that may require more than 8 bits to represent in unsigned binary, return the value of the data in the byte at the given index. If the data doesn't extend into the byte index requested, ...
def forward_propagation(x, theta): """ Implement the Linear forward propagation (compute J -- J(theta) = theta * x) Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: J -- the value of function J, computed using the formula J(theta) = the...
def suffixed_file_name(file_path, suffix_string): """ Returns file path with appended string (preserving file type) :param file_path: (string) either relative or absolute path of file :param suffix_string: (string) string to append to the original file name :return: (string) suffixed file path ex...
def snake_keys_to_camel_case(dictionary): """ Translate a dictionary containing snake_case keys into dictionary with camelCase keys as required for decision dicts. """ output = {} for original_key in dictionary.keys(): components = original_key.split('_') translated_key = compone...
def sign(x: float) -> int: """Returns 1 if x is positive, 0 if x is 0, and -1 otherwise""" retVal = 0 if x > 0: retVal = 1 elif x < 0: retVal = -1 return retVal
def setColor(grid, x, y, c): """ Takes a grid and changes one color """ grid = grid[:] grid[x][y] = c return grid
def indent_str(indent_number: int) -> str: """Given a number of indentation, returns the string to be used as prefix for indentation""" return "\t" * indent_number
def enhance_task_data_from_results(task_data, results): """Return the task data generated from JSON input data.""" # Index task_data by target indexed_task_data = {row['target']: row for row in task_data} enhanced_task_data = [] for row in results: info = row['info'] if not info: ...
def get_page_nav(current_page, result_count, page_limit): """ page-nav model('cp': current_page, '<': prev-page, '>': next-page): < cp-2, cp-1, cp, cp+1, cp+2 > :param current_page: :param result_count: all the result count :param page_limit: :return: """ pages = {'cp-2': 0, ...
def dot22(X, Y): """matrix multiplication, 2 by 2 """ a, b, c, d = X e, f, g, h = Y return a * e + b * g, a * f + b * h \ ,c * e + d * g, c * f + d * h
def transpose(matrix): """ Returns `transposed_matrix` from a given matrix by appending its contents to an empty list with a switched rows and columns. Parameters ---------- matrix : list The given matrix. Returns ------- transposed_matrix : list The transposed...
def update_cflags(cflags): """ NOT_RPYTHON """ # force the right target arch for s390x for cflag in cflags: if cflag.startswith('-march='): break else: # the default cpu architecture is zEC12 # one can directly specifying -march=... if needed revision = 'zEC12...
def last_word(s): """Returns the last word in `s`. Parameters ---------- s : string Returns ------- word : string The last word in `s`. """ # Initialisations s_list = list(s) for i in range(len(s_list)-1, 0, -1): if s_list[i] == " ": ...
def meta_diff(old, new): """ Diffs the two provided Meta definitions (dicts). """ # First, diff unique_together old_unique_together = eval(old.get('unique_together', "[]")) new_unique_together = eval(new.get('unique_together', "[]")) added_uniques = set() removed_uniques = set(...
def get_bias(sdv, edv): """ Get trend line bias Args: Double: Start date value Double: End date value Returns: String: Bias """ ret = "Neutral" if sdv is not None and edv is not None: if sdv > edv: ret = "Negative" if sdv < edv: ...
def get_select_fields(selects, base_ht): """ Generic function that takes in a select config and base_ht and generates a select dict that is generated from traversing the base_ht and extracting the right annotation. If '#' is included at the end of a select field, the appropriate biallelic position w...
def int_to_lb(loadbalance): """Returns the string representation in VPP of a given load-balance strategy, or "" if 'lb' is not a valid int. See src/vnet/bonding/bond.api and schema.yaml for valid pairs, although bond.api defined more than we use in vppcfg.""" ret = { 0: "l2", 1: "l...
def dampening(eps, rho): """Dampening factor for entropy+unbalanced OT with KL penalization of the marginals.""" return 1 if rho is None else 1 / (1 + eps / rho)
def colums_widths(myTable): """Calculates the widths of the table's columns . The table we are talking about will be filled with information taken from our list 'myTable' Inputs : myTable -- nested list : list of lists of strings Outputs : widths -- list of table's widths computed based on ...
def indent(n, s="-"): """ :param n: number >= 0 :param s: string :return: string containing a copy of n times the string s """ return s.join("" for _ in range(n))
def find_max(memory): """ :param memory: the list :return: the index of the first maximum value """ import operator index, value = max(enumerate(memory), key=operator.itemgetter(1)) return index
def ranges_overlap(x1, x2, y1, y2): """Returns true if the ranges `[x1, x2]` and `[y1, y2]` overlap, where `x1 <= x2` and `y1 <= y2`. Raises: AssertionError : If `x1 > x2` or `y1 > y2`. """ assert x1 <= x2 assert y1 <= y2 return x1 <= y2 and y1 <= x2
def return_one_value(number_1, number_2): """ :param number_1: int, double :param number_2: int, double :return: sum of 2 increased number """ number_1 += 10 print ('number 1 is increased by 10') number_2 += 20 print ('number 2 is increased by 20') return number_1 + number_2
def assert_time_of_flight_is_positive(tof): """ Checks if time of flight is positive. Parameters ---------- tof: float Time of flight. """ if tof <= 0: raise ValueError("Time of flight must be positive!") else: return True
def obtain_reverse_codes(mapped, dst): """ Given the list of desired dst codes and an extensive map src -> dst, obtain the list of src codes :param mapped: Correspondence between src codes and dst codes [{"o", "to": [{"d", "e"}]}] :param dst: Iterable of destination codes :return: List of origi...
def clean(text: str) -> str: """Clean a paragraph of text; removing extra whitespace.""" # text = text.strip() # lines = [line for line in text.split('\n') if line] # return " ".join(lines) return " ".join(text.split())
def navigate_to_history_entry(entryId: int) -> dict: """Navigates current page to the given history entry. Parameters ---------- entryId: int Unique id of the entry to navigate to. """ return {"method": "Page.navigateToHistoryEntry", "params": {"entryId": entryId}}
def odd_occurrence_parity_set(arr): """ A similar implementation to the XOR idea above, but more naive. As we iterate over the passed list, a working set keeps track of the numbers that have occurred an odd number of times. At the end, the set will only contain one number. Though th...
def uniform_expval(lower, upper): """ Expected value of uniform distribution. """ return (upper - lower) / 2.
def safediv(*args): """ .. function:: safediv(int, int, int) -> int Returns the first argument, when the division of the two subsequent numbers includes zero in denominator (i.e. in third argument) Examples: >>> sql("select safeDiv(1,5,0)") safeDiv(1,5,0) -------------- 1 """...
def decode(data, type_=None): """ Decodes binary data to its original format """ if type_ is not None: if type_ == int: return int.from_bytes(data, byteorder='little')
def sum_key(value, key): """Sums up the numbers in a 'column' in a list of dictionaries or objects. Positional arguments: value -- list of dictionaries or objects to iterate through. Returns: Sum of the values. """ values = [r.get(key, 0) if hasattr(r, 'get') else getattr(r, key, 0) for r ...
def getfreqs(stream): """ This function Takes a stream as an input. it gets the number of occurrences of each symbol in that stream, store it in a Dictionary containing every symbol in the stream . Arguments: stream {list} -- [the input stream we want to compress] Returns: ...
def string_list(argument): """ This function ... :param argument: :return: """ return argument.split(",")
def value(iterable, key=None, position=1): """Generic value getter. Returns containing value.""" if key is None: if hasattr(iterable, '__iter__'): return iterable[position] else: return iterable else: return iterable[key]
def is_subset(iterable, iterable_superset): """ Helper function for gen_symbols_samples below. Checks to see if every item in iterable is in iterable_superset. """ for item in iterable: if item not in iterable_superset: return False return True
def ethiopic_date(year, month, day): """Return the Ethiopic date data structure.""" return [year, month, day]
def create_blocks(message, download_link=''): """ Create blocks for the main message, a divider, and context that links to Shipyard. If a download link is provided, creates a button block to immediately start that download. For more information: https://api.slack.com/block-kit/building """ mess...
def preOrderTestTreeNode(root): """ """ lst = [] if root is None: return lst lst.append(root.data) if root.left is not None: lst.extend(preOrderTestTreeNode(root.left)) if root.right is not None: lst.extend(preOrderTestTreeNode(root.right)) return lst
def gcd(a, b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). Copied from the Python2.6 source Copyright (c) 2001-2011 Python Software Foundation; All Rights Reserved ...
def isiterable(x): """Determines if an object is iterable and not a string.""" return hasattr(x, "__iter__") and not hasattr(x, "upper")
def A007089(n: int) -> int: """Numbers in base 3.""" if n == 0: return 0 digits: list = [] while n: n, r = divmod(n, 3) digits += str(r) o = "".join(reversed(digits)) return int(o)
def filters_logical_and(f1, f2, f3): """ given three filters, returns the logical and of these filters in the order: f1 AND f2 AND f3. Parameters: ----------- f[1/2/3]: `dict` filter expression to be combined. Returns...
def clean_line(line: str) -> str: """Clean line.""" return line.replace("\n", "").replace("<", "").replace(">", "").replace( "#+", "")
def _is_winning_combination(board, combination, player): """ Checks if all 3 positions in given combination are occupied by given player. :param board: Game board. :param combination: Tuple containing three position elements. Example: ((0,0), (0,1), (0,2)) Returns True of a...
def rem(x, a): """ x: a non-negative integer argument a: a positive integer argument returns: integer, the remainder when x is divided by a. """ if x == a: return 0 elif x < a: return x else: rem(x-a, a)
def gcd(m, n): """A method to determine the greatest common denominator of m and n Parameters: m (int): an integer n (int): another integer Returns: n (int): the gcd of parameters m and n """ while m % n != 0: oldm = m oldn = n m = oldn n = o...
def header(fn): """ Custom header for isomiR-SEA importer. Args: *fn (str)*: file name with isomiR-SEA GFF output Returns: *(str)*: isomiR-SEA header string. """ h = "" return h
def min_distance(tuple1, tuple2): """ helper function to determine which tuple distance is smaller and returns that tuple tuples have form (distance, idx1, idx2) """ if tuple1[0] < tuple2[0]: return tuple1 else: return tuple2
def unkeyed(v): """Convert the specified `v` from DynamoDB's dict keyed by the type to a primitive Python type.""" for type_name in v: value = v[type_name] if type_name == "BOOL": return value if type_name == "S": return value elif type_name == "N": ...
def some(predicate, seq): """If some element x of seq satisfies predicate(x), return predicate(x). Ex: some(callable, [min, 3]) ==> 1; some(callable, [2, 3]) ==> 0""" for x in seq: px = predicate(x) if px: return px return False
def fact(number): """ Factorial function """ if number < 0: raise ValueError('Factorial is defined only for non-negative numbers') if number == 0: return 1 return number * fact(number - 1)
def is_latinx(ethnicities): """ Checks if Latinx and not Black was provided by the developer in their list of race-ethnicities """ return 'Hispanic or Latino/Latina' in ethnicities and not 'Black or of African descent' in ethnicities
def formatter(data, headers): """ format a message sent with slack api endpoints""" text = data["attachments"][0]["text"] data["body"] = f"{text}" return data
def pie_percent(n): """ :param n: int :return: int precodition: n >0 """ return int(100 / n )
def get_color_map_list(num_classes): """ Returns the color map for visualizing the segmentation mask, which can support arbitrary number of classes. Args: num_classes: Number of classes Returns: The color map """ color_map = num_classes * [0, 0, 0] for i in range(0, num_c...
def validate_file_and_rtn_filter_list(filename): """ Function to validate file exists and generate a list of keywords or userids""" if filename is None: return [] with open(filename, "r") as file: kw_list = file.read() kw_list = kw_list.strip().split() if kw_list != []: ...
def find_index_closing_parenthesis(string: str): """Find the index of the closing parenthesis""" assert string.startswith("("), "string has to start with '('" stack = [] for index, letter in enumerate(string): if letter == "(": stack.append(letter) elif letter == ")": ...
def prepend_zeros(length, string): """ Prepend zeros to the string until the desired length is reached :param length: the length that the string should have :param string: the string that we should appends 0's to :return: A string with zeros appended """ return "{}{}".format("0" * (length - ...
def vhdl_register_address(name, address_offset): """ Return a string with a VHDL constant declaration of the supplied register. """ return "constant {} : integer := {};\n".format(name, address_offset)
def is_shutout(goalie_dict, goalies_in_game): """ Checks whether current goalie game can be considered a shutout. """ # only goalies that played and didn't concede any goals can have a shutout if (goalie_dict['games_played'] and not goalie_dict['goals_against']): # if more than two goalies (...
def isprime(d: int) -> int: """ returns whether the given digit is prime or not >>> isprime(1) 0 >>> isprime(17) 1 >>> isprime(10000) 0 """ if d == 1: return 0 i = 2 while i * i <= d: if d % i == 0: return 0 i = i + 1 ...
def combine_code(selfcode, to_add): """ Combines two verb codes, part of the verb interaction framework Parameters ---------- selfcode,to_add: ints Upper and lower verb codes, respectively Returns ------- combined value """ #print(selfcode) #print(to_...
def get_url_stripped(uri): """ :param uri: <myuri> or uri :return: myuri """ uri_stripped = uri.strip() if uri_stripped[0] == "<": uri_stripped = uri_stripped[1:] if uri_stripped[-1] == ">": uri_stripped = uri_stripped[:-1] return uri_stripped
def one_is_none(*args) -> bool: """ Return True if exactly one arg is None. """ return sum([arg is None for arg in args]) == 1
def feed(attribute, kwargs, dictionary, tab='\t'): """ Args: attribute (str): Attribute to be operated. kwargs (dict): generic parameters. dictionary (dict): default parameters dictionary. tab (str): '\t' or '\t\t', depend on orders of attribute. Return: (str) ""...
def separate_substructures(tokenized_commands): """Returns a list of SVG substructures.""" # every moveTo command starts a new substructure # an SVG substructure is a subpath that closes on itself # such as the outter and the inner edge of the character `o` substructures = [] curr = [] for c...
def find_in_reference_list(reference_list, source_name): """Check if it is already in reference list""" for reference in reference_list: if reference['sname'] == source_name: return True return False
def isAnagramB(s, t): """ :type s: str :type t: str :rtype: bool """ s=sorted(s) t=sorted(t) return s == t
def clamp(value, min_, max_): """ Returns the value clamped between a maximum and a minumum """ value = value if value > min_ else min_ return value if value < max_ else max_
def str_ranges_2_list(nputstr=""): """Return list of numbers given a string of ranges http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html """ selection = set() invalid = set() # tokens are comma separated values tokens = [x.strip() for x in nputstr.split(',')]...
def is_prime(number): """ This function will check if the number is prime or not returns True if prime false otherwise """ for index in range(2, number//2): if number%index == 0: return False return True
def offset_flat_index(idx, offset): """Return an index into a flat array with the given offset applied. All indices are assumed to have been converted to explicit form, so no negative indices, slices with ':', or tuples are allowed. """ if isinstance(idx, slice): return slice(idx.st...
def get_iterable(x): """Ensure x is iterable""" from collections.abc import Iterable if isinstance(x, Iterable): return x else: return [x]
def _from_serialized_headers(headers): """ httpx accepts headers as list of tuples of header key and value. """ header_list = [] for key, values in headers.items(): for v in values: header_list.append((key, v)) return header_list
def get_permutations(sequence): """ Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. You MUST use recursion for this part. Non-recursive solutions will not be accepted. Returns: a list of all permutations...
def calculate_trapezoid_area(top_base, bottom_base, height): """ :param top_base: :param bottom_base: :param height: :return: """ # result = (top_base + bottom_base) * height / 2 # return result return (top_base + bottom_base) * height / 2
def selection_sort(list): """This function takes a list as input and sorts it by selection sort algorithm""" for i in range(len(list)-1): index_min = i for j in range(i+1, len(list)): if list[j] < list[index_min]: index_min = j if index_min != i: l...
def php_trim(_str, _character_mask=" \t\n\r\0\x0B"): """ >>> a = r" \ttesting \t " >>> php_trim(a) 'testing' """ start = 0 end_ = len(_str) - 1 chars = [x for x in _character_mask] while True: if _str[start] in chars: start += 1 continue ...