content
stringlengths
42
6.51k
def class_rofs(log): """An error classifier. log the console log text Return None if not recognized, else the error type string. """ if ('Read-only file system' in log or 'Remounting filesystem read-only' in log): return 'ROFS' return None
def inherits_from(obj, a_class): """checks if an object is an instance of a class that inherited (directly or indirectly) from the specified class""" return (type(obj) is not a_class and issubclass(type(obj), a_class))
def count_sep(specstr, sep=','): """Count number of specified separators (default = ',') in given string, avoiding occurrences of the separator inside nested braces""" num_seps = 0 brace_depth = 0 for s in specstr: if s == sep and brace_depth == 0: num_seps += 1 elif s =...
def countVowelsConsonants(string:str)-> tuple: """ This function returns the number of vowels and consonants in a string. -> (no_vowels, no_consonants) """ vowels = ['a','e', 'i', 'o', 'u'] consonants = ['b','c','d','f','g','h','j','k','l','m', 'n','p','q','r','s','t','v','w','x','...
def create_args_string(num): """ Create sql args by arg num""" L = [] for n in range(num): L.append('?') return ', '.join(L)
def guess_csv_value(s): """Determine the most appropriate type for `s` and return it. Tries to interpret `s` as a more specific datatype, in the following order, and returns the first that succeeds: 1. As an integer 2. As a floating point value 3. If it is "false" or "true" (case insensitive),...
def f1_score(real_labels, predicted_labels): """ Information on F1 score - https://en.wikipedia.org/wiki/F1_score :param real_labels: List[int] :param predicted_labels: List[int] :return: float """ assert len(real_labels) == len(predicted_labels) true_p = 0 true_n = 0 false_p = 0...
def encodeUnicode(s): """ @summary: Encode string in unicode @param s: str python @return: unicode string """ return "".join([c + "\x00" for c in s]) + "\x00\x00"
def merge_dicts(x, y): """A function to merge two dictionaries, making it easier for us to make modality specific queries for dwi images (since they have variable extensions due to having an nii.gz, bval, and bvec file) Parameters ---------- x : dict dictionary you want merged with y ...
def get_items_per_page(results): """Return the itemsPerPage object from a Google Analytics API request. :param results: Google Analytics API results set :return: Number of items per page (default is 1000 if not set, max is 10000) """ if results['itemsPerPage']: return results['itemsPerPage...
def bbox_south_north_west_east_to_min_max(south_latitude, north_latitude, west_longitude, east_longitude): """ Coordinate conversion: south/north/west/east to min/max. Convert from south_latitude, north_latitude, west_longitude, east_longitude to min_longitude, min_latitude, max_longitu...
def is_straight(hand, numwildcards=0): """Checks for a five card straight Inputs: list of non-wildcards plus wildcard count 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace Hand can be any length (i.e. it works for seven card games). Outputs: highest card in a fiv...
def compare_versions(v1_raw, v2_raw): """ Parses v1_raw and v2_raw into versions and compares them Returns 'equal' if v1 == v2 Returns 'greater' if v1 > v2 Returns 'lower' if v1 < v2 """ v1 = v1_raw.replace("-rc", "") v2 = v2_raw.replace("-rc", "") v1_split = v1.split(".") v2_spl...
def uniqueness(container): """ Checks if the container is unique. In case of uniqueness it returns True """ return len(container) == len(list(set(container)))
def name_length(words): """Check the length of each word and an average. Args: words (list): A list of words Returns: dict: The data and summary results. """ names_length = [] for val in words: names_length.append(len(val)) summary = 'Of {} words, the average length...
def match_end_faces(test_end_face, end_faces): """ Test if test_end_face match with any end face in end_faces Each face takes value in (0, 90, 180, 270) :param test_end_face: one face :param end_faces: end_faces_to_match_against :return: True if there is a match """ for ef in end_faces: ...
def get_innermost_context(exc): """ Return information about the innermost exception context in the chain. """ depth = 0 while True: context = exc.__context__ if context is None: break exc = context depth += 1 return (type(exc), exc.args, depth)
def to_hashable(obj): """ Makes a hashable object from a dictionary, list, tuple, set etc. """ if isinstance(obj, (list, tuple)): return tuple(to_hashable(i) for i in obj) elif isinstance(obj, (set, frozenset)): return frozenset(to_hashable(i) for i in obj) elif isinstance(obj, d...
def round_to_even(x): """ :param x: some number (float or int) :return: nearst odd integer """ return int(round(x / 2) * 2)
def any_of(possibilities, to_add=''): """ Construct a regex representing "any of" the given possibilities :param possibilities: list of strings representing different word possibilities :param to_add: string to add at the beginning of each possibility (optional) :return: string corresponding to rege...
def is_number(s): """ Small function to check if a value is numeric """ try: float(s) # for int, long and float - not complex as complex also allows 'J' as number or unit except ValueError: return False return True
def word_simil(refr, new): """ maximum word similarity between sentence and list of sentences """ new = set(new.split(' ')) refr = [set(x.split(' ')) for x in refr if x!=new] refr = [len(x&new) for x in refr] return max(refr)
def find_voxel(x, y, z, g): """returns (i,j,k) of voxel containing point x,y,z if the point is within the grid, otherwise return the corresponding grid boundary. """ # g is grid boundaries i = max(0, int((x - g["xlo"]) // g["dx"])) j = max(0, int((y - g["ylo"]) // g["dy"])) k = max(0,...
def insert_seq(str1, str2, at): """ (str1, str2, int) -> str Return the DNA sequence obtained by inserting the second DNA sequence into the first DNA sequence at the given index. """ str1_split1 = str1[:at] str1_split2 = str1[at:] return str1_split1 + str2 + str1_split2
def tier_count(count): """ If a tier quota is 9999, treat it as unlimited. """ if count == 9999: return "Unlimited" else: return count
def win_check(board, mark): """ function that takes in a board and checks to see if someone has won. :param board: the board to check :param mark: the last mark in placed in the board :return: True if game is win or False otherwise """ return ((board[7] == mark and board[8] == mark and board...
def conv_nmbr(N): """ convert a list of integers in a number """ a = list(map(lambda i: str(i), N)) return int("".join(a))
def numerise_params(prop_dict): """ Returns drug properties with all qualitative values transformed into numeric values returns: numerically transformed property dictionaries rtype: dict """ clearance_dict = { 'low (< 5.6)': 1, 'medium (5.6-30.5)': 4, 'low (< 3.7)': 1, ...
def _query_absolute(start, end): """ :type start_absolute: float :param start_absolute: This is the absolute start time (unix time since the epoch) for the batch of metrics being retrieved. :type end_absolute: float :param end_absolute: This is the absolute start time (unix time since the epoch) fo...
def name_fun(n): """ input: stopping rule output: finish nodes """ output = [] temp = [''] for i in range(2*n - 1): temp_cur = [] for j in temp: candidate_pos = j + '+' candidate_neg = j + '-' if str.count(candidate_pos, '+') >= n: ...
def int_to_bytes(n): """Takes an integer and returns a byte-representation""" return n.to_bytes((n.bit_length() + 7) // 8, 'little') or b'\0' # http://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes
def isValidPasswordPartOne(lowerBound: int, upperBound: int, targetLetter: str, password: str) -> int: """ Takes a password and returns 1 if valid, 0 otherwise. First part of the puzzle """ validSoFar: bool = True letterCount: int = 0 for char in password: if char == targetLetter: ...
def _pgsql_numerical_version_to_string(version_num): """Convert numerical PostgreSQL version to string.""" if version_num < 100000: major = version_num // 10000 minor = version_num % 10000 // 100 patch = version_num % 100 return f"{major}.{minor}.{patch}" # version 10+ m...
def initialize_2d_mask(num_rows, num_cols): """ Initializes mask with False values. Parameters: num_rows (int): number of rows num_cols (int): number of columns Returns: a 2D mask of size num_rows * num_cols """ return [[False for c in range(num_cols)] for r in range(num_rows)]
def splitName(s, titleDict): """ Extract title from name, replace with value in title dictionary. Also return surname. """ # Remove '.' from name string s = s.replace('.', '') # Split on spaces s = s.split(' ') # get surname surname = s[0] # Get title - loop over titleDict,...
def normalize_vartype(vartype): """Return the canonical form for a variable type (or func signature).""" # We allow empty strring through for semantic reasons. if vartype is None: return None # XXX finish! # XXX Return (modifiers, type, pointer)? return str(vartype)
def helper_grep_funcNames(funcName_2_score_arr_str): """ funcName_2_score_arr_str = '{{"GO:0005777",0.535714},{"GO:0005783",0.214286},{"GO:0016021",3}}' --> ['GO:0005777', 'GO:0005783', 'GO:0016021'] """ funcName_2_score_arr_str = [ele[1:] for ele in funcName_2_score_arr_str.replace('"', '').replace...
def convert_base2(n): """This function takes an integer as input and returns a string with it's binary representation. Parameters ---------- n : int Integer in base 10 to convert. Returns ------- n_base2 : string String representation of n in base 2. """ n_base2...
def query_len(cigar_string): """ Given a CIGAR string, return the number of bases consumed from the query sequence. """ from itertools import groupby read_consuming_ops = ("M", "I", "S", "=", "X") seqlength = 0 cig_iter = groupby(cigar_string, lambda chr: chr.isdigit()) fo...
def _object_lookup_to_pk(model, lookup): """Performs a lookup if `lookup` is not simply a primary key otherwise is returned directly.""" try: pk = int(lookup) except (TypeError, ValueError): # otherwise, attempt a lookup try: pk = model._default_manager.get(**lookup).pk ...
def lower_case(value): """Converts string by removing whitespace and lower-casing all chars.""" value = value.strip() value = value.lower() return value
def convert_to_kebab_case(name, join_character='-'): """ Transforms incoming name into hyphen-separated lower-cased string.""" return join_character.join(name.split()).lower()
def stringify_bundle2(allocation_dict: dict): """ Convert a bundle where each item is a character to a compact string representation. For testing purposes only. This method adds the allocation part to the item as well, not just the name """ result = "{" for item, alloc in allocation_dict.ite...
def overlap_length(a, b): """ Calculate the length of overlap for two intervals. Args: a (int, int): First interval (as 2-tuple of integers). b (int, int): Second interval (as 2-tuple of integers). Returns: int: The length of overlap for a and b, or 0 if there is no overlap. E...
def parse_keyval_list(options): """ Convert list of key/value pairs (typically command line args) to a dict. Typically, each element in the list is of the form option=value However, multiple values may be specified in list elements by separating them with a comma (,) as in a=1,b=5,c...
def get_locations(data: dict) -> list: """ Get users' locations from the dictionary. Return list of lists, every one of which contains user's nickname and location. >>> get_locations({'users': [{'screen_name': 'Alina', 'location':\ 'Lviv, Ukraine'}]}) [['Alina', 'Lviv, Ukraine']] """ result...
def parse_im_name(im_name, parse_type='id'): """Get the person id or cam from an image name.""" assert parse_type in ('id', 'cam') if parse_type == 'id': parsed = int(im_name[:8]) else: parsed = int(im_name[9:13]) return parsed
def fartocels(fahrenheit): """ This function converts fahrenheit to celsius, with fahrenheit as parameter.""" celsius = 5 * (fahrenheit - 32) / 9 return celsius
def binary_search(x, error): """sqrt via binary search, with error margin""" if x < 0: return -1 else: # watch out for float rounding errors if x > 1: lo = 0.0 hi = x else: lo = x hi = 1 while abs(hi - lo) > error: ...
def arg_max(list_input): """ Return the index of the biggest element on the array :param list_input: Input List :return: index biggest element """ biggest_element = max(list_input) idx_max = list_input.index(biggest_element) return idx_max
def find_factors(num): """Find factors of num, in increasing order. >>> find_factors(10) [1, 2, 5, 10] >>> find_factors(11) [1, 11] >>> find_factors(111) [1, 3, 37, 111] >>> find_factors(321421) [1, 293, 1097, 321421] """ answer = [] for i in range(1, num): i...
def flatten(data): """Flatten out all list items in data.""" flatten_list = [] if type(data) == list: for item in data: flatten_list.extend(flatten(item)) return flatten_list else: return [data]
def count_digit(k, n): """ Count the number of k's between 0 and n. k can be 0 - 9. :param k: given digit :type k: int :param n: given number :type n: int :return: number of k's between 0 and n :rtype: int """ count = 0 for i in range(n + 1): # treat number as string...
def determine_winner(choice1, choice2): """ Determines the winning choice between two choices from selectable options: "rock", "paper", or "scissors". Returns the winning choice (e.g. "paper"), or None if there is a tie. Example: determine_winner("rock", "paper") """ #if choice1 == choice2: ...
def sum_naturals(n): """Return the sum of the first n natural numbers >>> sum_naturals(10) 55 >>> sum_naturals(100) 5050 """ total, k = 0, 1 while k <= n: total, k = total + k, k + 1 return total
def timespan(ts): """Calculates the time span of the timeseries. Args: ts: A timeseries list of [time, value]. Returns: The time span of the timeseries. """ return ts[-1][0] - ts[0][0]
def get_y_for_x(x: float, gradient: float, y_intercept: float) -> float: """ Linear equation, y = mx + c """ return (x * gradient) + y_intercept
def update_args_dict(args_dict, updater): """Update a dict of arg values with more values from a list or dict.""" if isinstance(updater, list): for arg in updater: key, sep, value = arg.partition('=') if sep == '=': args_dict[key] = value if isinstance(updater, dict): for key, ...
def _printable_name(model_obj): """Returns a print-frendly name for a model object. :param model_obj: a model, schema, table, column, key, or foreign key object. :return: string representation of its name or "catalog" if no name found """ if not hasattr(model_obj, 'name'): return 'catalog' ...
def expected(A, B): """ Calculate expected score of A in a match against B :param A: Elo rating for player A :param B: Elo rating for player B """ return 1 / (1 + 10 ** ((B - A) / 400))
def get_docstring(obj): """ Returns docstring for a given object or empty string if no-object is provided or there is no docstring for it. :param obj: Object for which the docstring to be provided :return: Docstring """ if obj is None: return '' doc = obj.__doc__ if doc is None...
def strip_trailing_zeroes(num) -> str: """Remove trailing zeroes, e.g. 0.500 --> 0.5 and 1.000 -> 1""" s = "{:.3f}".format(num) return s.rstrip("0").rstrip(".") if "." in s else s
def accumulate_sum(lst): """Return accumulated sum list.""" if len(lst) == 1: return lst accumulated_sum = [lst[0]] for i in range(1, len(lst)): accumulated_sum.append(accumulated_sum[i - 1] + lst[i]) return accumulated_sum
def get_config_identifier(nodes): """Generate an identifer for a configuration of nodes Takes in a list of nodes within a cluster and generates a consistent identifier for that configuration. Args: nodes - Dict mapping node names (e.g. n1-standard-2) to the number of nodes of that type present in ...
def forcestring(value): """Test a value, if it is not an empty string or None, return the string representation of it, otherwise return an empty string. """ if value is None: return "" return str(value)
def left(s, amount): """ Returns the left characters of amount size """ return s[:amount]
def get_box_neighbors(i_cur, j_cur, i_max, j_max): """ Return tupels with coordinates of neighboring boxes. Raises: ValueError: If input coordinates are outside of design Args: i_cur(int or float): index of box in x direction j_cur(int or float): index of box in y direction ...
def preprocess_pages(pages, **options): """Convert a 2-element page range tuple to a string.""" if isinstance(pages, tuple) and len(pages) == 2: return "{0}--{1}".format(pages[0], pages[1]) return str(pages)
def _isCharEnclosed(charIndex, string): """ Return true if the character at charIndex is enclosed in double quotes (a string) """ numQuotes = 0 # if the number of quotes past this character is odd, than this character lies inside a string for i in range(charIndex, len(string)): if string[i] == '"':...
def convert_position_to_engine_format(position): """Convert conventional position format to engine format. position can be for example "a1". For example "a1" is converted to 0. """ return "abcdefgh".find(position[0]) + (int(position[1]) - 1) * 8
def ins_all_positions(x, l): """Return a list of lists obtained from l by inserting x at every possible index.""" res = [] for i in range(0, len(l) + 1): res.append(l[:i] + [x] + l[i:]) return res
def slice_output_shape(input_shape, options): """Slice input to output shape conversion""" size = options["size"] return (int(input_shape[0]),) + size
def axis_ticklabels_overlap(labels): """Return a boolean for whether the list of ticklabels have overlaps. Parameters ---------- labels : list of ticklabels Returns ------- overlap : boolean True if any of the labels overlap. """ if not labels: return False try:...
def b_string_to_bytes(b_str: str) -> bytes: """ converts a string containing a bytes literal (ex: 'b"something"') to bytes. """ return b_str[2:-1].encode()
def _iterable(obj): """ Returns True if `obj` is iterable. """ try: iter(obj) except TypeError: return False return True
def isunauthenticated(func): """Checks if the function does not require authentication. Mark such functions with the `@unauthenticated` decorator. :returns: bool """ return getattr(func, 'unauthenticated', False)
def between(val, end1, end2): """ Return True if val is between end1 and end2 or equals either.""" return end1 <= val <= end2 or end2 <= val <= end1
def format_num_2(num): """ Format the number to 2 decimal places. :param num: The number to format. :return: The number formatted to 2 decimal places. """ return float("{:.2f}".format(num))
def silence_error_if_missing_file(exception): """ Ugly way of checking in an exception describes a 'missing file'. """ missing_files_errs = ('no such file', 'does not exist', ) def find_msg_in_error(msg): return msg in str(exception).lower() if not any(map(find_msg_in_error, missing_fi...
def get_curr_bids(active_players): """Returns count of total bids at the moment""" curr_bids = 0 for player in active_players: curr_bids += player.bid return curr_bids
def escape_naive(context): """A tag that doesn't even think about escaping issues""" return "Hello {0}!".format(context['name'])
def _before_name(method_name): # type: (str) -> str """Return the name of the before check method. >>> _before_name('read') 'can_read__before' """ return 'can_' + method_name + '__before'
def _getName(log): """extract the Name""" for l in log: if "name:" in l.lower(): return l[l.index("Name:") + 5:].strip() return ""
def clean(s, isInt=False): """ This function takes the string input from the HTML text area field and converts those entries into a list of floating-point numbers or integers (for bitwise operations) which will be used to intialize the matrices. This function assumes the string only has number valu...
def split_permutations(n, minimum=0, recurse=0, require_full_size=False): """ Generates a list of permutations for how many ways you can split a the number n into smaller values For example: split_permutations(5, minimum=2, recurse=0) = [[2, 3], [3, 2]] split_permutations(4, minimum=1, recur...
def add_int(x, y): """Add Integers Add two integer values. Parameters ---------- x : int First value y : int Second value Returns ------- int Result of addition Raises ------ TypeError For invalid input types. """ if not isins...
def rel_to_abs(vector, cell): """ converts interal coordinates to absolut coordinates in Angstroem. """ if len(vector) == 3: postionR = vector row1 = cell[0] row2 = cell[1] row3 = cell[2] new_abs_pos = [postionR[0]*row1[0] + postionR[1]*row2[0]+ postionR[2]*r...
def _mask_for_bits(i): """Helper function for read_bitpacked to generage a mask to grab i bits.""" return (1 << i) - 1
def _find_line_containing(source, index): """Find (line number, line, offset) triple for an index into a string.""" lines = source.splitlines() if not lines: # Special case: empty program return 1, '', 0 this_line_start = 0 for zero_index_line_number, line in enumerate(lines): ...
def just_two_adjacent_digits_same(number: int) -> bool: """Two adjacent matching digits are not part of a larger group of matching digits.""" digits = str(number) num_length = len(digits) for pair in range(num_length - 1): # For example, a 6 digit number has 5 pairs to check. d1 = dig...
def dd2ddm(x): """A little helper function that takes a coordinate in decimal degrees and splits it into degrees, decimal minutes. Values are returned as a dictionary that can then be used in string formatting""" from math import floor negative = 1 if x > 0 else -1 x = abs(x) degrees...
def mk_pct(amt=1, total=1): """ mk_pct :param amt: int :param total: int :return: float """ return f"{(amt/total)*100:.2f}"
def merge_list(old, new): """merges lists and comma delimited lists.""" if not old: return new if isinstance(new, list): old.extend(new) return old else: return ','.join([old, new])
def name_to_args(namestring): """Takes a script name which may contain CLI args and splits out the args. Assumes string is generically of the form '<script name>.py -arg --arg' """ namestring = namestring.rstrip().lstrip() if namestring[-3:] == '.py': return [namestring] args = namestring.split('.p...
def format_duration_in_millis(duration=0): """ formats the difference between two times in millis as Xd:Xh:Xm:Xs """ seconds, millis = divmod(duration, 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) output = [] written = False if d...
def search_lists(k, v, data): """ Search a list of lists by index """ match = [] k = int(k) for row in data: row_values = list(row.values()) if row_values[k] == v: match.append(row) if len(match) == 1: # If we only get one result: return just it. ...
def minimal_svg(s): """Returns the SVG document without the XML declaration and SVG namespace declaration :rtype: str """ return s.replace('<?xml version="1.0" encoding="utf-8"?>\n', '') \ .replace('xmlns="http://www.w3.org/2000/svg" ', '').strip()
def duplicate_randomly(thelist: list, maxduplication=3): """Takes a list of objects and will randomly duplicate the occurrence of each object in the list. The maximum threshold of how many duplicates are created is limited by the 'maxduplication' parameter and defaults to 3. Args: thelist (list): Refe...
def format_resolve_template(template_in, format_variables): """Renders the given Resolve template with the given Python dict. The result is always Resolve safe. Meaning that variables like "%{Clip Type}" will be preserved if the given ``format_variables`` doesn't alter it. :param str template_in: A str...
def text2int(textnum, numwords={}): """ Returns integer number from its string representation, or False if the string doesn't represent a number. """ if not numwords: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "ele...