content
stringlengths
42
6.51k
def left_to_right_check(input_line, pivot): """ str, int -> bool Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hin...
def _Delta(a, b): """Compute the delta for b - a. Even/odd and odd/even are handled specially, as described above.""" if a+1 == b: if a%2 == 0: return 'EvenOdd' else: return 'OddEven' if a == b+1: if a%2 == 0: return 'OddEven' else: return 'EvenOdd' return b - a
def correlate(x, y): """Pearson's correlation """ # Assume len(x) == len(y) n = len(x) sum_x = float(sum(x)) sum_y = float(sum(y)) sum_x_sq = sum(xi*xi for xi in x) sum_y_sq = sum(yi*yi for yi in y) psum = sum(xi*yi for xi, yi in zip(x, y)) num = psum - (sum_x * sum_y/n) den ...
def HMStime(s): """ Given the time in seconds, an appropriately formatted string. """ if s < 60.: return '%.2f s' % s elif s < 3600.: return '%d:%.2f' % (int(s / 60 % 60), s % 60) else: return '%d:%d:%.2f' % (int(s / 3600), int(s / 60 % 60), s % 60)
def psycopg_uri(username, password, db_name, host='', port=None): """Create a URL for psycopg2. http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#module-sqlalchemy.dialects.postgresql.psycopg2 # noqa """ if port: return f'postgresql+psycopg2://{username}:{password}@{host}:{port}/{db_name}' else: ...
def _list_from_list_or_value(value): """ Returns a list, regardless of the value is str or list """ if isinstance(value, list): return value elif isinstance(value, str): return [value] else: raise Exception('type of value not recognized')
def _geom_series_uint32(r, n): """Unsigned integer calculation of sum of geometric series: 1 + r + r^2 + r^3 + ... r^(n-1) summed to n terms. Calculated modulo 2**32. Use the formula (r**n - 1) / (r - 1) """ if n == 0: return 0 if n == 1 or r == 0: return 1 m = 2**32 ...
def password_filter(password: str) -> bool: """ Test that the password meets the criteria above """ # happily, strings also work in numeric order in terms of sorting if ''.join(sorted(password)) == password and len(set(password)) < len(password): return True return False
def GetMovingImages(ListOfImagesDictionaries,registrationImageTypes,interpolationMapping): """ This currently ONLY works when registrationImageTypes has length of exactly 1. When the new multi-variate registration is introduced, it will be expanded. """ if len(registrationImageTypes) !=1: ...
def batch(elems, args): """Filter that batches an iterator into batchsize sized groups Takes a single string argument in one of two forms: 1. batchsize as an int. e.g. ``batch:"4"`` 2. batchsize as an int followed by a comma followed by a string to pad the last row with. e.g. ``batch:"4,&nbsp"`...
def make_inverse_actions_bidirectional(inverse_actions): """Add inverse of all dict tuples to the dict.""" for key, val in inverse_actions.copy().items(): inverse_actions[val] = key return inverse_actions
def _get_node_color(egraph, color_nodes, point): """Color nodes based on ``color_nodes`` arg: - if `color_nodes` is a string use the string as color, - using the attribute and color dict if `color_nodes` is a tuple(str,dict), - or based on color attribute (when available) if `color_nodes` is bool and T...
def recreate_doubled_chars(text): """Transform '+' chars into previous letter.""" text_as_list = list(text) for index in range(len(text_as_list) - 1): if text_as_list[index + 1] == '+': text_as_list[index + 1] = text_as_list[index] text = ''.join(text_as_list) return text
def _freeze_it(values): """Freezes a set of values (handling none/empty nicely).""" if not values: return frozenset() else: return frozenset(values)
def color(string, color, do_color): """ Wrap a string in an ansi color code """ if do_color: return '\033[{}m{}\033[0m'.format(color, string) else: return string
def _parse_options(opts, delim): """Helper method for split_options which creates the options dict. Also handles the creation of a list of dicts for the URI tag_sets/ readpreferencetags portion.""" options = {} for opt in opts.split(delim): key, val = opt.split("=") if key.lower() ==...
def comp_cols(comps): """Return columns corresponding to the average composition :comps: str :returns: list str """ return ["<comp({})>".format(c) for c in comps]
def _splitext(p, sep, altsep, extsep): """Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.""" sepIndex = p.rfind(sep) if altsep: altsepIndex = p.rfind(altsep) sepIndex = max(se...
def get_device_name_prefix(device_name): """Return device name without device number. /dev/sda1 -> /dev/sd /dev/vda -> /dev/vd """ dev_num_pos = 0 while '0' <= device_name[dev_num_pos - 1] <= '9': dev_num_pos -= 1 return device_name[:dev_num_pos - 1]
def numPositionsInRing(ring): """Number of positions in ring (starting at 1) of a hex lattice.""" return (ring - 1) * 6 if ring != 1 else 1
def epsilon(T): """ stepwise linear annealing """ M = 1000000 if T < M: return 1 - 0.9 * T / M if T < 2 * M: return 0.1 - 0.09 * (T - M) / M return 0.01
def DFS_Shortest_Path(graph, start, end, path = [], shortest = None): """ Depth First Search to find the shortest path """ path = path + [start] # path found - termination case if start == end: return path # check if start not in edge if not start in graph.keys(): return None ...
def start_smash(stage=None, game_type=None): """Provides information to start the game in smash mode. The function takes the parameters to set the stage and game type. It checks whether any arguments were passed to these parameters and returns an f-string based on the parameters passed. Parameters:...
def get_group_dict (configuration: dict) -> dict: """ Returns the dictionary of all groups. Parameters: configuration (dict) : configuration from `trex.json` Returns: group_dict (dict) : dictionary of groups """ group_dict = {} for k ...
def get_domain_label(domain): """ "." is not a valid character in a prometheus label and the recommended practice is to replace it with an "_". """ return domain.replace('.', '_')
def dfdz_PReLU(z, alpha): """Derivative of the parametric rectified linear unit function... Args: z (np.array) Returns: df(z)/dz = 1 if x > 0 else alpha (np.array) """ return 1.0 * (z > 0) + alpha * (z <= 0)
def _bunnies_info(container): """extract bunnies information from container information in job""" if not container: return None env = container.get('environment', None) if not env: return None info = { 'BUNNIES_JOBID': None, 'BUNNIES_VERSION': None, 'BUNNIES_...
def turnCard(indexValue, myBoard): """Return the value of a guessed card.""" cardname = myBoard[indexValue] return cardname
def hamming(seq1, seq2): """ Returns hamming distance between two sequences Parameters ---------- seq1 : query sequence seq2 : reference sequence Returns ------- integer hamming distance between query sequence and reference sequence """ return sum(1 for ch1, ch2 in...
def escape_latex(string): """ Get string, where reserved LaTeX charachters are escaped. For more info regarding LaTeX reserved charachters read this: https://en.wikibooks.org/wiki/LaTeX/Basics#Reserved_Characters """ string = string.replace("\\", "\\\\") string = string.replace("&", r"\&") ...
def get_optimal_bin_size(n, round=True): """Helper function to calculate optimal binning This function calculates the optimal amount of bins for the number of events n. Args: n (int): number of events to be binned round (bool or int): Round to Returns: (int): Optimal number of ...
def end_chat(input_string): """ Takes user input and checks if equal to 'quit' or 'exit' Function taken from A3 Input: string Output: boolean """ for i in input_string: if i == 'quit' or i == 'exit': return True else: return False
def removeModifications(peptide): """Removes all modifications from a peptide string and return the plain amino acid sequence. :param peptide: peptide sequence, modifications have to be written in the format "[modificationName]" :param peptide: str :returns: amino acid sequence of ``peptid...
def find_last_break(times, last_time, break_time): """Return the last index in times after which there is a gap >= break_time. If the last entry in times is further than signal_separation from last_time, that last index in times is returned. Returns -1 if no break exists anywhere in times. """ i...
def noneOrValueFromStr(s): """Return `None` if `s` is '' and the string value otherwise Parameters ---------- s : str The string value to evaluate Return ------ `None` or the string value """ r = None if not s or not s.strip() or s.upper() == 'NONE' else s return r
def _keys_sorted_by_values(adict): """Return list of the keys of @adict sorted by values.""" return sorted(adict, key=adict.get)
def index_to_point(index, origin, spacing): """Transform voxel indices to image data point coordinates.""" x = origin[0] + index[0] * spacing[0] y = origin[1] + index[1] * spacing[1] z = origin[2] + index[2] * spacing[2] return (x, y, z)
def char_at(s, index): """ Return the str[index] in int class. Args: s: index: Returns: value (int): the int value of s[index], -1 for IndexError. """ if index < len(s): value = ord(s[index]) else: value = -1 return value
def vowel_count(phrase): """Return frequency map of vowels, case-insensitive. >>> vowel_count('rithm school') {'i': 1, 'o': 2} >>> vowel_count('HOW ARE YOU? i am great!') {'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1} """ my_return = {} for letter in phrase: if my_re...
def format_text_overview(r_actual, text, total, url=''): """ Formats text for the learner overview """ if r_actual is None: # It has not been started yet return text, total else: if r_actual.status in ('C', 'L'): score = int(r_actual.score) return '{0}<a href=...
def song_length(len_s): """ return formatted string for time given a value in seconds """ m, s = divmod(int(len_s), 60) s = str(s) if s > 9 else '0' + str(s) return ':'.join([str(m), s])
def count_clues(puzzle_grid): """Counts clues in a puzzle_grid, which can be a list of lists or string.""" if isinstance(puzzle_grid, list): return sum([1 for sublist in puzzle_grid for i in sublist if i]) return len(puzzle_grid) - puzzle_grid.count(".")
def format_output(outputs): """ The output is of the form {layer_name: blob} Return a list of blobs in _increasing_ id order of layer_name suffix, which maps onto how ConcatTable, etc return their outputs (in the multi output case) Consider that the layer name is of form <name>_<id> and sort b...
def tagsContain(f_tn, ec2_dict): """ Similar to isitfit.cost.ec2_common.tagsContain """ if ec2_dict['Tags'] is None: return False if len(ec2_dict['Tags']): return False for t in ec2_dict['Tags']: for k in ['Key', 'Value']: if f_tn in t[k].lower(): return True return False
def _check_output_repeat(msg, output): """ Return True if a message fully constists of output. Otherwise return False. Parameters ---------- msg: Union[bytes, str] A message. output: Union[bytes, str] An output. """ if len(msg) < 1 or len(output) < 1: return F...
def create_city_map(n: int) -> set: """ Generate city map with coordinates :param n: defines the size of the city that Bassi needs to hide in, in other words the side length of the square grid :return: """ return set((row, col) for row in range(0, n) for col in range(0, n))
def has_valid_dimension(l, d=None): """Check congruent dimensions in a two-dimensional list.""" if not l: return False if d is None: d = len(l[0]) for sub in l: if len(sub) != d: return False return True
def pirepFcn(table, doc): """Create and return partial key for PIREP messages. Args: table (str): Database table. doc (dict): Message from database. Returns: str: With partial key for ``vectorDict``. """ return 'PIREP~' + doc['report_type'] + '-' + doc['station'] + '-' + do...
def irc_de_projected(step_size, grad, hess): """ Compute anticipated energy change along one dimension """ return step_size * grad + 0.5 * step_size * step_size * hess
def get_acres(grid, coordinates): """Get acres from coordinates on grid.""" acres = [] for row, column in coordinates: if 0 <= row < len(grid) and 0 <= column < len(grid[0]): acres.append(grid[row][column]) return acres
def func_test(args): """ TU """ from random import random print(args) # Crash ? for _ in range(99999): _ = 3^80 return random() > 0.01
def exception_handler(error): """ :return str(): red formatted error name and args """ return f"{type(error).__name__} {error.args}"
def normalize_ps( patch_sequence ): """Given an sequence of ROPath deltas, remove blank and unnecessary The sequence is assumed to be in patch order (later patches apply to earlier ones). A patch is unnecessary if a later one doesn't require it (for instance, any patches before a "delete" are unne...
def identify_correct_partition_idx(array, begin_idx, end_idx): """ This function looks at the element of array[end_idx] and then it identifies its correct position index in a sorted array such that everything to left is smaller or equal, and everything to right is larger. Reference: https://www.you...
def list_func(data, member='name'): """Used for state=list.""" return [getattr(x, member) for x in data]
def _list_of_command_args(command_args, conf_args_dict): """ Creates a reduced list of argument-only commands from the namespace args dictionary by removing both non-argument commands and None arguments from the namespace args. Parameters ---------- command_args(dict): A dictionary object tha...
def normalisation_min_max(list_of_values): """ Will normalise a list to be between 0 and 1 :param list_of_values: A list of numeric values :type list_of_values: list[int] | list[float] :return: A list of values between zero and 1 :rtype: list[float] """ value_min = min(list_of_values)...
def maybe_cast_list(value, types): """ Try to coerce list values into more specific list subclasses in types. """ if not isinstance(value, list): return value if type(types) not in (list, tuple): types = (types,) for list_type in types: if issubclass(list_type, list): ...
def isseq(x): """Returns True if x is a list or tuple.""" return isinstance(x, (list, tuple))
def set_device_orientation_override(alpha: float, beta: float, gamma: float) -> dict: """Overrides the Device Orientation. Parameters ---------- alpha: float Mock alpha beta: float Mock beta gamma: float Mock gamma **Experimental** """ return { ...
def plural(how_many): """Construct postfix for singular or plural.""" if how_many > 1 or how_many == 0: return "s" return ""
def gather_loss(loss_dict: dict, loss_weight: dict): """Gather overall loss and compute mean of individual losses. Args: loss_dict (dict): individual loss terms loss_weight (dict): weights for each loss, only the loss with valid weight will be meaned. """ loss = 0.0 sca...
def arrow_style(val): """ Defines styling for badges (ui elements) Args: val: float (positive or negative) Returns: background-color, color, class for font awesome icons """ if round(val, 1) < 0: return "#50B1A2", "#fff", "down" if round(val, 1) > 0: return "#C3043E...
def estimate_probability(word, previous_n_gram, n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0): """ Estimate the probabilities of a next word using the n-gram counts with k-smoothing Args: word: next word previous_n_gram: A sequence of words of len...
def int_to_bool_list(number: int, byte_like: bool = False, reverse: bool = False): """ Convert Integer to List of Booleans. This function converts an integer to a list of boolean values, where the most significant value is stored in the highest point of the list. That is, a...
def retrieve_request_body(request_index: int, html): """Returns default request body from API_GUIDANCE.md file""" request_body = "" a = "" body = False for _ in range(request_index, len(html)): if html[_] != " ": if body is False: a = a + html[_] elif body...
def extract_bits(n, n_bits, offset_from_lsb): """Extract a number of bits from an integer. Example: >>> bin(extract_bits(0b1101011001111010, n_bits=5, offset_from_lsb=7)) '0b1100' 0b1101011001111010 -> 0b01100 ^^^^^<- 7 -> The bits marked with ^ will be extracted. The offset...
def calculateScale(w, h, min_x, max_x, min_y, max_y): """ returns scale factor between route bounds (dx,dy) and the canvas """ dx = max_x - min_x dy = max_y - min_y scale = dy if dx < dy else dx scale_x = float(w)/scale scale_y = float(h)/scale return scale_x, scale_y
def delete_document_on_mongo(collection, query): """ Deletes a single document to the collection Args: collection (Collection): collection object to insert the document query (dictionary): Query used to find the object and delete it in the collection Returns: bool: True if document...
def initial_node(nodes): """ Return node ID of node with smallest _ID identifier. :param nodes: graph 'nodes' object :return: node ID """ minid = min([n['_id'] for n in nodes.values()]) for node, attr in nodes.items(): if attr['_id'] == minid: return n...
def longestConsecutive(nums): """ :type nums: List[int] :rtype: int """ arr_set = set(nums) to_return = 0 for elem in arr_set: if elem-1 in arr_set: continue curr_val, max_streak = elem, 0 while curr_val in arr_set: max_streak += 1 ...
def get_labels_auto(file_list, seperator = '_'): """ If files are labelled in this format: Name_Yead_{LABEL}.ply where {LABEL} is the label or Folder_Name/{LABEL}.ply This function will return the {LABEL} from the filename """ label_list = [] for file in file_list: print(file) ...
def floatToStr(number: float, showNumOfDigits: int = 2) -> str: """ Convert float number with any number of decimal digits and return string with ``showNumbOfDigits`` places after ``.``. Args: number: float number to convert to string. showNumOfDigits: number of decimal places (characters)...
def unescape_str(a_string: str, uri: bool = False) -> str: """Iterative parser for string escapes. """ out = '' while len(a_string) > 0: char = a_string[0] if char == '\\': # Backslash escape esc_c = a_string[1] if esc_c in ('u', 'U'): ...
def tree_pos_height(pos: int) -> int: """ calculate pos height in tree Explains: https://github.com/mimblewimble/grin/blob/0ff6763ee64e5a14e70ddd4642b99789a1648a32/core/src/core/pmmr.rs#L606 use binary expression to find tree height(all one position number) return pos height """ # conver...
def check_year_increment(first_step_data, current_step_data): """Check if year value should be incremented inside environment table.""" if first_step_data is current_step_data: # do not increment first step return False return first_step_data >= current_step_data
def str_manipulation(s): """ This function turns all the alphabet into lower case. ---------------------------------------------------------------------------- :param s: (str) the word that user input. :return: ans (str), the word with the lower case. """ ans = '' for ch in s: if ch.isupper(): ans += ch.lo...
def dict_to_msg(input_dict): """ Unfold a nested dictionary to a string. To the maximum of 3 levels. """ msg = "" for ikey, ivalue in input_dict.items(): if isinstance(ivalue, dict): msg += f"{ikey}:\n" for iikey, iivalue in ivalue.items(): if isin...
def items(dct_or_lst): """Returns list items, or dictionary items""" if isinstance(dct_or_lst, dict): return list(dct_or_lst.items()) return list(enumerate(dct_or_lst))
def render_response_v1(response, version=2): """ Renders a response into version 1 compatible format response: a dict to convert version: the version of the response """ if version == 2: status = response.get("status") data = response.get("message...
def _normalizeImpurityMatrix(matrix): """Normalize each row of the matrix that the sum of the row equals 1. :params matrix: a matrix (2d nested list) containing numbers, each isobaric channel must be present as a row. :returns: a matrix containing normalized values """ newMatrix = list() ...
def IsDash(s: str, index: int) -> bool: """Verifies that character at index of string is '-'. Args: s (str): string to be examined. index (int): starting index of the possible '-' character. Return: (boolean): true or false to if the value is valid. ...
def _Remap(x, x0, x1, y0, y1): """Linearly map from [x0, x1] unto [y0, y1].""" return y0 + (x - x0) * float(y1 - y0) / (x1 - x0)
def getCounts(IDandRatingsTuple): """ Calculate average rating Args: IDandRatingsTuple: a single tuple of (MovieID, (Rating1, Rating2, Rating3, ...)) Returns: tuple: a tuple of (MovieID, number of ratings) """ return (IDandRatingsTuple[0], len(IDandRatingsTuple[1]))
def _create_expanded_value(value, isExpanded): """Creates a JSON serializable dictionary matching the `BazelExpandedValue` type in the test runner.""" return { "value": value, "containsExpansion": isExpanded, }
def _get_var_name(name): """Convert a parameter name to a var_name. Example: 'alpha[0,1]' return 'alpha'.""" if name[-1] != "]": return name ind = name.rfind("[") if ind == 0 or ind == len(name) - 1: return name substr = name[ind + 1 : -1] if len(substr) == 0: retur...
def _color_message(message, colour_start='\033[31m'): """ Colourize message using ANSI escape codes """ colour_end = '\033[0m' return f'{colour_start}{message}{colour_end}'
def anglicize1to19(n): """ :return: English equivalent of n precondition: 0 < n < 20 """ if n == 1: return 'one' elif n == 2: return 'two' elif n == 3: return 'three' elif n == 4: return 'four' elif n == 5: return 'five' elif n == 6: ...
def selection_sort(array): """ Def: Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simpli...
def number_to_bytearray(number, size): """Convert a number to a bytearray Args: number (int): the number to convert size (int): the size of the bytearray of the result Returns: bytearray: the resulting byte array """ array = bytearray() for i in range(size): num...
def decode(line): """Takes bytes and returns unicode. Tries utf8 and iso-8859-1.""" try: return str(line, 'utf8') except UnicodeDecodeError: return str(line, 'iso-8859-1') except TypeError: # Already unicode return line
def _get_intent(frame): """Returns the top intent label.""" return frame.split("-")[0]
def encode_string(string): """Encode String Data Type. The "string" data type encodes binary data as a sequence of undistinguished octets. Where the range of lengths for a particular attribute is limited to a subset of possible lengths, specifications MUST define the valid range. Attributes with le...
def min_value(digits): """Apply string join approach.""" sorted_digits_ls = sorted(set(digits)) lst = [] for d in sorted_digits_ls: lst.append(str(d)) return int(''.join(lst))
def get_heating_period(heat_level, day_period, current_temp, base_level, circuit_data): """ Calculates the length in seconds to heat the specific circuit :param heat_level: The heat level (0-1) from the external temperature :param day_period: The heating period - 1 (night) or 2 (day) :param current_...
def bool_to_str(val: bool) -> str: """Convert a boolean into a yes/no value.""" return "yes" if val else "no"
def get_unique_values(local_data, attr): """ Given data set and attribute, returns unique values that the attribute takes """ values = [] for element in local_data: if element[attr] not in values: values.extend([element[attr]]) return values
def _front_left_tire_pressure_supported(data): """Determine if front left tire pressure is supported.""" return data["status"]["tirePressure"]["frontLeftTirePressurePsi"] is not None
def TwoToOneDim(xycoord, dimensions): """ 2D --> 1D Args: xycoord : tuple dimensions : tuple with image width and height """ return xycoord[0] + (dimensions[0] * xycoord[1])
def get_star_column_info(line, column): """ For a given .STAR file line entry, extract the data at the given column index. If the column does not exist (e.g. for a header line read in), return 'False' """ # break an input line into a list data type for column-by-column indexing line_to_list = li...