content
stringlengths
42
6.51k
def _deep_get(instance, path): """ Descend path to return a deep element in the JSON object instance. """ for key in path: instance = instance[key] return instance
def binomial_coeff_nested_conditionals(n, k): """Original rewritten using nested conditional expressions. """ return 1 if k==0 else 0 if n == 0 else (binomial_coeff_nested_conditionals(n-1, k) + binomial_coeff_nested_conditionals(n-1, k-1))
def clamp(value, min_value, max_value): """Clamps a value witin the bound [min_value, max_value] Returns ------- float """ if min_value > max_value: raise ValueError("min_value must be bigger than max_value") return float(min(max(value, min_value), max_value))
def append_reverse(n=int(1e4)): """Assemble list with `append` and `reverse`. """ L = [] for x in range(n): L.append(x) L.reverse() return L
def format_filesize(num, suffix='B'): """ See: https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) ...
def RL(text, cb=None): """Convenience function returning a readline test expectation.""" return { "name": "readline", "args": [], "ret": text, "cb": cb, "cwd": None, }
def valid(node, min_value, max_value): """Iteratively validate BST""" if node is None: return True if node.value <= min_value or node.value >= max_value: return False return valid(node.left, min_value, node.value) and valid(node.right, node.value, max_value)
def getTriangleCentroid(x1, y1, x2, y2, x3, y3): """ Return the x and y coordinates of a triangle's centroid. Parameters ---------- x1 : float x coordindate of first point defining a triangle y1 : float y coordindate of first point defining a triangle x2 : float x co...
def pocock_cutoff(K, alpha): """ Returns the cutoff value for Pocock's Test Arguments: K: An integer less than 10. alpha: The alpha level of the overall trial (0.01, 0.05 or 0.1). Returns: cutoff: The value of \(C_P(K, \alpha)\) for the study. Note: Since there is no c...
def playfair_deal_with_dups(text): """playfair can't deal with conseuctive letters being duplicated, this adds in an X between conseuctive duplciated letters Args: text ([str]): plain text to get rid of dups Returns: [message]: list of text with the X's added where there are conseuctiv...
def get_formatted_amount(order_amount): """ Returns the decimal order_amount in the format expected by RedSys. Example: 20,00 -> 2000 """ return int(round(float(order_amount) * 100))
def prep_available_bundle(device, npc): """ Prepare bundle query XML. :param device: Hexadecimal hardware ID. :type device: str :param npc: MCC + MNC (see `func:bbarchivist.networkutils.return_npc`) :type npc: int """ query = '<?xml version="1.0" encoding="UTF-8"?><availableBundlesRequ...
def to_percentage(number): """ Formats a number as a percentage, including the % symbol at the end of the string """ return "{:.2%}".format(number)
def unpack_singleton(x): """Gets the first element if the iterable has only one value. Otherwise return the iterable. # Argument x: A list or tuple. # Returns The same iterable or the first element. """ if len(x) == 1: return x[0] return x
def time_to_sample(time_, samplerate): """Return sample index closest to given time. Args: time (float): Time relative to the start of sample indexing. samplerate (int): Rate of sampling for the recording. Returns: sample (int): Index of the sample taken nearest to ``time``. ""...
def all_equal(arg1,arg2): """ Return a single boolean for arg1==arg2, even for numpy arrays. Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise. """ try: return all(a1 == a2 for a1, a2 in zip(arg1, arg2)) except TypeError: return arg1==arg2
def genpass(pwds_amount=1, paswd_length=8): """ Returns a list of 'pwds_amount' random passwords, having length of 'paswd_length' """ import random return [ ''.join([chr(random.randint(32, 126)) for _ in range(paswd_length)]) for _ in range(pwds_amount)]
def last_not_in_set(seq, items): """Returns last occurrence of any of items in seq, or None. NOTE: We could do this slightly more efficiently by iterating over s in reverse order, but then it wouldn't work on generators that can't be reversed. """ found = None for s in seq: if s...
def normalize_judge_names(name): """Cleans up little issues with people's names""" out = [] words = name.split() for i, w in enumerate(words): # Michael J Lissner --> Michael J. Lissner if len(w) == 1 and w.isalpha(): w = '%s.' % w # Michael Lissner Jr --> Michael Li...
def safe_eval(expression): """Safely evaluates a mathematical expression. (Exists because I couldn't find a way to allow CL parameters to be expressions - ideally needs a better solution.) Parameters ---------- expression: str Mathematical expression in s...
def merge_sort(arr): """ Returns the list 'arr' sorted in nondecreasing order in O(nlogn) time. """ r = len(arr) if 1 < len(arr): q = int(r/2) L = merge_sort(arr[0:q]) R = merge_sort(arr[q:]) print(L,R) i,j,k = 0,0,0 while i < len(L) and j < len(R): ...
def path_join(p1: str, p2: str): """Helper to ensure there is only one '/' between two strings""" return '{}/{}'.format(p1.rstrip('/'), p2.lstrip('/'))
def is_numeric(obj): """ Checks to see object is numeric. Args: obj (object) Returns: Boolean """ try: float(obj) return True except: return False
def triangle_number(nth): """Returns the nth triangular number""" return nth * (nth + 1) / 2
def build_id(Z: int, A: int, state: str = "") -> int: """ Builds a canonical nuclide id from atomic number, atomic mass, and and energy state. Parameters ---------- Z : int Atomic number. A : int Atomic mass. state : str energy state. Returns ------- ...
def add_with_saturation_bad(a, b, c=10): """ add_with_saturation add with saturation """ return min(a+b, c)
def decode_number(value, float_factory): # type(string) -> (int) """ Decode string to integer and guess correct base :param value: string input value :return: integer """ value = value.strip() if '.' in value: return float_factory(value) base = 10 if len(value) > 1 and va...
def find_duplicates(arr): """ find the duplicates in a list :param arr: list to search :return: list containing unique duplicate elements """ cache = {} dupe = {} for e in arr: try: cache[e] # raise an error if not found dupe[e] = 1 # mark as a duplicat...
def bearerAuthHeader(auth_string): """ Build the bearer token authentication header of HTTP request. : param auth_string: the authentication string containing the OAuth token. : return: the 'Bearer token' authorization header. """ token = auth_string auth_header = 'Bearer {0}'.format(token) return auth_he...
def exercise_5(inputs): # DO NOT CHANGE THIS LINE """ This functions receives the input in the parameter 'inputs'. Change the code, so that the output is sqaure of the given input. Output should be the name of the class. """ output = inputs return output # DO NOT CHANGE THIS LINE
def rev_comp(seq: str) -> str: """ Generates the reverse complement of a sequence. """ comp = { "A": "T", "C": "G", "G": "C", "T": "A", "B": "N", "N": "N", "R": "N", "M": "N", "Y": "N", "S": "N", "W": "N", "K...
def toTupple(obj): """ Converts recursively to tuple :param obj: numpy array, list structure, iterators, etc. :return: tuple representation obj. """ try: return tuple(map(toTupple, obj)) except TypeError: return obj
def lookup(name, namespace): """ Get a method or class from any imported module from its name. Usage: lookup(functionName, globals()) """ dots = name.count(".") if dots > 0: moduleName, objName = ".".join(name.split(".")[:-1]), name.split(".")[-1] module = __import__(moduleName) ...
def _amount(amount, asset='HBD'): """Return a steem-style amount string given a (numeric, asset-str).""" assert asset == 'HBD', 'unhandled asset %s' % asset return "%.3f HBD" % amount
def format_ml_code(code): """Checks if the ML code ends with the string 'model = ' in its last line. Otherwise, it adds the string. Args: code (str): ML code to check Returns: str: code formatted """ return code[:code.rfind('\n')+1] + 'model = ' + code[code.rfind('\n...
def find_common_left(strings): """ :param list[str] strings: list of strings we want to find a common left part in :rtype: str """ length = min([len(s) for s in strings]) result = '' for i in range(length): if all([strings[0][i] == s[i] for s in strings[1:]]): result += strings[0][i] else: break retur...
def sao_anagramas(frase1, frase2): """ Funcao que identifica anagramas :param frase1: :param frase2: :return: True se frase1 e frase2 sao anagramas e False caso contrario """ # eliminar espacos em branco frase1 = frase1.replace(' ', '') frase2 = frase2.replace(' ', '') # compar...
def mini_batch_weight(batch_idx: int, num_batches: int) -> float: """Calculates Minibatch Weight. A formula for calculating the minibatch weight is described in section 3.4 of the 'Weight Uncertainty in Neural Networks' paper. The weighting decreases as the batch index increases, this is because th...
def unescape(s): """Excel save as tsv escaped all '"' chars - undo that!""" if len(s) < 2: return s if s[0] == '"' and s[-1] == '"': return s[1:-1].replace('""', '"') return s
def number_of_batches(total, sizeperc): """ :param data: :param sizeperc: size of a batche expressed as a percentage of the total data (between 0 and 1) :return: """ if sizeperc > 1: raise ValueError('sizeperc must be between 0 and 1') if sizeperc < 0: raise ValueErr...
def take(list_, index_list): """ Selects a subset of a list based on a list of indices. This is similar to np.take, but pure python. Args: list_ (list): some indexable object index_list (list, slice, int): some indexing object Returns: list or scalar: subset of the list ...
def safe_to_bool(input): """ Safely convert user input to a boolean, throwing exception if not boolean or boolean-appropriate string For flexibility, we allow case insensitive string matching to false/true values If it's not a boolean or string that matches 'false' or 'true' when ignoring case, throws a...
def valid_distance(dist_m): """check that distance is: * non-negative * an integer * devisable by 100 * above 3000 """ if type(dist_m) != int: return False if 0 < dist_m < 3000: return False if dist_m % 100 != 0: return False return True
def virtual_machine_names_to_container_names(configuration): """ convert virtual machine names to container names using configuration Args: configuration: user final configuration Returns: list of container name in array """ return [ "{0}_{1}".format(configuration[select...
def factor_size(value, factor): """ Factors the given thumbnail size. Understands both absolute dimensions and percentages. """ if type(value) is int: size = value * factor return str(size) if size else '' if value[-1] == '%': value = int(value[:-1]) return '{0}%...
def maskify(cc): """return masked string""" le = len(cc) if le < 5: return cc else: return "#" * (le - 4) + cc[le - 4:]
def unescape_tokenized_text(s: str) -> str: """ Remove some escaped symbols introduces by moses tokenizer that are unneeded """ s = s.replace("&apos;", "'") s = s.replace("&quot;", "\"") s = s.replace("&#91;", "[") s = s.replace("&#93;", "]") return s
def intersects(left, right): """ Returns true if two rectangles overlap """ (xl, yl, wl, hl) = left (xr, yr, wr, hr) = right return not ((xl + wl) < xr or xl > (xr + wr) or yl > (yr + hr) or (yl + hl) < yr)
def ensure_iob2(tags): """Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2. """ tags = list(tags) for i, tag in enumerate(tags): if tag == 'O': continue split = tag.split('-') if len(split) != 2 or split[0] not in ['I', 'B']: ...
def is_sorted(s: str) -> bool: """Is s a sorted string?""" return list(s) == sorted(s)
def collapse_list(l, empty = '.'): """ Concatena todas las cadenas de la lista en una sola lista """ collapsed = '' for elt in l: if elt == None: collapsed = collapsed + empty else: collapsed = collapsed + elt return collapsed
def _gendesc(infiles): """ Generate a desc entity value. Examples -------- >>> _gendesc("f") 'coeff' >>> _gendesc(list("ab")) ['coeff0', 'coeff1'] """ if isinstance(infiles, (str, bytes)): infiles = [infiles] if len(infiles) == 1: return "coeff" retur...
def number_of_differences(str1, str2): """ >>> str1 = str2 = 'ABABABABAB' >>> assert(number_of_differences(str1, str2) == 0) >>> str1, str2 = 'ABABABABAB', 'BABABABABA' >>> assert(number_of_differences(str1, str2) == 10) >>> str1, str2 = 'SOSSPSSQSSOR', 'SOSSOSSOSSOS' >>> assert(number_of_di...
def general_calculation(table, targets): """Returns the sum of all targets unit values, if the id is unknown, add it as value 1""" total = 0 for enemy in targets: table.setdefault(enemy.type_id, 1) total += table[enemy.type_id] return total
def compare_val(expected, got): """ Compare values, throw exception if different. """ if expected != got: raise Exception("expected '%s', got '%s'" % (expected, got)) return True
def howmany(bit): """ how many values are we going to pack? """ return 32 #number = (64+bit-1)/bit #while((number * bit) % 8 != 0): # number += 1 #return number
def kernel_sigmas(n_kernels): """ get sigmas for each guassian kernel. :param n_kernels: number of kernels (including exactmath.) :param lamb: :param use_exact: :return: l_sigma, a list of simga """ bin_size = 2.0 / (n_kernels - 1) l_sigma = [0.001] # for exact match. small variance...
def line_segment_intersection(a, b, c, d): """Checks if two lines intersect. Args: a (list): Point 1 of Line 1 b (list): Point 2 of Line 1 c (list): Point 1 of Line 2 d (list): Point 2 of Line 2 Returns: (bool) True if there is an intersection, otherwise False. ...
def str2bool(v): """Function For converting unicode values to bool""" print('Entering conversion function') return v.lower() in ("yes", "true", "t", "1")
def partition_names_by_comp(names): """Take an iterator of names and return a tuple of the form (namelist, compmap) where namelist is a list of simple names (no dots) and compmap is a dict with component names keyed to lists of variable names. """ simple = [] compmap = {} for name in names: ...
def fix_desc(desc, units=None): """Clean up description column.""" full_desc = desc.strip() if units and units != 'N/A': if full_desc: full_desc += ' (' + units + ')' else: full_desc = units return full_desc
def first_word(s): """Returns the first word in a string""" return s.split()[0]
def smallest_square(n: int): """ returns the smallest int square that correspond to a integer example: smallest_square(65) returs 8 (8*8 = 64) """ n = abs(n) i = 0 while i**2 <= n: i += 1 if n - (i-1)**2 < i**2 - n: return i - 1 else: return i
def convert_time(_time) -> str: """ Convert time into a years, hours, minute, seconds thing. """ # much better than the original one lol # man I suck at docstrings lol try: times = {} return_times = [] time_dict = { "years": 31536000, "months": 262...
def lerp(x0, x1, t): """ Linear interpolation """ return (1.0 - t) * x0 + t * x1
def channel_to_gauge_names(channel_names: list) -> list: """ Replace the channel names with gauge locations. """ gauges = {"CH 1": "Main", "CH 2": "Prep", "CH 3": "Backing"} return [gauges.get(ch, ch) for ch in channel_names]
def explode_entity_name(entity_name: str) -> str: """ replaces _ with space """ return entity_name.replace('_', ' ')
def to_ascii(text): """ Force a string or other to ASCII text ignoring errors. Parameters ----------- text : any Input to be converted to ASCII string Returns ----------- ascii : str Input as an ASCII string """ if hasattr(text, 'encode'): # case for existin...
def dict_get_nested(d, key): """Get a (potentially nested) key from a dict-like.""" if '.' in key: key, rest = key.split('.', 1) if key not in d: raise KeyError(key) return dict_get_nested(d[key], rest) else: if key not in d: raise KeyError(key) ...
def is_printable(str1, codec='utf8'): """ Returns True if s can be decoded using the specified codec """ try: str1.decode(codec) except UnicodeDecodeError: return False else: return True
def str_to_hexstr(s): """Convert a string into an hexadecimal string representation""" if type(s) is not str: s = chr(s) return ":".join("{:02x}".format(ord(c)) for c in s)
def solar_elevation_corrected_atm_refraction( approx_atmospheric_refraction, solar_elevation_angle ): """Returns the Solar Elevation Corrected Atmospheric Refraction, with the Approximate Atmospheric Refraction, approx_atmospheric_refraction and Solar Elevation Angle, solar_elevation_angle.""" sol...
def known_face_sentence(known_face_name): """ describe known person Example: Anuja is in front of you. :param known_face_name: name of known person in the frame :return: sentence descibing person """ return "%s in front of you" % ( known_face_name )
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(" ") return words
def bigger_price(limit: int, data: list) -> list: """ TOP most expensive goods """ result = sorted(data, key=lambda k: k["price"], reverse=True) return result[:limit]
def _check_consistency_sizes(list_arrays) : """Check if all arrays in list have the same size Parameters: ----------- list_arrays: list of numpy arrays Return ------ bool: True if all arrays are consistent, False otherwise. """ if len(list_arrays) == 0 : return True re...
def filter_folder_path(path): """ This function will filter out \\..\\ or \\ at the begining. Also if path becomes empty, . will be used """ local_search_path = path local_search_path = local_search_path.replace('\\..\\', '\\') local_search_path = local_search_path.replace('/../', '/') if local_sear...
def _anharm_zpve_from_scaling(freq, scaled_freq): """ Determine what the anharmonic ZPVE should be after scaling """ return (freq / 2.0) - (1.0 / 8.0) * (scaled_freq - freq)
def _get_testm_tree(ind): """Generate a fake package with submodules We need to increment index for different tests since otherwise e.g. import_modules fails to import submodule if first import_module_from_file imports that one """ return { 'dltestm%d' % ind: { '__init__.py'...
def get_registry_for_env(environment: str) -> str: """ Mapping of container registry based on current environment Args: environment (str): Environment name Returns: str: Connect registry for current """ env_to_registry = { "prod": "registry.connect.redhat.com", ...
def number_of_lottery_tickets_by_veet_units(veet_units): """ Function to calculate the number of lottery tickets to assign for each participants based on veet units. Args: veet_units (int): count of veet units """ veet_units = int(veet_units) max_ticket_to_assign = 15 veet_tic...
def sort_012(arr): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: arr(list): List to be sorted """ if arr is None: return arr zero_index = 0 current_index = 0 two_index = len(arr) - 1 while current_index < len(arr...
def get_file_list_based_on_suffix(file_list, suffix): """Get filenames ending with the given suffix.""" match_list = [] for fid in file_list: fid = str(fid) # MW: To also allow fid to be of type pathlib.Path if '~$' in fid: # memory prefix when a file is open contin...
def remove_invalid_resource_name_charaters( # pylint: disable=invalid-name str_to_process: str, ) -> str: """Remove characters that would be invalid in certain cases (e.g. DNS).""" remove_these_chars = ["'", '"', "%", "$", "`"] out_str = "" for this_char in str_to_process: if this_char in ...
def utf8_decoder(s): """ Decode the unicode as UTF-8 """ if s is None: return None return s.decode('utf-8')
def observed_name(name): """Return `_name_observed`.""" return "_{}_observed".format(name)
def remove_scale_offset(value, scale, offset): """Remove scale and offset from the given value""" return (value * scale) - offset
def touching(pos1, pos2): """ tells you if two positions are touching """ if pos1[0] == pos2[0] and abs(pos1[1] - pos2[1]) == 1: return True if pos1[1] == pos2[1] and abs(pos1[0] - pos2[0]) == 1: return True return False
def has_double_letters(text): """Check if text has any double letters""" # Check if any two successive letters are the same, # and return True if they are, of False if there aren't any. for i in range(len(text) - 1): if text[i] == text[i + 1]: return True return False
def setlist(L): """ list[alpha] -> set[alpha] """ # E : set[alpha] E = set() # e : alpha for e in L: E.add(e) return E
def get_data(payload_for_geo): """ Returns the full timeseries data as from a DataCommons API payload. Args: payload_for_geo -> The payload from a get_stats call for a particular dcid. Returns: The full timeseries data available for that dcid. """ if not payload_for_...
def http_error_handler(error): """Default error handler for HTTP exceptions""" return ({"message": str(error)}, getattr(error, "code", 500))
def longest_increasing_subsequence(X): """Returns the Longest Increasing Subsequence in the Given List/Array""" N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): ...
def _package_variables(variables, check_type): """ Removes token and customer id and adds check type to dict data Removes the token from the dictionary that will be sent to NodePing in JSON format as well as the customer id since these aren't a part of the check data. Also adds the check type. :ty...
def _check_preferred_compat_mode(preferred_mode, supported_modes): """Checks whether the LPAR's preferred mode is supported :param preferred_mode: preferred compat mode of the LPAR :param supported_modes: proc compat modes supported by the dest host :returns: True if the preferred mode is supp...
def lerp1d(a: float, b: float, r: float) -> float: """Returns a point interpolated from a to b, at r.""" return a + (b - a) * r
def do_steps_help(cls_list): """Print out the help for the given steps classes.""" for cls in cls_list: print(cls.help()) return 0
def replace_nones_in_dict(target, replace_value): """Recursively replaces Nones in a dictionary with the given value.""" for k in target: if target[k] is None: target[k] = replace_value elif type(target[k]) is list: result = [] for e in target[k]: ...
def range_spec(x, y): """ range_spec """ for _ in range(1, 10, 3): x = x + 1 return x + y
def compare_config(module, kwarg_exist, kwarg_end): """compare config between exist and end""" dic_command = {'isSupportPrmpt': 'lacp preempt enable', 'rcvTimeoutType': 'lacp timeout', # lacp timeout fast user-defined 23 'fastTimeoutUserDefinedValue': 'lacp timeout user-de...