content
stringlengths
42
6.51k
def get_key_paths(d, key_paths=None, param_lists=None, acc=None): """Used to traverse a config and identify where multiple parameters are given. Args: d (dict): Config dictionary. key_paths (list): The list of keys to the relevant part of the config. param_lists (list): The list of mult...
def parseReviewsCount(textIn, replaceStr): """ """ if not textIn:return None _text=textIn.replace(replaceStr, "") return int(_text.strip())
def _resource_name_package(name): """ pkg/typeName -> pkg, typeName -> None :param name: package resource name, e.g. 'std_msgs/String', ``str`` :returns: package name of resource, ``str`` """ if not '/' in name: return None return name[:name.find('/')]
def opt_pol_1(state) -> int: """'100 or bust' policy. Bet the maximum stake required to (possibly) get to 100 in one go. """ return min(state, 100 - state)
def isValidOpts(opts): """ Check if the required options are sane to be accepted - Check if the provided files exist - Check if two sections (additional data) exist - Read all target libraries to be debloated from the provided list :param opts: :return: """ # if not option...
def flatten_nested(nested_dicts): """ Flattens dicts and sequences into one dict with tuples of keys representing the nested keys. Example >>> dd = { \ 'dict1': {'name': 'Jon', 'id': 42}, \ 'dict2': {'name': 'Sam', 'id': 41}, \ 'seq1': [{'one': 1, 'two': 2}] \ } >>>...
def luhn_algorthm_check(card_num: int) -> bool: """Checks that a user entered card num corresponds with the luhn algorithm""" card_num_lst = [int(x) for x in str(card_num)] last_digit = card_num_lst[-1] card_num_lst[-1] = 0 # Mutiplying odd digits by two for index, value in enumerate(card_...
def __x_product_aux (property_sets, seen_features): """Returns non-conflicting combinations of property sets. property_sets is a list of PropertySet instances. seen_features is a set of Property instances. Returns a tuple of: - list of lists of Property instances, such that within each list...
def cipher(text, shift, encrypt=True): """ Encrypts and decrypts phrases by moving each alphabetical character a given number of index units. Parameters ---------- text: A string to be encrypted or decrypted. Can include alphabetical or other characters shift: The number of index units ...
def pluck(n): """New pluck. It's longer! """ rval = n - 2 return rval
def comment_out_magics(source): """ Utility used to make sure AST parser does not choke on unrecognized magics. """ filtered = [] for line in source.splitlines(): if line.strip().startswith('%'): filtered.append('# ' + line) else: filtered.append(line) ...
def check_orientation(orientation): """Check ``orientation`` parameter and return as `bool`. Parameters ---------- orientaion : {'vertical', 'horizontal'} Returns ------- is_vertical : bool Raises ------ ValueError """ if orientation == "vertical": is_vertical ...
def rank_simple(vector ): """given a list, return the ranks of its elements when sorted.""" return sorted(range(len(vector)), key=vector.__getitem__)
def gen_profile_id(profile_id): """ Generates the Elasticsearch document id for a profile Args: profile_id (str): The username of a Profile object Returns: str: The Elasticsearch document id for this object """ return "u_{}".format(profile_id)
def rankAnomalousPoint(sampleErrors: list, rankingMap: dict) -> dict: """Adds a new list of sample errors to the majority voting map. Args: sampleErrors: A list of `(name, distance)` tuples. rankingMap: A mapping between counter names and vote count lists. Returns: A updated rankin...
def wlist_to_dict_parenthesis(words): """Converts a list of strings in the format: ['(', '(', 'n1', 'v1', ')', ..., '(', 'nk', 'vk', ')', ')'] to a dictionary {n1:v1, ..., nk:vk}.""" res = {} i = 1 while True: if words[i] == '(': res[words[i+1]] = words[i+2] i += 4 ...
def rep01(s): """REGEX: build repeat 0 or 1.""" return s + '?'
def snake_to_camel_case(text: str, dontformat: bool = False) -> str: """Convert a snake_case string into camelCase format if needed. This function doesnt check that passed text is in snake_case. If dontformat is True, return text. """ if dontformat: return text first, *others = text.spl...
def is_private_env_name(env_name): """ Examples: >>> is_private_env_name("_conda") False >>> is_private_env_name("_conda_") True """ return env_name and env_name[0] == env_name[-1] == "_"
def __get_tp(rank_query_taxids, rank_truth_taxids): """ Returns true positive >>> __get_tp(test_rank_query_taxids, test_rank_truth_taxids) 2 """ return len(rank_query_taxids.intersection(rank_truth_taxids))
def rel_to_abs_ages(rel_ages, gestation=19): """Convert sample names to ages. Args: rel_ages (List[str]): Sequence of strings in the format, ``[stage][relative_age_in_days]``, where stage is either "E" = "embryonic" or "P" = "postnatal", such as "E3.5" for 3.5 ...
def compare(reference, tested): """ Compare the two outputs according to a specific logic :return: True iff both input are equal """ epsilon = 0.01 for k,v in reference.items(): tested_vals = tested[k] ok = all (map( lambda x: (abs(x[1] - x[0])) <= epsilon, zip(v,tested_vals))) ...
def _reverse_bytes(mac): """ Helper method to reverse bytes order. mac -- bytes to reverse """ ba = bytearray(mac) ba.reverse() return bytes(ba)
def skipPunctuation(word): """ skip punctuation in word """ if "'" in word: split = word.split("'") word = split[0] # define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # remove punctuation from the string wordWithoutPunctuation = "" for char in word: ...
def group(list_, size): """Separate list into sublists of size size""" return [list_[i:i + size] for i in range(0, len(list_), size)]
def lower_bound_index(desired_capacity, capacity_data): """Determines the index of the lower capacity value that defines a price segment. Useful for accessing the prices associated with capacity values that aren't explicitly stated in the capacity lists that are generated by the build_supply_curve() fun...
def redM(m1, m2): """The reduced mass shows up in Kepler formulae, m1*m2/(m1+m2) """ return( m1*m2/(m1+m2) )
def marge_ranges(range_1, range_2): """Return merged range.""" return min(range_1[0], range_2[0]), max(range_1[1], range_2[1])
def permute(nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) == 0: return [] if len(nums) == 1: return [[nums[0]]] element = nums.pop() result_curr = permute(nums) result_next = [] for i in range(len(result_curr)): for j in range(len(...
def get_f1_score_for_each_label(pre_lines, gold_lines, label): """ Get F1 score for each label. Args: pre_lines: listed label info from pre_file. gold_lines: listed label info from gold_file. label: Returns: F1 score for this label. """ TP = 0 FP = 0 FN ...
def normalize_mode(mode): """ Return a mode value, normalized to a string and containing a leading zero if it does not have one. Allow "keep" as a valid mode (used by file state/module to preserve mode from the Salt fileserver in file states). """ if mode is None: return None if...
def parse_record2(raw_record): """Parse raw record and return it as a set of common symbols""" common_symbols = set("abcdefghijklmnopqrstuvwxyz") for person in raw_record.split(): common_symbols.intersection_update(set(person)) return common_symbols
def create_candidates(dataset, verbose=False): """Creates a list of candidate 1-itemsets from a list of transactions. Parameters ---------- dataset : list The dataset (a list of transactions) from which to generate candidate itemsets. Returns ------- The list of candidate i...
def has_property(property_set, property): """"Checks whether given property set has the given property.""" positive = True if property.startswith("NOT "): property = property[4:] positive = False if property == "TRUE": return True if property == "FALSE": return False ...
def grid_to_surface(x, y, w, h, tw, th): """ Converts grid coordinates to screen coordinates with 0,0 on the top corner of the topmost tile in the map """ return ( ((tw * (h-1)) + ((x-y)*tw)) / 2 ,((x+y)*th) / 2 )
def ComputeRho(A, nr, A_tot): """ Compute the ratio of area of a reinforcement to area of a section. @param A (float): Area of reinforcement. @param nr (float): Number of reinforcement (allow float for computing ratio with different area; just convert the other areas to one and compute the equi...
def lasso(number: complex, unit: str = '') -> str: """ Make a large number more readable by inserting commas before every third power of 10 and adding units """ return f'{number:,} {unit}'.strip()
def clean_euler_path(eulerian_path: list) -> list: """Cleans a Eulerian path so that each edge (not directed) appears only once in the list. If a edge appears more than once, only the first occurrence is kept. Arguments: eulerian_path {list} -- Eulerian path Returns: list -- cleaned Euleri...
def stamp_tuple_to_secs(stamp): """ Converts a stamp tuple (secs,nsecs) to seconds. """ return stamp[0] + stamp[1]*1.0e-9
def time_interpolation(array0, array1, date0, date, date1): """ Time interpolation at date 'date' of two arrays with dates 'date0' (before') and 'date1' (after). Returns the interpolated array. """ w = (date-date0)/(date1-date0) #Weights array = (1 - w ) * array0 + w * array1 return ar...
def g_iter(n): """Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) 10 >>> g_iter(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion']) True """ "*** YOUR...
def check_new_value(new_value: str, definition) -> bool: """ checks with definition if new value is a valid input :param new_value: input to set as new value :param definition: valid options for new value :return: true if valid, false if not """ if type(definition) is list: if new_va...
def filter_broker_list(brokers, filter_by): """Returns sorted list, a subset of elements from brokers in the form [(id, host)]. Passing empty list for filter_by will return empty list. :param brokers: list of brokers to filter, assumes the data is in so`rted order :type brokers: list of (id, host) ...
def tabs(num): """ Compute a blank tab """ return " " * num
def module_to_str(obj): """ Return the string representation of `obj`s __module__ attribute, or an empty string if there is no such attribute. """ if hasattr(obj, '__module__'): return str(obj.__module__) else: return ''
def int_with_commas(number): """helper to pretty format a number""" try: number = int(number) if number < 0: return '-' + int_with_commas(-number) result = '' while number >= 1000: number, number2 = divmod(number, 1000) result = ",%03d%s" % (nu...
def round_list(x, n = 2): """Auxiliary function to round elements of a list to n decimal places. Parameters ---------- x : list List of float values. n : int Number of decmial places to round the elements of list. Returns ------- list List with elements rounded ...
def parse_structure(node): """Turn a collapsed node in an OverlayGraph into a heirchaical grpah structure.""" if node is None: return None structure = node.sub_structure if structure is None: return node.name elif structure.structure_type == "Sequence": return {"Sequence" : [parse_structure(n) f...
def isAlreadyInArchive(archive, x): """ Check to see if the candidate is already in the archive. """ already = False for xi in archive: if tuple(xi) == tuple(x): already=True return (already)
def separate_list(inlist, rule): """ Separates a list in two based on the rule. The rule is a string that is mached for last characters of list elements. """ lrule = len(rule) list1 = [] list2 = [] for item in inlist: if (item[-lrule:] == rule): list1.append(item) ...
def calculate_reward(state, l_gap=0.25, road_length=200): """ Calculate reward for the given state. Notice that this function doesnt account for status inconsistency, but it gets covered in the state_transition function. :param road_length: segment length :param l_gap: minimum safety gap :param ...
def bb_intersection_over_union(box_a, box_b): """Thank you pyimagesearch! https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ :param box_a: Rect :param box_b: Rect """ # determine the (x, y)-coordinates of the intersection rectangle xA = max(box_a[0],...
def average_above_zero(tab): """ Brief: computes of the avrage of the positive value sended Arg: a list of numeric values, except on positive value, else it will raise an Error Return: a list with the computed average as a float value and the max value Raise: Valu...
def dict_differs_from_spec(expected, actual): """ Returns whether all props in "expected" are matching in "actual" Note that "actual" could contain extra properties not in expected """ for k, v in enumerate(expected.items()): if not k in actual: return False if actual[k] != v: return False return True
def delete_multi( keys, retries=None, timeout=None, deadline=None, use_cache=None, use_global_cache=None, global_cache_timeout=None, use_datastore=None, use_memcache=None, memcache_timeout=None, max_memcache_items=None, force_writes=None, _options=None, ): """Dele...
def tone(n, base_freq=440.0): """Return the frequency of the nth interval from base_freq (in 12-TET).""" # -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12 # G G# A A# B C C# D D# E F F# G G# A # G Ab A Bb B C Db D Eb E F Gb G Ab A return base_freq * 2 ** (n/12)
def truth(exp) -> str: """ Converts return of expression from 1,0 to corresponding bool """ return '[FALSE]' if (exp == 0) else '[TRUE]'
def consecutive_pairs(list): """ Utility function to return each consecutive pair from a list >>> consecutive_pairs([1,2,3,4,5]) [(1, 2), (2, 3), (3, 4), (4, 5)] >>> consecutive_pairs(['a', 'b', 'c']) [('a', 'b'), ('b', 'c')] >>> consecutive_pairs([2]) [] """ return [(list[i...
def masternode_status(status): """Get a human-friendly representation of status. Returns a 3-tuple of (enabled, one_word_description, description). """ statuses = { 'ACTIVE': (False, ('ACTIVE'), ('Waiting network to allow Masternode.')), 'PRE_ENABLED': (True, ('PRE_ENABLED'), ('Waiting ...
def decryptlist(d, n, dalist): """ >>> decryptlist(257, 377, [341, 287, 202, 99, 96, 69, 116, 69]) [100, 105, 115, 99, 5, 101, 116, 101] >>> decryptlist(257, 377, [56, 287, 556, 235, 22, 45, 354, 78]) [374, 105, 225, 40, 42, 197, 178, 169] >>> decryptlist(257, 377, [256, 35, 456, 543, 32, 56, 6...
def CleanParties(column): """Removes any text within parentheses.""" parties = column.replace("(",";(").split(";") party = [] for i in range (0,len(parties)): if parties[i].find("(") == -1: party.append(parties[i]) i+=1 preposition = ", between " if len(party) == 2 else "...
def numberList(listItems): """Convert a string list into number @param listItems (list) list of numbers @return list of number list """ return [float(node) for node in listItems]
def bin2hexstr(binbytes): """ Converts bytes to a string with hex Arguments: binbytes - the input to convert to hex Return : string with hex """ return ''.join('\\x%02x' % ord(c) for c in binbytes)
def str_splitword(chars, count=1): """Return the leading whitespace and words, split from the remaining chars""" tail = chars if count >= 1: counted_words = chars.split()[:count] for word in counted_words: tail = tail[tail.index(word) :][len(word) :] if not tail: r...
def is_stochastic_matrix(m, ep=1e-8) -> bool: """Checks that the matrix m (a list of lists) is a stochastic matrix.""" for i in range(len(m)): for j in range(len(m[i])): if (m[i][j] < 0) or (m[i][j] > 1): return False s = sum(m[i]) if abs(1.0 - s) > ep: ...
def twos_comp(val, bits=8): """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val # return positive value as is
def is_file_readable(file, strict=False): """Check if a file exists and is readable. Parameters ---------- file : :class:`str` The file to check. strict : :class:`bool`, optional Whether to raise the exception (if one occurs). Returns ------- :class:`bool` Wheth...
def pentagonal(n: int) -> int: """ Pentagonal Number Conditions: 1) n >= 0 :param n: non-negative integer :return: nth pentagonal number """ if not n >= 0: raise ValueError return (3*n**2 - n)//2
def zone_url_to_name(zone_url): """Sanitize DNS zone for terraform resource names zone_url_to_name("mydomain.com.") >>> "mydomain-com" """ return zone_url.rstrip(".").replace(".", "-")
def delleadingoff(process_list): """ if the first input of the process list is 'off' delete it""" if (process_list[0][0] == 'off'): del process_list[0] return process_list
def data_type_transfer(data): """ Transfer string fields in submitted json data if necessary """ if isinstance(data['is_active'], str): data['is_active'] = data['is_active'] in ["true", "True", "1"] if data['like_count']: data['like_count'] = int(data['like_count']) if isinstance(data['products'...
def fibonacci_two(n): """ Return the n-th fibonacci number""" if n in (0, 1): return n return (fibonacci_two(n - 2) + fibonacci_two(n - 1))
def _to_camel(snake_str: str) -> str: """Convert a string from snake_case to JSON-style camelCase Args: snake_str (str): Input string Returns: str: Camel case formatted string """ components = snake_str.split("_") return components[0] + "".join(x.title() for x in components[1:]...
def fibonacci(n): """ Returns the n-th number in the Fibonacci sequence. Parameters ---------- n: int The n-th number in the Fibonacci sequence. """ if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2)
def path_parts(path): """Returns a list of all the prefixes for this document's [snoop.data.digests.full_path][]. This is set on the Digest as field `path-parts` to create path buckets in Elasticsearch. """ elements = path.split('/')[1:] result = [] prev = None for e in elements: ...
def header(time_type=float): """ Return a header that describes the fields of an example record in a table of example definitions. time_type: Constructor for type of time / date found in example records: time_type<T>(str) -> T. An example record describes a span of time where a sub...
def obtain_header(line_lexems): """ get an included file name from provided lexems :param line_lexems: a list of lexems :return: file name is include construction exists, None otherwise """ control_stack = [] include_words = [] for lex in line_lexems: if lex == '//': ...
def sort_by(dict_list, key): """ Returns a List of dictionaries, sorted by a specific key """ return sorted(dict_list, key=lambda k: k[key])
def strip_suffix(filename): """Returns a filename minus it's extension.""" dotidx = filename.rfind(".") return filename[:dotidx] if dotidx != -1 else filename
def chunks(l, n, truncate=False): """Yield successive n-sized chunks from l.""" batches = [] for i in range(0, len(l), n): if truncate and len(l[i:i + n]) < n: continue batches.append(l[i:i + n]) return batches
def bigramSuggest(world, word, invert=False): """ world format: { word1 : { word2 : count } } """ ret=[] word=word.lower() if(word in world): items=world[word] invertedList={} vals=[] for item in items.keys(): vals.append(items[item]) if (not (items[item] in invertedList)): invertedList[items[ite...
def proof_of_euler(big_number): """ proof euler number using exponential growth """ return (1 + 1/big_number) ** big_number
def _build_task_dependency(tasks): """ Fill the task list with all the needed modules. Parameters ---------- tasks : list list of strings, containing initially only the last module required. For instance, to recover all the modules, the input should be ``['fourier']``. Returns ...
def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2): """ returns a (x, y) tuple or None if there is no intersection """ d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1) if d: uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d uB = ((Ax2 - Ax1) * (Ay1 - By1) - (...
def title_case(sentence): """ convert a string to a title case. Parameters __________ sentence: string string to be converted to title case Returns _______ title_case_sentence : string String converted to title case Example _______ >>> title...
def quadratic_equation(a, b, c, rnd=4): """Solving quadratic equations""" if a == 0: if b == 0: if c == 0: return 'any numbers' else: return 'No solutions' else: return -c / b elif b == 0: if c <= 0: re...
def parse_gender(gender_codeName_str): """ parse user gender :param gender_codeName_str: :return: """ dict_gender_mapping = {'0': 'male', '1': 'female', '2': "unknown"} if isinstance(gender_codeName_str, str): return dict_gender_mapping[gender_codeName_str]
def check_arg_type(arg_name: str, arg_value: str): """ Checks that RST Threat Feed API parameters are valid. Args: arg_name (str): paramater name arg_value (str): paramater value to verify Returns: (str): a null string means OK while any text is an erro...
def my_sum(x_val: int, y_val: int) -> int: """Sum 2 integers. Args: x_val (int): integer to sum. y_val (int): integer to sum. Returns: int: result of the summation. """ assert isinstance(x_val, int) and isinstance( y_val, int ), "Input parameters should be integ...
def _as_inline_code(text): """Apply inline code markdown to text Wrap text in backticks, escaping any embedded backticks first. E.g: >>> print(_as_inline_code("foo [`']* bar")) `foo [\\`']* bar` """ escaped = text.replace("`", r"\`") return f"`{escaped}`"
def human_readable_size(size): """Show size information human readable""" symbols = ["Ei", "Ti", "Gi", "Mi", "Ki"] symbol_values = { "Ei": 1125899906842624, "Ti": 1099511627776, "Gi": 1073741824, "Mi": 1048576, "Ki": 1024 } if size < 1024: return "%d" ...
def is_onehotencoder(feat_name): """ Parameters ---------- feat_name : string Contains the name of the attribute Returns ------- Returns a boolean value that states whether OneHotEncoder has been applied or not """ if "oneHotEncoder" in feat_name: return True ...
def get_atom_table(topology): """Convert the atom information to a dictionary.""" if 'atoms' not in topology: return None atoms = {} for atom in topology['atoms']: atoms[atom[0]] = atom return atoms
def _string_merge_wildcard(s1: str, s2: str, wildcard: str) -> str: """Takes a "union" of two equal-length strings `s1` and `s2`. Whenever one has a symbol `wildcard` and the other does not, the result has the non-wildcard symbol. Raises :py:class:`ValueError` if `s1` and `s2` are not the same length or do...
def dms_to_deg(degrees: int, minutes: int, seconds: float) -> float: """Converts degrees minutes seconds to dgrees in a float point format. Args: degrees (int): Number of degrees minutes (int): Number of minutes seconds (float): Number of seconds Returns: float: Th...
def chop(s): """Chop off the last bit of a file object repr, which is the address of the raw file pointer. """ return ' '.join(s.split()[:-1])
def bytes_to_int(byte): """Takes some Bytes and returns an Integer.""" return int.from_bytes(byte, 'little')
def build_response_card_attachment(title, subtitle, image_url, link_url, options = None): """ Build a responseCard attachment with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in ...
def partition (ar, left, right, pivotIndex, comparator): """ In linear time, group an array into two parts, those less than a certain value (left), and those greater than or equal to a certain value (right). left and right are inclusive. """ pivot = ar[pivotIndex] # move pivot to th...
def _is_float(value): """Use casting to check if value can convert to a `float`.""" try: float(value) except ValueError: return False else: return True