content
stringlengths
42
6.51k
def get_product_classname(product_data): """Get the name of the produt's object class based on the its type and asset class Args ---- product_data: dict The product's data in the product_data dict, containing the product's type and possibly its asset class Return ------ classname: ...
def count_digits(n): """Counts the number of digits in `n` Test cases: - 057 """ if n == 0: return 1 num_digits = 0 while n > 0: num_digits += 1 n /= 10 return num_digits
def unique_list(l): """Returns a list of unique values from given list l.""" x = [] #iterate over provided list for a in l: #check if number is in new list if a not in x: #add it to new list x.append(a) return x
def get_ecr_vulnerability_package_version(vulnerability): """ Get Package Version from a vulnerability JSON object :param vulnerability: dict JSON object consisting of information about the vulnerability in the format presented by the ECR Scan Tool :return: str package version...
def near_hundred(n: int) -> bool: """Integer n is near 100 or 200 by 10.""" near100 = abs(100 - n) <= 10 near200 = abs(200 - n) <= 10 return any((near100, near200,))
def _get_union_pressures(pressures): """ get list of pressured where rates are defined for both mechanisms """ [pr1, pr2] = pressures return list(set(pr1) & set(pr2))
def makeTuple(rect): """ Take in rectangle coordinates as list and return as tuple """ rectTuple = (rect[0], rect[1], rect[2], rect[3]) return rectTuple
def sort_at(nl, lis, k, a=0): """ [-1,1,0,0,0,0,-1,1] """ mind = 0 mval = 0 vlis = [] for i in range(0, len(nl)-k + 1 - a): v = abs(sum(nl[i:i+k])) vlis.append(v) if(v > mval and v != 0): mval = v mind = i return mind, max(lis) != 0
def parse_enums(code): """ Parses code and returns a list of enums. Usage: For this function to work properly input code needs to be prepared first, function prepare_for_parsing(code) has to be called to pre-process the code first. Input arguments: code -- code ...
def filter_func(token): """ :param token: (str) word or part of word after tokenization :return: (str) token as a word or part of word (whithout extra chars) """ if token == '[UNK]': token = '' symbols = ['\u2581', '#'] #chars that need to be filtered out (e. g. '#' for BERT-like tokeniz...
def pad(s, n, p = " ", sep = "|", align = "left"): """ Returns a padded string. s = string to pad n = width of string to return sep = separator (on end of string) align = text alignment, "left", "center", or "right" """ if align == "left": return (s + (p * n))[:n] + sep elif ...
def split_detail(detail): """ split detail :param detail: :return: """ info_list = detail.split("*") if len(info_list) >= 2: return "\t".join(info_list) return ""
def weighted_average(values): """Calculates an weighted average Args: values (Iterable): The values to find the average as an iterable of ``(value, weight)`` pairs Returns: The weighted average of the inputs Example: >>> weighted_average([(1, 2), (2, 3)]) 1...
def wxyz2xyzw(wxyz): """Convert quaternions from WXYZ format to XYZW.""" w, x, y, z = wxyz return x, y, z, w
def make_pseudonumber_sortable(pseudonumber): """For a quantity that may or may not be numeric, return something that is partially numeric. The method must always return a tuple containing a number, then zero or more strings. Other parts of the program assume that the first number is the numeric representa...
def sequence_id(data: list, ids: list) -> list: """ Filter out images that do not have the sequence_id in the list of ids :param data: The data to be filtered :type data: list :param ids: The sequence id(s) to filter through :type ids: list :return: A feature list :rtype: list """...
def get_target_for_label(label): """Converted a label to `0` or `1`. Args: label(string) - Either "POSITIVE" or "NEGATIVE". Returns: `0` or `1`. """ if(label == 'POSITIVE'): return 1 else: return 0
def format_time(mp): """Convert minutes played from analog time to digital time. :param str mp: minutes played, e.g. '24:30' :return int: e.g. 24.5 """ (m, s) = mp.split(':') digital = int(m) + int(s) / 60 return round(digital, 1)
def _metdata_filter(img_metadata, filters, img_pass): """Check if an image metadata value matches a filter value. Args: img_metadata: The metadata value for the given image filters: The metadata filter values img_pass: The current pass/fail state :param img_metadata: str ...
def _float_parameter(level: float, maxval: float): """Helper function to scale a value between ``0`` and ``maxval`` and return as a float. Args: level (float): Level of the operation that will be between [0, 10]. maxval (float): Maximum value that the operation can have. This will be scaled to ...
def rfact(n): """Recursive""" return rfact(n - 1) * n if n > 1 else 1
def is_collade(v1, v2): """ Input: v1,v2: velocity of train one and train two respectively in km/h Output: True if trains collade under defined circumstates, False if not """ t1 = 4/v1 s1 = t1*v2 if s1 >= 6: return True else: return False
def summation(num) -> int: """This function makes numbers summation.""" return sum(range(1, num + 1))
def num_to_letter(n): """Inverse of letter_to_num""" return chr(n + 97)
def transform_diag_element(element, file_ids_to_remove, new_file_ids): """ This function will update every file attribute of the given diagnostic element. On the first call it will get a diagnostic section dictionary and recursively traverse all children of it. If the child element is a file att...
def toggleMonths2(click): """ When syncing years, there should only be one time slider """ if not click: click = 0 if click % 2 == 0: style = {"display": "none", "margin-top": "0", "margin-bottom": "80"} else: style = {"margin-top": "30", "margin-bottom": "30"} return...
def density(tab): """Return for a given grid the proportion of filled holes among all holes after percolation Args: tab (array): grid Returns: float: proportion of filled holes """ n = len(tab) holes = 0 filled = 0 for i in range(n): for j in range(n): ...
def timeFix(s,m,h): """ Fixes time to ensure it stays within normal range (0-60) """ if(s>=60 or m>=60): while(s>=60 or m>=60): if s >= 60: m+=1 s-=60 if m >= 60: h+=1 m-=60 elif(s<0 or m<0): ...
def hash_fold(item, tablesize): """ The folding method for constructing hash functions begins by dividing the item into equal-size pieces (the last piece may not be of equal size). These pieces are then added together to give the resulting hash value. For example, if our item was the phone number 436-...
def dependencies(metadata_dict, field='depends'): """Returns a dictionary of (str, str) based on metadata's dependency field. The keys indicate the name of a package (shorthand name or full git URL). The names 'zeek' or 'zkg' may also be keys that indicate a dependency on a particular Zeek or zkg versi...
def is_off(filename): """Checks that the file is a .off file Only checks the extension of the file :param filename: path to the file """ return filename[-4:] == '.off'
def to_hex2(i): """Converts an integer to hex form (with 2 digits).""" tmp = hex(i)[2:] if len(tmp) == 1: return "0" + tmp else: return tmp
def example_func(param1, param2): """Example function with types documented in the docstring Args: param1 (int): The first parameter param2 (str): The second parameter Returns: bool: The return value. True for success, False otherwise. """ print(param1) print(p...
def unique(content): """Takes an iter and find the unique elements and return the simplified iter :param content: iter Any iter that can be converted to a set :returns: iter an iter of same type but with only unique elements """ the_type = type(content) retur...
def ByteToHex( byteStr ): """ Convert a byte string to it's hex string representation e.g. for output. """ # Uses list comprehension which is a fractionally faster implementation than # the alternative, more readable, implementation below # # hex = [] # for aChar i...
def _value_checker(index_input): """Helper function to input check the main index functions""" if index_input == '': # empty string, default index return "default" try: return float(index_input) except ValueError: return False
def get_item_properties(item, fields, mixed_case_fields=(), formatters=None): """Return a tuple containing the item properties. :param item: a single item resource (e.g. Server, Tenant, etc) :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to p...
def GetSymbolsFromReport(report): """Extract all symbols from a suppression report.""" symbols = [] prefix = "fun:" prefix_len = len(prefix) for line in report.splitlines(): index = line.find(prefix) if index != -1: symbols.append(line[index + prefix_len:]) return symbols
def count_trailing_newlines(s): """count number of trailing newlines this includes newlines that are separated by other whitespace """ return s[len(s.rstrip()):].count('\n')
def get_best(current, candidate): """ Return the new bunnies saved if the given candidate did saved more bunnies than the current Args: current (list[int]): sorted list of bunnies candidate (set[int]): unordered collection of saved bunnies Return: list[int]: bunnies saved sorted ...
def _cpp_field_name(name): """Returns the C++ name for the given field name.""" if name.startswith("$"): dollar_field_names = { "$size_in_bits": "IntrinsicSizeInBits", "$size_in_bytes": "IntrinsicSizeInBytes", "$max_size_in_bits": "MaxSizeInBits", "$min_size_in_bits": "MinSizeInB...
def nll_has_variance(nll_str): """ A simple helper to return whether we have variance in the likelihood. :param nll_str: the type of negative log-likelihood. :returns: true or false :rtype: bool """ nll_map = { 'gaussian': True, 'laplace': True, 'pixel_wise': False, ...
def _check_issue_label(label): """ Ignore labels that start with "Status:" and "Resolution:". These labels are mirrored from Jira issue and should not be mirrored back as labels """ ignore_prefix = ("status:", "resolution:") if label.lower().startswith(ignore_prefix): return None ...
def __eingroup_shapes(in_groups, out_groups, dim): """Return shape the input needs to be reshaped, and the output shape.""" def shape(groups, dim): return [group_dim(group, dim) for group in groups] def product(nums): assert len(nums) > 0 result = 1 for num in nums: ...
def friend(names): """Return list of friends with name lenght of four.""" result = [] for name in names: if len(name) == 4: result.append(name) return result
def connect(endpoint=None): """Generate connect packet. `endpoint` Optional endpoint name """ return u'1::%s' % ( endpoint or '' )
def humedad_solidos(Xs,z,k,Xe,M,S): """this is the rhs of the ODE to integrate, i.e. dV/dt=f(V,t)""" ''' Xs: Solid moisture [] z: Dimensionless position [] k: Drying constant Xe: Equilibrium moisture [] M: Total load [kg] S: Solid flow in [kg/s] ''' return -((k*(Xs-Xe))*M)/S
def vardim2var(vardim): """ Extract variable name from 'variable (dim1=ndim1,)' string. Parameters ---------- vardim : string Variable name with dimensions, such as 'latitude (lat=32,lon=64)'. Returns ------- string Variable name. Examples -------- >>> vard...
def concat_maybe_tuples(vals): """ >>> concat_maybe_tuples([1, (2, 3)]) (1, 2, 3) """ result = [] for v in vals: if isinstance(v, (tuple, list)): result.extend(v) else: result.append(v) return tuple(result)
def reverse_dict(d): """Reverses direction of dependence dict >>> d = {'a': (1, 2), 'b': (2, 3), 'c':()} >>> reverse_dict(d) # doctest: +SKIP {1: ('a',), 2: ('a', 'b'), 3: ('b',)} :note: dict order are not deterministic. As we iterate on the input dict, it make the output of this function d...
def get_cfg_sec_dict(cfg, sec, convert='float', verbose=False): """ Retrieve a dictionary of a section with options as keys and corresponding values. Parameters ---------- cfg : configparser.ConfigParser() Configuration as retrieved by the function read_cfg_file(). sec : str ...
def strip_dot_from_keys(data: dict, replace_char='#') -> dict: """ Return a dictionary safe for MongoDB entry. ie. `{'foo.bar': 'baz'}` becomes `{'foo#bar': 'baz'}` """ new_ = dict() for k, v in data.items(): if type(v) == dict: v = strip_dot_from_keys(v) if '.' in k: ...
def _get_prop(properties: list, key: str): """ Get a property from list of properties. :param properties: The list of properties to filter on :param key: The property key :return: """ result = list(filter(lambda prop: prop["name"] == key, properties)) if len(result) == 0: raise...
def xor(s1, s2): """ Exclusive-Or of two byte arrays Args: s1 (bytes): first set of bytes s2 (bytes): second set of bytes Returns: (bytes) s1 ^ s2 Raises: ValueError if s1 and s2 lengths don't match """ if len(s1) != len(s2): raise ValueError('Input n...
def find_net_from_node(node, in_dict, in_keys): """ Return the net name to which the given node is attached. If it doesn't exist, return None """ for k in in_keys: if node in in_dict[k]: return k
def _retry_matcher(details): """Matches retry details emitted.""" if not details: return False if 'retry_name' in details and 'retry_uuid' in details: return True return False
def inherits_init(cls): """Returns `True` if the class inherits its `__init__` method. partof: #SPC-notify-inst.inherits """ classname = cls.__name__ suffix = f"{classname}.__init__" return not cls.__init__.__qualname__.endswith(suffix)
def isclose(a, b): """adapted from here: https://stackoverflow.com/a/33024979/2260""" rel_tol = 1e-09 abs_tol = 0.0 return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def make_bold(text): """Make text bold before sending to the telegram chat.""" return f'<b>{text}</b>'
def type_name(item): """ ---- examples: 1) type_name('apple') -> 'str' ---- :param item: :return: """ return type(item).__name__
def strip_new_line(str_json): """ Strip \n new line :param str_json: string :return: string """ str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings return str_json
def construct_ecosystem(species, ecosystem): """Return A list of lists (interaction matrix) with the interaction parameters from the ecosystem dictionary. Each list contains the ordered interaction parameters with all other species for a focal species. The order is defined by alphabetically ordered species....
def gray_augment(is_training=True, **kwargs): """Applies random grayscale augmentation.""" if is_training: prob = kwargs['prob'] if 'prob' in kwargs else 0.2 return [('gray', {'prob': prob})] return []
def tcol(ui_cols): """two column value""" tcol = "_".join(ui_cols.keys()) return tcol
def compare_test_pairs(test_pairs, compare_function): """For each of the entries in test_pairs, the supplied compare_function is run on the 'ground_truth' and 'test_input' values and added as the 'results' value in a dictionary keyed by the pair 'name'""" results = {} for pair in test_pairs: gro...
def _serialize_tag(tag: int): """Serializes tag to bytes""" if tag <= 0xff: return bytes([tag]) elif tag <= 0xffff: return bytes([tag >> 8, tag & 0xff]) elif tag <= 0xffffff: return bytes([tag >> 16, (tag >> 8) & 0xff, tag & 0xff]) raise RuntimeError("Unsupported TLV tag")
def dirname(p): """Returns the directory component of a pathname""" i = p.rfind('/') + 1 assert i >= 0, "Proven above but not detectable" head = p[:i] if head and head != '/'*len(head): head = head.rstrip('/') return head
def parse_dimensions(descr): """ Parse a list of dimensions. """ return set(int(value) for value in descr.split(",") if value.strip() != "")
def IsDict(inst): """Returns whether or not the specified instance is a dict.""" return hasattr(inst, 'iteritems')
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 >>> # ban recursion >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion']) Tr...
def _toInt(val, replace=()): """Return the value, converted to integer, or None; if present, 'replace' must be a list of tuples of values to replace.""" for before, after in replace: val = val.replace(before, after) try: return int(val) except (TypeError, ValueError): return ...
def __prefixNumber(num, leading): """ Prefixes "num" with %leading zeroes. """ length = int(leading)+1 num = str(num) while len(num) < length: num = '0' + num return num
def path_type(value): """Path value routing.""" print(value) return "correct"
def cmp_floats(a, b): """NOTE: This code came from here: https://github.com/danieljfarrell/pvtrace/blob/master/pvtrace/Geometry.py""" #noqa abs_diff = abs(a-b) if abs_diff < 1e-12: return True else: return False
def build_error(non_accessible_datasets): """" Fills the `error` part in the response. This error only applies to partial errors which do not prevent the Beacon from answering. """ message = f'You are not authorized to access some of the requested datasets: {non_accessible_datasets}' return { ...
def filter_any_answer(group): """Filter questions answered by anyone in group.""" answers = set() for person in group: for question in person: answers.add(question) return answers
def merge(xs, ys): """ merge sorted lists xs and ys. Return a sorted result """ result = [] xi = 0 yi = 0 while True: if xi >= len(xs): # If xs list is finished, result.extend(ys[yi:]) # Add remaining items from ys return result # And we're d...
def theta_map(mat, z): """ Evaluates the conformal map "theta" defined by a matrix [a,b],[c,d] theta = (a*z + b)/(c*z + d). """ [a, b], [c, d] = mat return (a*z + b)/(c*z + d)
def is_variable_name(test_str: str): """Is the test string a valid name for a variable or not? Arguments: test_str (str): Test string Returns: bool: Is str a variable name """ return test_str.isidentifier()
def unify_sex(sex): """Maps the sex of a patient into one of the following values: "M", "F" or ``None``. Parameters ---------- sex : str Sex of the patient. Returns ------- sex : str Transformed sex of the patient. """ transform_dict = { "MALE": "M", ...
def _from_yaml_to_func(method, params): """go from yaml to method. Need to be here for accesing local variables. """ prm = dict() if params is not None: for key, val in params.items(): prm[key] = eval(str(val)) return eval(method)(**prm)
def size_uint_var(value: int) -> int: """ Return the number of bytes required to encode the given value as a QUIC variable-length unsigned integer. """ if value <= 0x3F: return 1 elif value <= 0x3FFF: return 2 elif value <= 0x3FFFFFFF: return 4 elif value <= 0x3FF...
def make_context(host, port, path, store, callbacks, collection_funcs, retrieve_funcs, entry_funcs, strip_meta, ctl, queue): """Returns a context object which is passed around by visit().""" return {"host": host, "port": port, "store": store, "path": path, "queue": ...
def is_cfn_magic(d): """ Given dict `d`, determine if it uses CFN magic (Fn:: functions or Ref) This function is used for deep merging CFN templates, we don't treat CFN magic as a regular dictionary for merging purposes. :rtype: bool :param d: dictionary to check :return: true if the dictio...
def __is_utf8(rule_string): """ Takes the string of the rule and parses it to check if there are only utf-8 characters present. :param rule_string: the string representation of the yara rule :return: true if there are only utf-8 characters in the string """ try: rule_string.encode('utf-8...
def default_pipeline(pipeline=None): """Get default pipeline definiton, merging with input pipline if supplied Parameters ---------- pipeline : dict, optional Input pipline. Will fill in any missing defaults. Returns ------- dict pipeline dict """ defaults = { ...
def weighted(x,y,p1,p2): """A weighted sum Args: x (float): first value y (float): second value p1 (float): first weight p2 (float): second weight Returns: float: A weighted sum """ tmp = p1*x + p2*y output = tmp return output
def fib_dp_tbl(n: int) -> int: """Computes the n-th Fibonacci number. Args: n: The number of which Fibonacci sequence to be computed. Returns: The n-th number of the Fibonacci sequence. """ memo = {0: 0, 1: 1} for i in range(2, n+1): memo[i] = memo[i-1] + memo[i-2] ...
def find_x(search_string): """find x in the search str:arr; return True if found""" found = False for char in search_string: if char.lower() == 'x': found = True break print(f'Is x in the string? {found}') return found
def make_shard_files(dataset_files, num_shards, shard_id): """ Make sharding files when shard_equal_rows is False. """ idx = 0 shard_files = [] for dataset_file in dataset_files: if idx % num_shards == shard_id: shard_files.append((dataset_file, -1, -1, True)) idx += 1 ...
def _get_plane_coeff(x, y, z): """private method: compute plane coefficients in 3D given three points""" a = ((y[1] - x[1]) * (z[2] - x[2]) - (z[1] - x[1]) * (y[2] - x[2])) b = ((y[2] - x[2]) * (z[0] - x[0]) - (z[2] - x[2]) * (y[0] - x[0])) c = ((y[0] - x[0]) * (z[1] - x[1]) - ...
def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def find_subseq_in_seq(seq, subseq): """Return an index of `subseq`uence in the `seq`uence. Or `-1` if `subseq` is not a subsequence of the `seq`. The time complexity of the algorithm is O(n*m), where n, m = len(seq), len(subseq) from https://stackoverflow.com/questions/425604/best-way-to-determ...
def hello_world(name: str) -> str: """Hello world function Parameters ---------- name : str Name to say hi to Returns ------- greeting : str A simple greeting """ return f"Hello {name}"
def value_or_none(value): """Return string value if not empty. Otherwise, returns None.""" if value.strip() == "": return None return value
def apply_noise(val_list, noise_params, noise_function): """ Applies noise to each value in a list of values and returns the result. Noise is generated by a user-provided function that maps a value and parameters to a random value. """ result = [] for val, params in zip(val_list, noise_par...
def _canonicalize_lv_path(lv_path): """Convert LV path to a (vg, lv) tuple""" if lv_path.startswith('/dev'): # '/dev/vg/lv' _, _, vg, lv = lv_path.split('/') else: # vg/lv vg, lv = lv_path.split('/') return vg, lv
def sum_digits(n): """Sum all the digits of n. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> x = sum_digits(123) # make sure that you are using return rather than print >>> x 6 """ i = 0 def pow_count(...
def wwma_values(values, period=None): """Returns list of running Welles Wilder moving averages. Approximation of the ema. :param values: list of values to iterate and compute stat. :param period: (optional) # of values included in computation. * None - includes all values in computation. :...
def add_number_separators(number, separator=' '): """ Adds a separator every 3 digits in the number. """ if not isinstance(number, str): number = str(number) # Remove decimal part str_number = number.split('.') if len(str_number[0]) <= 3: str_number[0] = str_number[0] ...