content
stringlengths
42
6.51k
def get_indices_of_max(iterable): """Return the max indices of the iterable.""" max_indices = [] max_v = float('-inf') ACCEPTABLE_DIFFERENCE = 1 # hyperparameter for i, iter in enumerate(iterable): difference = max_v - iter squared_difference = difference*difference if squa...
def generate_command_statement(instruction): """ Converts json fragment to list (cmd, [args] [switches] [flags]) :param instruction: json fragment :return: statement list """ cmd_statement = [instruction.get("cmd")] for arg in instruction.get("args", []): cmd_statement.append(arg) ...
def get_attribute(attrs, name, default=None): """ Get div attribute :param attrs: attribute dict :param name: name field :param default: default value :return: value """ if 'data-'+name in attrs: return attrs['data-'+name] else: return default
def checksum_header(flags, length): """ Calculate checksum over the header. """ a = (flags & 0x00FF) >> 0 b = (flags & 0xFF00) >> 8 c = (length & 0x00FF) >> 0 d = (length & 0xFF00) >> 8 return a ^ b ^ c ^ d
def takeall_reversed(levels, **_): """ Reverses a sequence of Level objects. >>> takeall_reversed([1, 2, 3, 4]) [4, 3, 2, 1] Args: levels: A sequence of Level objects Returns: A list containing the same Level objects, in reverse order. """ return list(reversed(levels))
def schema_url(server, app): """URL of the schema of the running application.""" return f"http://127.0.0.1:{server['port']}/schema.yaml"
def maxThreats(a): """ left_threads stores threads in left-top-to-right-bottom direction right_threads stores threads in right-top-to-left-bottom direction""" left_threads, right_threads = dict(), dict() max_threads, threads = 0, [0] * len(a) for row, col in enumerate(a): col -= 1 # def...
def m_calc(Kp_GCC,u,x): """Duty cycle for a single phase.""" return Kp_GCC*u + x
def get_forms(data): """Takes a JSON data object and returns a list of its forms""" to_return = [] forms = data.get('forms') if forms: for form in forms: form_value = form.get('form') if form_value != None: to_return.append(form_value) word = data.get(...
def delete_redon_nominal_group(nominal_group_list): """ delete the redundancy in the list of nominal groups Input=nominal group list Output=nominal group list """ #init i = 0 j = 0 #We have to loop the list twice whi...
def union(list_a: list, list_b: list) -> list: """Return the union of two lists""" if list_a is None: list_a = [None] if list_b is None: list_b = [None] return list(set(list_a) | set(list_b))
def create_formats(wb, cfg_fmt, f_db={}): """Takes a workbook and (likely empty) database to fill with formats""" for name, db in cfg_fmt.items(): f_db[name] = wb.add_format(db) return f_db
def get_caption(prop, dic): """ Get a textual caption of a keras property that my be $ - a literal string label (e.g. 'mse') - an instance of a class - a reference to a function """ if prop is not None: if isinstance(prop, str): prop_extract = prop.lower().replace...
def tail_add(x: int, y: int) -> int: """A tail-recursive implementation which will run in constant space.""" if y == 0: return x else: return tail_add(x + 1, y - 1)
def unalias_key(dict_, name): """ Converts a simple key name into the actual key name by certain alias rules.""" try: dict_[name] return name except: pass try: dict_[str(name).upper()] return str(name).upper() except: pass try: dict_['PARAM...
def format_xpaths(xpath_map, *args, **kwargs): """ :return: a copy of xpath_map, but with XPATHs formatted with ordered or keyword values """ formatted = {}.fromkeys(xpath_map) for key, xpath in xpath_map.items(): formatted[key] = xpath.format(*args, **kwargs) return formatted
def _break_into_words(line): """ Turn a already-tokenized line into a list of words. :param line: string, already tokenized. All tokens are separated by space. :return: List[string], broken into words. """ return line.strip().split(' ')
def vector_add(v, w): """ adds corresponding elements """ return [v_i + w_i for v_i, w_i in zip(v, w)]
def ReadableSizeOf(num): """Convert to a human readable number.""" if num < 1024.0: return '[%5dB]' % num for x in ['B','K','M','G','T']: if num < 1024.0: return '[%5.1f%s]' % (num, x) num /= 1024.0 return '[%dT]' % int(num)
def parse_sentences(name,data): """ Returns a list of natural language sentence in a dataset file Parameters ---------- name : str string key that contains sentences in the dataset file data : list of dict list of dictionaries where each dictionary contains a sentence and its an...
def parse_mappings(mapping_list): """Parse a list of mapping strings into a dictionary. Adapted from neutron_lib.utils.helpers.parse_mappings. :param mapping_list: A list of strings of the form '<key>:<value>'. :returns: A dict mapping keys to values or to list of values. :raises ValueError: Upon ...
def format_sex_string(sex_str): """ Converts 'M', 'F', or else to 'male', 'female', or empty string (e.g. ''). Args: sex_str (str): String consisting of 'M', 'F', '', or None. Returns: str: 'M', 'F', or '' """ if sex_str == "M": sex = "male" elif sex_str == "F": ...
def get_element_parts( original_list: list, splitter_character: str, split_index: int ) -> list: """ Split all elements of the passed list on the passed splitter_character. Return the element at the passed index. Parameters ---------- original_list : list List of strings to be spli...
def locale_to_source_path(path): """ Return source resource path for the given locale resource path. Source files for .po files are actually .pot. """ # Comment this for now as js-lingui does not provide .pot files, only .po # Commenting these lines is enough to make it work # if path.endswi...
def sort_by_report_time(item): """A helper function for sorting, indicates which field to use""" return item['reportTime']
def get_field(field, row, field_map, default_value=None): """Access fields in a row according to the specified field map. Args: field: field to extract. row: row to extract field from. field_map: field map. default_value: value to be returned in case the field is not mapped. Returns: specifie...
def reverse_list_strings(lines): """ Reverse a list of strings: - First, reverse entries of the list. - Second, reverse each entry of the reversed list. """ return [line[::-1] for line in lines[::-1]]
def create_vectors_from_dicts(dict1, dict2): """ From two dicts that contain as values a tuple = (score, pval), two lists are created in which each position contains the score of a concrete key which has to be the same for both lists Example: dict1 = {"C":(1,0), "B":(5,0), "A":(9,0)} ...
def distance(strand_a: str, strand_b: str) -> int: """count the mistakes between two DNA strands. :type strand_a: str :type strand_b: str :param strand_a: DNA strands. :param strand_b: DNA strands. :return: mistake count. :raises: ValueError if lengths of the two strands are different. ...
def add_colon(in_str): """Add colon after every 4th character.""" return ':'.join([in_str[i:i+4] for i in range(0, len(in_str), 4)])
def _get_copyrights_from_ts(ts_file): """ Get copyright information from a TypeScript file. Assumes that copyright information is in the form: // Definitions by: owner1 // owner2 // owner3 // Definitions: """ ts_start = "// Definitions by:" ts_end...
def update_nested_dict(data: dict, to_update: dict) -> dict: """ Returns an updated version of the `data` dict updated with any changes from the `to_update` dict. This behaves differently from the builting`dict.update` method, see the example below. Example using `update_nested_dict`: >>> data = {...
def format_normalized_package_name(package_name): # type: (str) -> str """Normalize a package name""" return package_name.replace(".", "-").replace("_", "-").lower()
def update_serviceable_demand(coverage, sd): """ Updates a coverage with new values from a serviceable demand dict :param coverage: (dict) The coverage to update :param sd: (dict) The corresponding serviceable demand to use as update :return: (dict) The coverage with the updated serviceable demands...
def author_join(value, d=u', ', last=u', and ', two=u' and '): """ Like join but for list of names (convenient authors list) """ if len(value) == 1: return value[0] elif len(value) == 2: return value[0] + two + value[1] else: return d.join(value[:-1]) + last + value[-1]
def event_to_dict(event, context): """ Extract params decoding in base64 and parse Json for event message :param event: {'data'} :param context: Context :return: dict """ import base64 import json try: if event['data']: return json.loads(base64.b64decode(event['data']).decode('utf-8')) ...
def is_iterable(val): """ Checks if `val` is iterable. This method calls `iter(val)`. If an exception is raised, it's not an iterable. This is the 'correct' way, to account for the mess types are in Python. For details, see https://stackoverflow.com/a/1952655 """ try: iter(val) ...
def icosahedron_nodes_calculator(order): """Calculate the number of nodes corresponding to the order of an icosahedron graph Args: order (int): order of an icosahedron graph Returns: int: number of nodes in icosahedron sampling for that order """ nodes = 10 * (4 ** order) + 2 ...
def get_f1(num_correct, num_infer, num_label): """ get p r f1 input: 10, 15, 20 output: (0.6666666666666666, 0.5, 0.5714285714285715) """ if num_infer == 0: precision = 0.0 else: precision = num_correct * 1.0 / num_infer if num_label == 0: recall = 0.0 else: ...
def convert_pixel_to_mask_index( edge_length, window_size, flattened_pixel_index): """Maps flattened pixel index to the flattened index of its mask. Args: edge_length: int, side length of the 2D array (image). window_size: int, side length of the square mask. flattened_pixel_index: int, flattened p...
def flatten(t): """Flatten a 2-dimensional list. Returns a generator""" return [a for s in t for a in s]
def make_range(opening_tag=None, closing_tag=None, ix=0): """ Makes selection ranges for matched tag pair @type opening_tag: Tag @type closing_tag: Tag @type ix: int @return list """ start_ix, end_ix = -1, -1 if opening_tag and not closing_tag: # unary element start_ix = opening_tag.start end_ix...
def get_ogheader(blob, url=None): """extract Open Graph markup into a dict The OG header section is delimited by a line of only `---`. Note that the page title is not provided as Open Graph metadata if the image metadata is not specified. """ found = False ogheader = dict() for line in...
def pretty_eta(seconds_left): """Print the number of seconds in human readable format. Examples: 2 days 2 hours and 37 minutes less than a minute Paramters --------- seconds_left: int Number of seconds to be converted to the ETA Returns ------- eta: str Stri...
def contours(x_vals, y_vals): """Plot defaults for plotting.contours""" aspect_ratio = (y_vals[-1] - y_vals[0]) / (x_vals[-1] - x_vals[0]) figsize = (8, 8 * aspect_ratio) return { 'figsize': figsize }
def number_format(context, value): """ Enforces 2 decimal places after a number if only one is given (adds a zero) also formats comma separators every 3rd digit before decimal place. """ value = str(value) negative = False addzero = None if value[0] == '-': value = value[1:] ...
def get_snr_from_mix_path(mix_path): """ Retrieves mixing SNR from mixture filename. Args: mix_path (str): Path to the mixture. Something like : book_11346_chp_0012_reader_08537_8_kFu2mH7D77k-5YOmLILWHyg-\ gWMWteRIgiw_snr6_tl-35_fileid_3614.wav Returns: int or None: the SNR...
def construct_headers(cookie, id): """Constroi o cabecalho HTTP que sera enviado na requisicao. Parameters ---------- cookie : str, string com o cookie a ser passado na requisicao id : str, string com o id do CV, usado no referer Notes ----- Todas as requisicoes desse sistema enviam es...
def norm_percent(raw): """Normalize a list in a percentage format. If the sum of all the elements in the list is 0, returns a list of the size of the input full of 0. >>> norm_percent([2,5,3]) [20.0,50.0,30.0] >>> norm_percent([0,0,0]) [0,0,0] >>> norm_percent([2,3,-5]) [0,0,0] :param ...
def delistify(some_list): """ Untangle multiple nested one-element lists. Occasionally a problem in Libris, e.g. "[['x']]". Converts it to 'x'. @param some_list: list to convert. @type some_list: list """ while isinstance(some_list, list) and len(some_list) == 1: some_list = so...
def _equivalent_for_plotgroup_update(p1,p2): """ Helper function for save_plotgroup. Comparison operator for deciding whether make_plots(update==False) is safe for one plotgroup if the other has already been updated. Treats plotgroups as the same if the specified list of attributes (if present...
def roundlist (inlist, digits): """ Goes through each element in a 1D or 2D inlist, and applies the following function to all elements of float ... round(element,digits). Usage: roundlist(inlist,digits) Returns: list with rounded floats """ if isinstance(inlist[0], (int, float)): inlist = [inlist] ...
def precision(tp: int, fp: int, zero_division: int = 0) -> float: """Calculates precision (a.k.a. positive predictive value) for binary classification and segmentation. Args: tp: number of true positives fp: number of false positives zero_division: int value, should be one of 0 or 1...
def drop_below(threshold=5, **kwargs): """Trigger function that returns True if the price falls below the threshold price_today < threshold and price_yest >= threshold """ if ( # kwargs['price_today'] and kwargs['price_yest'] and # not np.isnan(kwargs['price_today'] and not kwargs['price_...
def sieve_of_eratosthenes(n): """ Sieve of Eratosthenes implementation; Finding prime numbers from 2 to n (inclusive). """ primes = [True] * (n + 1) primes[0] = False primes[1] = False results = [] # List to store the prime numbers for i in range(2, int(n ** 0.5) + 1): if pri...
def calc_precision(TP, FP): """ Calculate precision from TP and FP """ if TP + FP != 0: precision = TP / (TP + FP) else: precision = 0 return precision
def check_dict(ref_dict, tst_dict): """Compare dictionaries of inputs and and those loaded from json files""" def to_list(x): if isinstance(x, tuple): x = list(x) if isinstance(x, list): for i, xel in enumerate(x): x[i] = to_list(xel) return x ...
def train_progress_desc(speed: int, epoch_loss: float, step_loss: float, speed_unit: str = "img/s") -> str: """The progress Train description. Args: speed (int): The speed of the process. epoch_loss (float): The loss of the epoch. (sum / n) step_loss (float): The loss of the step. ...
def saturation(value): """Saturation of the light. 254 is the most saturated (colored) and 0 is the least saturated (white).""" value = int(value) if value < 0 or value > 254: raise ValueError('Minimum saturation is 0, to the maximum 254') return value
def add_xor(op_a: bytearray, op_b: bytearray) -> bytearray: """ Byte-by-byte 'xor' operation for byte objects. Args: op_a: The first operand. op_b: The second operand. Returns: Result of the byte-by-byte 'xor' operation. """ op_a = bytearray(op_a) op_b = bytearray(o...
def make_error_response(status, error): """ make error response function :param status: :param error: :return: """ return dict(status=status, error=str(error))
def command_dict(parameter_dict, system_id): """A command represented as a dictionary.""" return { "name": "speak", "description": "desc", "parameters": [parameter_dict], "command_type": "ACTION", "output_type": "STRING", "hidden": False, "schema": {}, ...
def trim(text): """ {% load trim %} {{ var | trim }} """ return text.strip() if text else ""
def policy_access_analyzer(policy_actions): """parameters: policy_actions : list description: This function analyzes the bucket policy statements, and determines the access scope (read, write, full aceess, etc). It return a string of the access scope.""" access_actions = [] bu...
def determine_overall_status(qc_json): """Currently PASS no matter what """ qc_json.update({'overall_quality_status': 'PASS'}) return(qc_json)
def get_vmx(sandbox, image): """ get_vmx :param sandbox: str :param image: str :returns: str """ return f"{sandbox}/output-vmware-iso/{image}.vmx"
def get_variables(program, name, *parameters): """get all variables matching an indexed variable ## Inputs - program: dict of milp program generated using initialize_program() - name: str name of indexed variables - parameters: list of specific index values to return """ variables = [] ...
def github_auth_headers(github_access_token): """ Create headers for authenticating requests against github Args: github_access_token (str): A github access token Returns: dict: Headers for authenticating a request """ return { "Authorization": f"Bearer {git...
def _characteristic_vector(n,S): """Return the characteristic vector of the subset S of an n-set.""" return [0 if i not in S else 1 for i in range(n)]
def get_intersect_point(a1, b1, a2, b2): """ The point of intersection of two lines. If lines parallel then None is returned """ if a1 is None and a2 is None: return None, None if a1 is None and abs(a2 - 0.0) < 1e-6: return b1, b2 if a2 is None and abs(a1 - 0.0) < 1e-6: ...
def mixing_dict(xy, normalized=False): """Returns a dictionary representation of mixing matrix. Parameters ---------- xy : list or container of two-tuples Pairs of (x,y) items. attribute : string Node attribute key normalized : bool (default=False) Return counts if False ...
def transpose_func(classes, table): """ Transpose table. :param classes: confusion matrix classes :type classes: list :param table: input confusion matrix :type table: dict :return: transposed table as dict """ transposed_table = {k: table[k].copy() for k in classes} for i, item...
def cancel_registry_imports(on=0): """Anular Importacoes Acidentais no Registro DESCRIPTION Por padrao, se voce der um duplo clique sobre um arquivo com a extensao ".reg", o arquivo sera importado pelo registro do sistema. Se voce alterar o padrao, o arquivo sera aberto para edicao em...
def WriteFile(InData,FileName): """ IN: Data to save and Filename OUT: Bool True or False Description: Saves the data to the corresponding file """ try: with open(FileName,"wb") as fp: fp.write(InData) except Exception as ex: print("[-] Error hit ...
def bpc (val=None): """ Set or get black pixel correction """ global _bpc if val is not None: _bpc = val return _bpc
def es_base(caracter): """ Str -> Bool Ingresa un caracter, se determina si es True o False >>> es_base('A') True >>> es_base('T') True >>> es_base('C') True >>> es_base('G') True >>> es_base('AT') Traceback (most recent call last): .. ValueError: AT no...
def remove_www(hostname): """ Removes ``www``. from the beginning of the address. Only for routing purposes. ``www.test.com/login/`` and ``test.com/login/`` should find the same tenant. """ if hostname.startswith("www."): return hostname[4:] return hostname
def ma_to_xy(m, a): """Convert (M, A) value back to read counts/densities of two samples. Parameters ---------- m : float M value. a : float A vlaue. Returns ------- x : float Converted read count/density in sample 1. y : float Converted read count/d...
def get_descriptive_verbs(tree, gender): """ Returns a list of verbs describing pronouns of the given gender in the given dependency tree. :param tree: dependency tree for a document, output of **generate_dependency_tree** :param gender: 'male' or 'female', defines which pronouns to search for :ret...
def pos_line_diff(res_list, expected_list, raise_nonempty=True): """ Return differences between two bar output lists. To be used with `RE_pos` """ res = [(r, e) for r, e in zip(res_list, expected_list) for pos in [len(e) - len(e.lstrip('\n'))] # bar position if r != e # simpl...
def cf_contains(element: str, string: str) -> bool: """Casefold (aka 'strong `lower()`') check if a substring is in a larger string. Args: element: The shorter string to be tested for containment in `string`. string: The larger string. Returns: Caseless test of whether the larger s...
def check_dependencies(debug): """ check the dependencies and install if possible/required """ # suppress dependency checks temporarily return True with open('ENV.txt', 'r') as fp: env = fp.read().strip() ret = False logger.info('================ Checking Dependencies =====...
def xy2uv_with_res(x, y, color_width, color_height, depth_width, depth_height): """ Calculate pixel location from color to depth using only image resolutions :param x: integer x pixel coordinate :param y: integer y pixel coordinate :param color_width: integer color frame width :param color_heigh...
def dot_escape(label_content): """ Escape the given string so it is safe inside a GraphViz record label. Only actually handles the caharcters found in Avro type definitions, so not general purpose. """ return (label_content.replace("&", "&amp;").replace("<", "&lt;") .replace(">", "&gt;...
def ferret_result_limits(efid): """ Abstract axis limits for the shapefile_writexyzval PyEF """ return ( (1, 1), None, None, None, None, None, )
def _dol_to_lod(dol): """Convert a dict of lists to a list of dicts.""" return [dict((key, dol[key][ii]) for key in dol.keys()) for ii in range(len(dol[list(dol.keys())[0]]))]
def iter_in(value, seq, cmp): """ A function behaving like the "in" Python operator, but which works with a a comparator function. This function checks whether the given value is contained in the given iterable. Args: value: A value seq: An iterable cmp: A 2-arg comparator ...
def USListToRATDBFormat(AllReactors): """ Takes in a list of reactor names (as formatted on NRC.gov) and converts the names to name format found in REACTORS.ratdb in db/static. """ AllReacRATDBFormat = [] for ReacName in AllReactors: ReacName = ReacName.rstrip('1234567890 ') if R...
def sequence(funcs, ele): """ sequence(funcs: list[function], ele:any) [func(ele) for func in funcs] args: funcs = [L x: x+1, L x: x+2]; ele = 1 return: [2,3] """ return [ func(ele) for func in funcs ]
def fact(n): """Assumes n is a positive int Returns n!""" answer = 1 while n > 1: answer *= n n -= 1 return answer
def is_wanted_header(header): """Return True if the given HTTP header key is wanted. """ key, value = header return key.lower() not in ('x-content-type-warning', 'x-powered-by')
def _tf_tensor_name_to_tflite_name(tensor_tf_name: str) -> str: """Convert a TF tensor name to the format used by TFLiteConverter. Args: tensor_tf_name: Tensor name to convert. Returns: Converted tensor name. """ # See get_tensor_name() in //third_party/tensorflow/lite/python/util.py return tensor...
def choice_logic(num): """ Based on a numeric value this function will assign the value to an option which will be either rock, paper or scissors. And then return the option. """ if num == "1": return "Paper" elif num == "2": return "Scissors" else: return "Rock...
def move_left(t): """ A method that takes coordinates of bomb's position and returns coordinates of neighbour located at the left of the bomb. It returns None if there isn't such a neighbour """ x, y = t if y == 0: return None else: return (x, y - 1)
def index_schema(schema, path): """Index a JSON schema with a path-like string.""" for section in path.split("/"): if schema["type"] != "object": raise ValueError( "Only object types are supported in the schema structure, " "but saw type %s" % schema["type"] ...
def __get_mp_chunksize(dataset_size: int, num_processes: int) -> int: """ Returns the number of chunks to split the dataset into for multiprocessing. Args: dataset_size: size of the dataset num_processes: number of processes to use for multiprocessing Returns: Number of...
def pmap_dict_to_sitk(pmap_dict): """ Convert python dict to SimpleElastix ParameterMap Parameters ---------- pmap_dict SimpleElastix ParameterMap in python dictionary Returns ------- SimpleElastix ParameterMap of Python dict """ # pmap = sitk.ParameterMap() # pmap ...
def wildcard_in_db(namespace): """Return True if a wildcard character appears in the database name.""" return namespace.find('*') < namespace.find('.')
def count_pairs_distinct_unordered(arr, target): """ Counts the unordered pairs of distinct integers in arr that sum to target. """ comp_count = {} # Counts the number of times each complement occurs in arr. for num in arr: comp = target - num comp_count[comp] = comp_count.get(comp,...
def _par_indices(names): """ Given a list of objects, returns a mapping of objects in that list to the index or indices at which that object was found in the list. """ unique = {} for idx, name in enumerate(names): # Case insensitive name = name.upper() if name in unique...