content
stringlengths
42
6.51k
def wrap_text(text, max_length): """ Wrap text at the max line length Source: http://stackoverflow.com/a/32122312/499631 :param text: String of text :param max_length: Maximum characters on a line :return: """ words = iter(text.split()) lines, current = [], next(words) for word...
def rev(arr): """Reverse array-like if not None""" if arr is None: return None else: return arr[::-1]
def subdif_gap_1d(w, x): """ Horrible code, but otherwise does not work with numba """ eps = 1e-10 if x < 0 - eps: d = w + 1 elif x > 0 + eps: d = w - 1 else: if -1 <= w <= 1: d = 0 elif w > 1: d = w - 1 else: d = -w...
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificty). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positive ...
def mixfiles(d1, d2, cuts): """mixing data with exclusive parts of each data""" assert len(d1) == len(d2) d = b"" start = 0 keep = d1 skip = d2 for end in cuts: d += keep[start:end] start = end keep, skip = skip, keep d += keep[start:] return d
def prepend_chr(chr): """Prepends chromosome with 'chr' if not present. Users are strongly discouraged from using this function. Adding a 'chr' prefix results in a name that is not consistent with authoritative assembly records. Args: chr (str): The chromosome. Returns: ...
def filter_packets_by_filter_list(packets, filter_list): """ :param packets: Packet list :param filter_list: Filters with respect to packet field :type filter_list: list of pyshark_filter_util.PySharkFilter :return: Filtered packets as list """ filtered_packets = [packet for packet in packe...
def find_selected(nodes): """ Finds a selected nav_extender node """ for node in nodes: if hasattr(node, "selected"): return node if hasattr(node, "ancestor"): result = find_selected(node.childrens) if result: return result
def filter_out_installed_pkgs(event_out_pkgs, installed_pkgs): """Do not install those packages that are already installed.""" return {p for p in event_out_pkgs if (p.name, p.modulestream) not in installed_pkgs}
def insertDateRangeFilter(query): """ Add a date range filter on the '@timestamp' field either as a 'filter' or 'post_filter'. If both 'filter' and 'post_filter' are already defined then an RuntimeError is raised as the date filter cannot be inserted into the query. The date range filter will...
def _collect_scalars(values): """Given a list containing scalars (float or int) collect scalars into a single prefactor. Input list is modified.""" prefactor = 1.0 for i in range(len(values)-1, -1, -1): if isinstance(values[i], (int, float)): prefactor *= values.pop(i) return p...
def get_provenance_record(caption): """Create a provenance record describing the diagnostic data and plot.""" record = { 'caption': caption, 'statistics': ['diff'], 'domains': ['user'], 'plot_type': 'lineplot', 'authors': [ 'mueller_benjamin', 'cre...
def group_ngrams(p_words, window, fill_value): """ :param p_words: :param window: :param fill_value: Index for retrieving all zeros for padded regions. When loading the pre-trained embedding matrix, this row is filled with zeros. This is set as an additional row (last row) of the matrix. :retur...
def first_non_repeating_letter(str): """ This function returns the first non repeating letter in a string. This method does not use Counter function. Input: string Output: string of first non repeating letter. If all repeating, return empty string """ #Convert string to lower-case string ...
def _relu_not_vect(x, derivative=False): """Non vectorized ReLU activation function. Args: x (list): Vector with input values. derivative (bool, optional): Whether the derivative should be returned instead. Defaults to False. """ if x > 0: if derivative: return 1 ...
def freeParameters(self): """ Roadrunner models do not have a concept of "free" or "fixed" parameters (maybe it should?). Either way, we add a cheeky method to the tellurium interface to roadrunner to return the names of the parameters we want to fit """ return ['ki', 'kr', 'k_T1R', 'k_T2R',...
def get_location(location_strategy, dwell_location): """Determines if the vehicle can be charged given location strategy and dwelling location :param int location_strategy: where the vehicle can charge-1, 2, 3, 4, or 5; 1-home only, 2-home and work related, 3-anywhere if possibile, 4-home and school only, 5...
def read_reader(source, new_format=False): """ Read from EmotivReader only. Return data for decryption. :param source: Emotiv data reader :return: Next row in Emotiv data file. """ value = next(source) value = value.split(',') return value
def uri(argument): """ Return the URI argument with whitespace removed. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: uri = ''.join(argument.split()...
def check_central_position(m, n, i, j, width): """ checking if the distribution given by the `i,j` and `width` will be inside the grid defined by the `n` and `m`. :math:`i\in[1..m]`, :math:`j\in[1..n]`, where `m` -- number of cells along latitude and `n` is the number of cells along longi...
def get_nodes_ids(ipfs_diag_net_out): """ Parsing nodes IDs """ node_ids_set = set() for line in ipfs_diag_net_out.split("\n"): line = line.strip() if line.startswith("ID"): line = line.strip().split(" ")[1] node_ids_set.add(line) return node_ids_set
def cond_swap_bit(x,y, b): """ swap if b == 1 """ if x is None: return y, None elif y is None: return x, None if isinstance(x, list): t = [(xi - yi) * b for xi,yi in zip(x, y)] return [xi - ti for xi,ti in zip(x, t)], \ [yi + ti for yi,ti in zip(y, t)] els...
def coerce_to_list(data, key): """ Returns the value of the ``key`` key in the ``data`` mapping. If the value is a string, wraps it in an array. """ item = data.get(key, []) if isinstance(item, str): return [item] return item
def get_IGV_header(samples): """get header for IGV output file""" header = '#type=DNA_METHYLATION\nChromosome\tStart\tEnd\tFeature' for sample in samples[9:]: header += '\t%s' % sample return header + '\n'
def lift(lst): """Lift from 2D to 3D, with z=0.""" return [(x, y, 0) for (x,y) in lst]
def get_delta_from_interval(data_interval): """Convert interval name to number of seconds Parameters ---------- interval : str interval length {day, hour, minute, second, tenhertz} Returns ------- int number of seconds for interval, or None if unknown """ if data_in...
def sec_to_min_pretty(time_secs: int) -> str: """ Returns formatted string for converting secs to mins. """ if time_secs % 60 == 0: return f'{time_secs // 60}' m = time_secs / 60 return f'{m:.2g}'
def compute_phase_error(res, obs): """compute error in phase between 0 and 360""" if res < 0: res += 360 if obs < 0: obs += 360 if res >= obs: mu = res - obs return mu else: mu = res - obs mu += 360 return mu
def hex_switchEndian(s): """ Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i + 2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode()
def count_bcd_digits(bcd): """ Count the number of digits in a bcd value :param bcd: The bcd number to count the digits of :returns: The number of digits in the bcd string """ count = 0 while bcd > 0: count += 1 bcd >>= 4 return count
def _HPERM_OP(a): """Clever bit manipulation.""" t = ((a << 18) ^ a) & 0xcccc0000 return a ^ t ^ ((t >> 18) & 0x3fff)
def lev(str1, str2): """Make a Levenshtein Distances Matrix""" n1, n2 = len(str1), len(str2) lev_matrix = [ [ 0 for i1 in range(n1 + 1) ] for i2 in range(n2 + 1) ] for i1 in range(1, n1 + 1): lev_matrix[0][i1] = i1 for i2 in range(1, n2 + 1): lev_matrix[i2][0] = i2 for i2...
def triangleArea(a, b, c): """Calculates the area of a triangle spanned by three points. Note that the area will be negative if the points are not given in counter-clockwise order. Keyword arguments: a -- First point b -- Second point c -- Third point Returns: Area of triangle """ ...
def interval_converter(z, a, b): """ convert from [-1, 1] (the integration range of Gauss-Legendre) to [a, b] (our general range) through a change of variables z -> x """ z1 = 0.5*(b + a) + 0.5*(b - a)*z return z1
def collate_fn(batch): """Function that organizes the batch Keyword arguments: - batch """ return list(zip(*batch))
def validate_output(output_path): """ Converts 'default_loc' to './out.csv' and makes sure any passed in argument has a .csv file extension """ if output_path == 'default_loc' or not output_path: output_path = './out.csv' if output_path[-4:] != '.csv': output_path += '.csv' ...
def grad_desc(value, grad): """ Simple gradient descent function """ eta = 0.1 return (value - eta*grad)
def mergeWithLabels(json, firstField, firstFieldLabel, secondField, secondFieldLabel): """ merge two fields of a json into an array of { firstFieldLabel : firstFieldLabel, secondFieldLabel : secondField } """ merged = [] for i in range(0, len(json[firstField])): merged.append({ firstFieldLa...
def in_list(ldict, key, value): """ Find whether a key/value pair is inside of a list of dictionaries. @param ldict: List of dictionaries @param key: The key to use for comparision @param value: The value to look for """ for l in ldict: if l[key] == value: return True return False
def soft_equals(a, b): """Implements the '==' operator, which does type JS-style coertion.""" if isinstance(a, str) or isinstance(b, str): return str(a) == str(b) if isinstance(a, bool) or isinstance(b, bool): return bool(a) is bool(b) return a == b
def categorizeTypeOfDay(x): """ This function returns either the day provided is a week day or a weekend. :param x: string value of day :return: string """ if x == 'Monday': return 'Week Day' elif x == 'Tuesday': return 'Week Day' elif x == 'Wednesday': return 'We...
def get_root_url(url_path): """Split by forward-slash; Keep everything except image filename.""" return "/".join(url_path.split(r"/")[:-1])
def _clean_url(url: str) -> str: """...""" return '{}{}{}'.format( '' if url.startswith('http') else 'http://', '127.0.0.1' if url.startswith(':') else '', url.strip().rstrip('/') )
def _lambdas_to_sklearn_inputs(lambda1, lambda2): """Converts lambdas to input arguments for scikit-learn. :param lambda1: L1-regularization weight. :param lambda2: L2-regularization weight. :return: alpha: Input arg for scikit-learn model. :return: l1_ratio: Input arg for scikit-learn model. "...
def get_die_base_hazard_rate(type_id: int) -> float: """Retrieve the base hazard rate for a VHISC/VLSI die. :param type_id: the VHISC/VLSI type identifier. :return: _lambda_bd; the base die hazard rate. :rtype: float """ return 0.16 if type_id == 1 else 0.24
def purge_log_day(args_array, server): """Function: purge_log_day Description: purge_log_day function. Arguments: (input) args_array (input) server """ status = True if args_array and server: status = True return status
def size_of_window_vector(number_of_freq_estimations): """size of the window vector""" return 4*number_of_freq_estimations + 1
def minHour(rows, columns, grid): """ This function calculates the minimum hours to infect all humans. Args: rows: number of rows of the grid columns: number of columns of the grid grid: a 2D grid, each cell is either a zombie 1 or a human 0 Returns: minimum hours to infect all...
def cut(value, arg): """Removes all values of arg from the given string""" return value.replace(arg, "")
def rating_label(rating, cfg): """Convert a credibility rating into a label :param rating: a credibility rating. We assume it has `reviewAspect == credibility` and float `confidence` and `ratingValue`s :param cfg: configuration options :returns: a short string to summarise the credibility r...
def calculateAltitude(P, P0): """ Calculate altitude from barometric pressure readings Formula from: http://www.mide.com/products/slamstick/air-pressure-altitude-calculator.php """ return 44330.0 * (1 - (P / P0) ** (1 / 5.255))
def add_all(tap_stream_id): """ Adds all to the generic term e.g. groups_all for groups """ return tap_stream_id.split('-')[0] + '_all'
def is_palindrome(word_3): """ To check whether the word is the "Palindrome". """ for i in range(len(word_3)): if(word_3[i]==word_3[len(word_3)-1-i]): return(True) else: return(False)
def union_of_intervals(intervals): """ Takes an iterable of intervals and finds the union of them. Will fail if they are not on the same chromosome :param intervals: Iterable of ChromosomeIntervals :return: List of new ChromosomeIntervals """ new_intervals = [] for interval in sorted(interva...
def range_union(ranges): """Take a list of (H, M) tuples and merge any overlapping intervals.""" results = [] # tuples are sorted in increasing order, so we are sure we always have # the "latest" end time at the back of the list for start, end in sorted(ranges): last_end_time = results[-1] i...
def filter_groups_by_members(groups, quantity=1): """ Take groups list and return empty groups :param groups: :param quantity: :return: """ return [x for x in groups if int(x["total"]) < quantity]
def get_translated_text(basisObj): """ return the concatenated string of translated Named Entities if present """ concatenated_text = [] for e in basisObj.get('entities', []): if 'translation' in e: concatenated_text.append(e['translation']) return " ".join(concatenated_text)
def normalize_spec_version(version): """Return the spec version, normalized.""" # XXX finish! return version
def MissingNumber2(array, n) : """ In case we get a very large integer in the summation process """ summ = 0 for i in range(n-1) : summ += array[i] - (i+1) return n - summ
def find_even_index(arr): """ Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. :param arr: Array of integers. :return: The lowest index...
def insert_right(root, new_branch): """ :param root: current root of the tree :param new_branch: new branch for a tree :return: updated root of the tree """ t = root.pop(2) if len(t) > 1: root.insert(2, [new_branch, [], t]) else: root.insert(2, [new_branch, [], []]) ...
def factorial(n): # n! can also be defined as n * (n-1)! """ calculates n! recursively """ if n <= 1: return 1 else: return n * factorial(n-1)
def silent_write_text_file(filename, contents=''): """ Create a new text file and writes contents into it (do not raise exceptions). If file with specified name already exists, it will be overwritten. :return: Dict - 'error': empty string if success, or error message otherwise. """ result = {'er...
def delete_invalid_values(dct): """ Deletes entries that are dictionaries or sets """ for k, v in list(dct.items()): if isinstance(v, dict) or isinstance(v, set): del dct[k] return dct
def get_float_cell_value(cell_value) -> float: """Returns the value of an openpyxl cell value. This function is used in oder to operate with spreadsheets which use the comma as the decimal mark instead of a period. Arguments ---------- * cell_value ~ The openpyxl cell value """ ...
def timefmt(t, fmt): """ Format a timestamp in the correct way for subtitles. This is the only reason we need a programming language and can't do this in bash easily. """ seconds = t % (24 * 3600) hours = int(seconds // 3600) seconds %= 3600 minutes = int(seconds // 60) seconds %= 60...
def _is_chief(task_type, task_id): """Determines if the replica is the Chief.""" return task_type is None or task_type == 'chief' or ( task_type == 'worker' and task_id == 0)
def get_fib(position): """ Algorithm: 1. If position matches with base cases(0 and 1) then return the position. i.e. 1.1 If position == 0 return 0 1.2 If position == 1 return 1 2. Else return addition of previous two values """ if position == 0...
def _f_p_r_lcs(llcs, m, n): """ Computes the LCS-based F-measure score. Source: https://www.microsoft.com/en-us/research/publication/ researchouge-a-package-for-automatic-evaluation-of-summaries/ Args: llcs: Length of LCS m: number of words in (truncated) candidate summary n: nu...
def findMin(nums): """ :type nums: List[int] :rtype: int """ if nums == []: return 0 min_number = nums[0] for i in range(len(nums) - 1): if nums[i + 1] < nums[i]: return nums[i + 1] return min_number
def replace_ip_in_string(ip, string): """ Description ----------- Use to change the ip in a packet Parameters: string: Represent the ip that are overwrite string: Represent the string that have the uncorrect ip Return ------ ...
def find_next_empty(puzzle): """ Takes a puzzle as parameter Finds the next row, col on the puzzle that's not filled yet (with a value of -1) Returns (row, col) tuple or (None, None) if there is none """ for row in range(9): for col in range(9): if puzzle[row][col] ==...
def xor(stream: bytes, key: int) -> bytes: """Apply XOR cipher to ``stream`` with ``key``. Applying this operation twice decodes ``stream`` back to the initial state. Parameters ---------- stream: :class:`bytes` Data to apply XOR on. key: :class:`int` Key to use. Type ``u8`` (o...
def test(test_names): """ Run unit tests """ import unittest if test_names: """ Run specific unit tests. Example: $ flask test tests.test_auth_api tests.test_user_model ... """ tests = unittest.TestLoader().loadTestsFromNames(test_names) else: tests = u...
def unwrap(value): """ Unwrap a quoted string """ return value[1:-1]
def getfloat(value, default=None): """getfloat(value[, default]) -> float(value) if possible, else default.""" try: return float(value) except Exception: return default
def prob2odds(p): """ Return the odds for a given probability p """ # Note: in the case of the usual game, we do not have to handle impossible events (e.g if a horse cannot win), and so this equation will never result in # divion by zero. return (1-p) / p
def total_others_income(responses, derived): """ Return the total of other incomes """ total = 0.0 for income in derived['others_income']: try: total += float(income['income_others_amount']) except ValueError: pass return total
def equal(iterator): """ Checks whether all elements of ``iterator`` are equal. INPUT: - ``iterator`` -- an iterator of the elements to check OUTPUT: ``True`` or ``False``. This implements `<http://stackoverflow.com/a/3844832/1052778>`_. EXAMPLES:: sage: from sage.combinat...
def sendmsg(msg, value1=None, value2=None): """ Purpose : send the same message to the screen Passed : msg - the string value - the number associated with the string Returns ------- return """ print('*******************************************************...
def divND(v1, v2): """Returns divisor of two nD vectors (same as itemwise multiplication) Note that this does not catch cases where an element of the divisor is zero.""" return [vv1 / vv2 for vv1, vv2 in zip(v1, v2)]
def first_bad_version(last_version, is_bad_version): """ Finds the first bad version. Runtime: O(n), I should have thought this function as if find the min number in the sorted list. """ for version in range(last_version, -1, -1): print(f"version: {version}") if not is_bad_versi...
def id18to15(id18): """ Truncate an 18 char sObject ID to the case-sensitive 15 char variety. """ return id18[:15]
def compute_increment(draw, a, b): """ From a list of event timestamps in a counting process, count the number of events between a and b. :param list[float] draw: A list of timestamps drawn from a counting process :param float a: The left endpoint :param float b: The right endpoint :return:...
def adjust_key(key, shape): """Prepare a slicing tuple (key) for slicing an array of specific shape.""" if type(key) is not tuple: key = (key,) if Ellipsis in key: if key.count(Ellipsis) > 1: raise IndexError("an index can only have a single ellipsis ('...')") ellipsis...
def convert(args_list): """Convert a list of arguments from string to whatever type it can be converted. Args: args_list: A list of string arguments. Returns: A list of arguments, each of the type that could be converted. """ result = [] for item in args_list: try: ...
def initCtrl(size): """Init array usefull to check the diagionales and the lines Args: size (int): size of the board Returns: [array]: ctrl_line [array]: ctrl_oblique [array]: ctrl_obliqueinv """ x = 2 * size - 1 ctrl_oblique = [False] * x ctrl_obliqueinv = [False]...
def strify(iterable_struct, delimiter=','): """ Convert an iterable structure to comma separated string. :param iterable_struct: an iterable structure :param delimiter: separated character, default comma :return: a string with delimiter separated """ return delimiter.join(map(str, iterable_struc...
def constraints_check(constraints=None): """Check constraints list for consistency and return the list with basic problems corrected. A valid constraints list is a list of constraint dictionaries. --> [{const_dict}, ... ,{const_dict}] A constraint dictionary specifies individual constraint functions, argu...
def find_target_dict(scene_data): """Find and return the target dict from the scene data.""" return scene_data['objects'][0]
def flatten(lists): """ Singly flattens nested list """ return [item for sublist in lists for item in sublist]
def validate_brackets(code_to_validate): """ You're working with an intern that keeps coming to you with JavaScript code that won't run because the braces, brackets, and parentheses are off. To save you both some time, you decide to write a braces/brackets/parentheses validator. """ if not code...
def bytes_startswith_range(x: bytes, prefix: bytes, start: int, end: int) -> bool: """Does specified slice of given bytes object start with the subsequence prefix? Compiling bytes.startswith with range arguments compiles this function. This function is only intended to be executed in this compiled form. ...
def define_format_dict(): """Define FORMAT field Args: None Returns: d (dict): see define_info_dict """ d = { "AD": { "COLUMN": ["ref_count", "alt_count"], "Number": "R", "Type": "Integer", "Description": "Allelic depths by fr...
def IoU(bbox1, bbox2): """Compute IoU of two bounding boxes Args: bbox1 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of the bounding box, and (w, h) are width and height of the box. bbox2 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of the bou...
def split(l, c=0): """Split the given list in two.""" return (l[: int(len(l)/2)], l[int(len(l)/2) : None if c == 0 else c])
def computeDeviation(pDetect, pGener, tol_limit): """ per class deviation measurer""" expectedToleranceplus = pDetect+tol_limit*0.01*pDetect expectedToleranceminus = pDetect-tol_limit*0.01*pDetect if (pGener <= expectedToleranceplus and pGener >= expectedToleranceminus): deviation = 0 ...
def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2.""" y1 -= 1 y2 -= 1 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
def obj(X): """ Objective function: Rosenbrock function with n variables Minimum for obj(1.0,...,1.0) = 0.0 """ res = 0.0 for i_param in range(len(X)-1): res += 100.0*(X[i_param+1]-X[i_param]**2)**2 + (X[i_param]-1.0)**2 return res
def get_prob_from_odds( odds, outcome ): """ Get the probability of `outcome` given the `odds` """ oddFor = odds[ outcome ] oddAgn = odds[ 1-outcome ] return oddFor / (oddFor + oddAgn)