content
stringlengths
42
6.51k
def before_send_to_sentry(event, hint): """Edit event properties before logging to Sentry Docs: https://docs.sentry.io/error-reporting/configuration/filtering/?platform=python#before-send """ # Report a general logger name (`ingest_pipeline`) to Sentry, # rather than the function-specific logger na...
def _validate_padding(padding): """Verify correctness of `padding` argument.""" padding_ = str(padding).upper() if padding_ in {'SAME', 'VALID'}: return padding_ raise ValueError( 'Argument padding="{}" not recognized; must be one of ' '{{"VALID", "SAME"}} (case insensitive).'.format(padding))
def egcd(a, b): """Calculate greatest common divisor of two numbers. This implementation uses a recursive version of the extended Euclidian algorithm. Arguments: a: First number. b: Second number. Returns: A tuple (gcd, x, y) that where |gcd| is the greatest common divisor of |a| and |b| an...
def longest_in_dict( d:dict ) -> str: """ Returns longest item's string insde a dict """ longest:str = '' for i in d: if len(str(i)) > len(longest): longest=i return longest
def blinded_abs(blinded_id: str): """ Takes a blinded hex pubkey (i.e. length 66, prefixed with 15) and returns the positive pubkey alternative: that is, if the pubkey is already positive, it is returned as-is; otherwise the returned value is a copy with the sign bit cleared. """ # Sign bit is ...
def value_is_float_not_int(value): """Return if value is a float and not an int""" # this is klugy and only needed to display deprecation warnings try: int(value) return False except ValueError: try: float(value) return True except ValueError: ...
def dequantize(x, scale_factor, num_levels=255): """ Reverse operation of quantize_to_int Parameters: - x: np.array(dtype=int), quantized vector in integer representation - scale factor: float input will be mapped to this range - num_levels: int: number of quantization levels, must be odd ...
def int_to_roman(input): """ Convert an integer to Roman numerals. Examples: >>> int_to_roman(0) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>> int_to_roman(-1) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>>...
def calculate_dc_dT_CTM(temp): """ Seabird eq: dc/dT = 0.1 * (1 + 0.006 * [temperature - 20]) """ dc_dT = 0.1 * (1 + 0.006 * (temp - 20)) return dc_dT
def split_args_into_key_values(args): """ Receives a list of string command line arguments. For the ones with the `--KEY=VALUE` format (which is the format used by wandb to inject hyperparameters), creates a {KEY: VALUE} dictionary and returns. """ args = [ arg.strip()[2:] for a...
def catch_parameter(opt): """Change the captured parameters names""" switch = {'-h': 'help', '-f': 'file', '-g': 'update_gen', '-i': 'update_ia_gen', '-p': 'update_mpdf_gen', '-t': 'update_times_gen', '-s': 'save_models', '-e': 'evaluate', '-m': 'mining_alg'} try...
def str_join_instruction_options(dct): """ Build a string from the given dict that represents key/value pairs of optional instruction arguments. :param dct: Collection key/value pairs to join :return: Formatting string with double-dash options """ return ''.join(('--{}={}'.format(k.lower(), v) ...
def fib_r(n: int) -> int: """Recursively the nth fibonacci number :param n: nth fibonacci sequence number :type n: int :returns: the nth fibonacci number :rtype: int .. doctest:: python >>> fib_r(1) 1 >>> fib_r(2) 2 >>> fib_r(6) 13 """ ...
def calculate_diff_metrics(util1, util2): """Calculate relative difference between two utilities""" util_diff = {} for metric_k1, metric_v1 in util1.items(): if metric_k1 not in util2: continue util_diff[metric_k1] = {} for avg_k1, avg_v1 in metric_v1.items(): ...
def psched(n): """Create a prefix scan schedule for n ranks. The result is encoded as a list of slices -- one slice for the reduction carried out at each level of the scan. If needed, full list of (from,to) ranks can be recovered using the `slices_to_sched` function. Args: n: integer ...
def reducer(Pairs): """ The reducer function: reduces the Pairs. Args: - Pairs(list of tuples): a sorted list of 2D tuples with the pairs name-value. Return(list of tuples): a list of 2D tuples with the pairs name-value. """ Results = [] actualName = None resultsIndex = -1 for n...
def _grid(x): """Access the underlying ndarray of a Grid object or return the object itself""" try: return x.grid except AttributeError: return x
def bracketzap(instr, wild=True): """ Removes various bracket types from the input string. """ wstart = instr.find("[") if wstart == -1: return instr wstop = instr.rfind("]") if wstop == -1: return instr if wstart > wstop: return instr if wild: if instr[wstart:wstop+1] == "[-v]": return instr[0:wstart...
def check_jobs(jobs): """Validate number of jobs.""" if jobs == 0: print("Jobs must be >= 1 or == -1") elif jobs < 0: import multiprocessing jobs = multiprocessing.cpu_count() return jobs
def _calculate_insertion_point(existing_knob_list, knob_point=None, insert_before=False): """Encapsulates logic on working out where to insert in a the knob list Returns an integer index which tells us where to insert. For example in list [A,B,C]: - before A is 0 ...
def square_root(a): """Approximates the square root of input a to accuracy of 0.000001""" x = a/2 while True: print(x) y = (x + a/x) / 2 if abs(y-x) < 0.000001: break x = y return x
def rr_or(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with OR logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array Concentration of second repressor. ...
def _null_slice(s: slice): """Return true if a slice does nothing e.g. list[:]""" return s.start is s.step is s.stop is None
def clean_none_null(string): """ Removes 'None' and 'null' from string :param string: string - The string being evaluated :return: string """ return str(string).replace("None", "").replace("null", "")
def filter_out_exact_negative_matches(tests, negative_matches): """Similar to filter_tests, but filters only negative match filters for more speed With globbing disallowed, we can use sets, which have O(1) lookup time in CPython. This allows for larger filter lists. negative_filters is a list of lists...
def BigIntToBytes(n): """Return a big-endian byte string representation of an arbitrary length n.""" chars = [] while (n > 0): chars.append(chr(n % 256)) n = n >> 8 chars.reverse() return "".join(chars)
def map_file_to_plot_id(file_path: str, season_id: str, seasons: list) -> str: """Find the plot that is associated with the file Arguments: file_path: the path to the file season_id: the ID of the season associated with the file seasons: the list of seasons Return: Returns th...
def isiterable(obj) -> bool: """Checks whether object is iterable. Args: obj : object to check. Returns: boolean: True if object is iterable, else False. """ try: iter(obj) return True except TypeError: return False
def noduplicate(seq): """ List unique elements while preserving order stores values in dict for faster lookup """ seen = set() seen.clear() # make sure nothing remains return [x for x in seq if not (x in seen or seen.add(x))]
def json_perfect_exons_to_cdna_match(ordered_exons, single=False): """ Perfectly matched exons are basically a no-gap case of cDNA match single - use a single cDNA match (deletions for introns) - this is currently broken do not use """ cdna_match = [] if single: ordered_exons = list(orde...
def unfrozen(status): """ Return the unfrozen version of the given status name. @type status: C{unicode} @param status: a status returned from L{frozen}, which is to say, one for which L{isFrozen} is true. @rtype: C{unicode} """ return status[1:]
def getNamespace(string: str): """getNamespace Gives namespace of a type string, version included :param string: A type string :type string: str """ if '#' in string: string = string.rsplit('#', 1)[1] return string.rsplit('.', 1)[0]
def extended_euclidean_algorithm(a, b): # @param ax + by = gcd(a,b) """ Based on the fact that: b % a = b - (b // a) * a\\ gcd(a, b) = gcd(b%a, a) """ if a == 0: return b, 0, 1 gcd, x1, y1 = extended_euclidean_algorithm(b % a, a) x = y1 - (b//a)*x1 y = x1 ...
def deep_get(d, keys, default=None): """ Supports traversing nested dictionaries and searching for keys. Returns None if keys don't exist. Example: d = {'meta': {'status': 'OK', 'status_code': 200}} deep_get(d, ['meta', 'status_code']) # => 200 deep_get(d, ['garbage', 's...
def filter_nin(value): """ :param value: dict :return: list This function will compile a users verified NINs to a list of strings. """ result = [] for item in value: verified = item.get('verified', False) if verified and type(verified) == bool: # Be sure that it's not somet...
def read_string_weight(weights_data, offset, num_strings): """Decodes binary weight data for a tfjs string""" string_list = [] j = offset for _ in range(num_strings): # TFJS strings start with a 4 byte unsigned int indicating their length, followed by the bytes of the string length = str...
def format_text(txt, size): """ Format a given text in multiple lines Args: txt: Text to format size: Line size Returns: List of lines. """ res = [] sepchars = ' \t\n\r' txt = txt.strip(sepchars) while (len(txt) > size): # Search end of line enx =...
def _xyz_string(geom): """ .xyz format string of a cartesian geometry """ natms = len(geom) dxyz = '{:d}\n\n'.format(natms) for asymb, xyz in geom: dxyz += '{:s} {:s} {:s} {:s}\n'.format(asymb, *map(repr, xyz)) return dxyz
def verify_number(string): """Returns a boolean value on whether a given string is a positive integer.""" try: integer = int(string) assert integer > 0 except (ValueError, AssertionError): return False return True
def convert(word, mapping): """Converts a segment from jumbled to display wires""" res = set() for w in word: res.add(mapping[w]) return res
def _nx_get_source_target(pattern, record): """ Uses Node alias system to perform a pattern match. :param node_alias: Dict. :param pattern: List. :returns: Int. Source and target list indices. """ try: alias_seq = [p["node"]["alias"] for p in pattern[0::2]] except KeyError: ...
def getGenreList(books): """ Return the list of genres/categories of the books given a books object (from database query). """ genres = [] for book in books: if book.category: genre = book.category if genre not in genres: genres.append(genr...
def poll_me(query, slack_event): """ Makes a poll! Max of 9 options, comma separated. :param query: query str :param slack_event: A dict of slack event information :return: A poll with the given options in the query string """ if len(query) == 0: return "You want me to create a poll ...
def conversion_helper(val, conversion): """Apply conversion to val. Recursively apply conversion if `val` #is a nested tuple/list structure.""" if not isinstance(val, (tuple, list)): return conversion(val) rtn = [conversion_helper(v, conversion) for v in val] if isinstance(val, tuple): ...
def get_rightmost_idx(arr, key): """ Input: [4, 6, 6, 6, 9, 9], key = 6 Output: [1, 3] """ left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 if key < arr[mid]: right = mid - 1 else: left = mid + 1 return le...
def sub_dict(d, keys): """Return the subdictionary of 'd', with just the keys listed in 'keys'.""" return dict([(k, d[k]) for k in keys if k in d])
def midpoint_bin_key_to_str(key): """FIXME:add-doc""" return "{}\t{}\t{}\t{}\t{}\t{}".format(key[0], key[1][0], key[1][1], key[2], key[3][0], key[3][1])
def calc_unsaturated_evaporation(pet, unsatStore, fieldCap, wetFrac): """ Calculate evaporation from the unsaturated zone Parameters ---------- pet : int or float Potential evapotranspiration [mm day^-1] unsatStore : int or float Storage in the unsaturated zone [mm] fie...
def process_lines(file_reader, corpus_name:str)->list: """Strips and splits the lexicon lines. The case is kept intact for the 'switchboard' corpus, but is lowered for all others Args: file_reader: file reader object of lexicon corpus_name (str) Returns: (list): split lexicon li...
def arg_max(weights,args = None): """Returns the index of the list weights which contains the maximum item. If vals is provided, then this indicates the index""" if args == None: args = range(len(weights)) return max(zip(weights,args))[1]
def modify_string(string, add_data): """adds data to the string""" mod_string = string.strip('\n') + ' ' + add_data + '\n' return mod_string
def is_iterable(something): """ Test if it is an iterable other than a string. Returns ------- bool True if an iterable other than str, False otherwise. """ try: iter(something) except TypeError: return False return True and not isinstance(somethi...
def multiple_replace(string, rep_dict): """ Parameters ---------- string : string input string. rep_dict : dictionary thesaurus dictionary. Returns ------- string USAGE ------- multiple_replace("Do you like cafe? No, I prefer tea.", {'cafe':'tea', ...
def get_nested_value(outer_dict, path_str, default=None): """ Get a value from the given dictionary by following the path If the path isn't valid, nothing will be returned. """ # get a list of nested dictionary keys (the path) path = path_str.split(".") current_dict = outer_dict ...
def na_key(match, replacement='*'): """Replace APERTURE with N/A or *""" new = list(match) new[3] = replacement return tuple(new)
def is_max_string_singleline(string: str) -> bool: """ Checks to make sure the Base64 Shellcode string is not too large. https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2026?view=msvc-160&viewFallbackFrom=vs-2019 """ cpp_max_size = 16380 if len(string) >= cp...
def dict_encode(dict, encoding='cp1251'): """Encode dict values to encoding (default: cp1251).""" encoded_dict = {} for key in dict: encoded_dict[key] = dict[key].encode(encoding) return encoded_dict
def linear_mixture_to_original(k1, k2, b1, b2): """Translating linear mixture coefficients back to original parameterization. """ # (batch_size, ) k = k1 + k2 # (batch_size, ) b = (k1 * b1 + k2 * b2) / (k + 1e-7) return k, b
def person(author): """:person: Any text. Returns the name before an email address, interpreting it as per RFC 5322. >>> person('foo@bar') 'foo' >>> person('Foo Bar <foo@bar>') 'Foo Bar' >>> person('"Foo Bar" <foo@bar>') 'Foo Bar' >>> person('"Foo \"buz\" Bar" <foo@bar>') 'Foo "...
def str2bool(val): """String to integer conversion""" try: if isinstance(val, bool): return val elif not isinstance(val, str): return bool(val) elif val.lower() in ["true", "t", "yes", "y"]: return True elif val.lower() in ["false", "f", "no", ...
def monomial_mul(A, B): """ Multiplication of tuples representing monomials. Examples ======== Lets multiply `x**3*y**4*z` with `x*y**2`:: >>> from sympy.polys.monomials import monomial_mul >>> monomial_mul((3, 4, 1), (1, 2, 0)) (4, 6, 1) which gives `x**4*y**5*z`. ...
def filter(coord_list): """ Return a list with non doublon of each item """ checked_values = [] for value in coord_list: if not value in checked_values: checked_values.append(value) return checked_values
def penn_to_wn(tag): """Penn Treebank tag to Wordnet""" if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
def intYoCIS( fileName ) : """Returns the list of integers ( yo, C, I, S ) from fileName where fileName must be of the from 'yo##c##i###s###'.""" if ( len( fileName ) != 15 ) : raise Exception( "\nError from intYoCIS: bad file name = %s" % repr(fileName) ) return ( int( fileName[2:4] ), int( fileName[5:7] ...
def convert_format(f: str) -> int: """ get players per team based on format """ f = f[0] if not f.isnumeric(): return 1 return int(f)
def element_vol(vol, nx, ny, nz): """Calculates the volume of each of the elements on the grid. Args: vol: the cell volume (real) x : the number of grid points in each direction (real) Returns: ele_vol : the volume (real) """ number_of_elements = nx * ny * nz ele_vol = vo...
def Iyy_beam(b, h): """gets the Iyy for a solid beam""" return 1 / 12. * b * h ** 3
def get_error_msg(error, language): """ Filter the stack trace from stderr """ if error == "": return None elif language == "python3": if any(e in error for e in ["KeyboardInterrupt", "SystemExit", "GeneratorExit"]): return None else: return error.split('\n')[-2].strip() elif language == "node": re...
def rpad(l, until=0, fillvalue=None): """ Right pad a list. """ for _ in range(until - len(l)): l.append(fillvalue) return l
def last_elem_in_list(working_list): """ returns the last element of a list. """ return working_list[-1]
def _is_epub(file_bytes: bytes) -> bool: """ Decide if a file is an epub file. From https://github.com/h2non/filetype.py (MIT license) """ return (len(file_bytes) > 57 and file_bytes[0] == 0x50 and file_bytes[1] == 0x4B and file_bytes[2] == 0x3 and file_bytes[3] == 0x4 and file_bytes[30] == 0x6D and file_by...
def get_next_step_size(total: int, block_size: int, current_offset: int) -> int: """ Calculate next size of step for a TQDM progress-bar. :param total: :param block_size: :param current_offset: :return: """ if current_offset + block_size > total: step_size = total - current_offs...
def safe_get(obj, key, def_val=None): """ try to return the key'd value from either a class or a dict (or return the raw value if we were handed a native type) """ ret_val = def_val try: ret_val = getattr(obj, key) except: try: ret_val = obj[key] except: ...
def return_addition(first_number, second_number): """ Return the two numbers added together. """ return_value = first_number + second_number return return_value
def make_aws_filter(name, value): """ Helper to construct an AWS Filter. Many boto3 commands take an argument of the form: Filter=[{'Name': 'some string', 'Values': [list, of, values]}] :param str name: The value to put after Name. :param list values: The value to put in the Values list...
def clean_dict(d): """https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict""" if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (clean_dict(v) for v in d) if v] return {k: v for k, v in ((k, clean_dict(v...
def reverse_image(image): """ Reverse an image horizontally. :param [int] image: Image to reverse :return [int]: Reversed image """ return tuple(reversed(image))
def string2list(string): """ :param string: :return: """ return [char for char in string]
def sort_names(names): """ Sort task ``names`` by nesting depth & then as regular strings. """ return sorted(names, key=lambda x: (x.count('.'), x))
def _get_inputs(n): """ Prompt user n times. For each of their inputs, add to python list. :param n: option count / output of get_option_count() :return: list of strings containing options. """ options = [] counter = 1 try: for option in range(n): options.append(str...
def count_with_pseudocount(motifs): """Count the number of nucleotides (4 types: ACGT) column wise from a motifs matrix, then add 1 to each position, i.e. pseudocount. Args: motifs: 2D matrix, matrix of motifs in genome. Returns: dictionary, the count matrix of Motifs with pseudocounts as ...
def convert_type(var_type, var): """ convert value to type :param var_type: type for convert :param var: value for convert :return: converting result and exception/None """ try: value = var_type(var) return value, None except Exception as e: return var, e
def goodput_for_range(endpoint, first_packet, last_packet): """Computes the goodput (in bps) achieved between observing two specific packets""" if first_packet == last_packet or \ first_packet.timestamp_us == last_packet.timestamp_us: return 0 byte_count = 0 seen_first = False for pa...
def istriangle(a: float, b: float, c: float) -> bool: """checks if triad (a, b, c) obeys the triangle inequality Arguments: a: b: c: Returns: True if the triangle inequality is satisfied and False if it is not. """ return abs(a - b) <= c and c <= a + b
def dms2dd(arr): """ This method returns an array with the Decimal Degree format of an array with points in Degree,Minutes,Seconds format. Input Parameters: arr --> 1 Dimensional array with a list of location points in the DMS format Returned Parameters: result --> 1 Dimensional array wit...
def to_camel_case(snake_str: str) -> str: """ Convert "snake_case" => "snakeCase" :param snake_str: Snake String :return: Camel String """ components = snake_str.split("_") return components[0] + "".join(x.title() for x in components[1:])
def parseSizeString(theSize): """Parses a size string into an integer byte value. """ if not isinstance(theSize, str): return -1 theBits = theSize.split() if len(theBits) == 1: try: return int(round(float(theBits[0]))) except Exception: return -1 e...
def map_aStart_to_qTable(a_start, lambda_tmp): """ Returns the qTable index for the initial action. :param a_start: action from start state :param lambda_tmp: lambda value :return: domain label """ assert a_start in [0, 1, 2, 3], f'ERROR: Check agent label: {a_start}' assert lambda_tmp ...
def find_min(l): """ generic function that takes a list of numbers and returns smallest number in that list its index. return optimal value and the index of the optimal value as a tuple. :param l: list :return: tuple """ list_min = min(l); min_index = l.index(list_min); min_t...
def _reformat_extents(extents): """ Reformat extents from xmin list, xmax list, ymin list and ymax list to a list of (xmin, xmax, ymin, ymax) for each object. """ obj_group_extents = [] for xmin, xmax, ymin, ymax in zip(extents[0], extents[1], extents[2], e...
def _simplifyValues(*values): """Given a set of numbers, convert items to ints if they are integer float values, eg. 0.0, 1.0.""" newValues = [] for v in values: i = int(v) if v == i: v = i newValues.append(v) return newValues
def cost_function_part2(num_steps: int) -> int: """Recursive cost function for the second part. The first step costs 1, the second step costs 2, the third step costs 3, and so on. Args: num_steps (int): Number of Steps Returns: (int) cost Examples: >>> cost_function_p...
def binom_expansion(n:int): """Binomial expansion in n^2 time""" coeffs = [0, 1, 0] for _ in range(n): # Creates next level of Pascal's triangle coeffs = [0] + [coeffs[i] + coeffs[i+ 1] for i in range(len(coeffs) - 1)] + [0] return coeffs[1:-1]
def a (x: int, y: float) -> int: """ A sample :param x: x value :type x: int :param y: y value :type y: float :return: result :return type: int """ return 1 # Call tesnor flow here
def is_commended_function(line: str) -> bool: """ Check if function is commended. """ return line.strip()[0] == '#'
def remove_empty_tags(s, tags=('p', 'i', 'em', 'span')): """ >>> remove_empty_tags('Hi there') 'Hi there' >>> remove_empty_tags('<p>Hi there</p>') '<p>Hi there</p>' >>> remove_empty_tags('Hi there<p> </p>') 'Hi there ' >>> remove_empty_tags('Hi <span> </span>there') 'Hi there' ...
def exercise_3(string): """counts the number of spaces in a given input string. ARGS: a string RETURNS: an integer value representing the number of strings """ SPACE = " " return string.count(" ")
def validate_new_attending(in_new_attending, expected_keys): """ Validates inputted json data This function tests 3 criteria for the inputted json file. 1. It must be a dictionary 2. It must contain all of the expected_keys: "attending_username", "attending_email", and "attending_phone" 3. I...
def merge_schema(original: dict, other: dict) -> dict: """Merge two schema dictionaries into single dict Args: original (dict): Source schema dictionary other (dict): Schema dictionary to append to the source Returns: dict: Dictionary value of new merged schema """ source =...
def anf_coeffs(truthvalues): """ Convert a list of truth values of some boolean expression to the list of coefficients of the polynomial mod 2 (exclusive disjunction) representing the boolean expression in ANF (i.e., the "Zhegalkin polynomial"). There are 2^n possible Zhegalkin monomials in n v...