content
stringlengths
42
6.51k
def dot(x: dict, y: dict): """Returns the dot product of two vectors represented as dicts. Example: >>> x = {'x0': 1, 'x1': 2} >>> y = {'x1': 21, 'x2': 3} >>> dot(x, y) 42 """ return sum(xi * y.get(i, 0) for i, xi in min(x, y, key=len).items())
def parse_list(entry, valid, default): """ parsing entries entry - value to check valid - valid range default - value if entry is invalid return - entry or default if entry is out of range """ if entry in valid: result = entry else: result = default return result
def meanstdv(members): """ Calculate mean and standard deviation of data x[]: mean = {\sum_i x_i \over n} std = sqrt(\sum_i (x_i - mean)^2 \over n-1) """ from math import sqrt num, mean, std = len(members), 0, 0 for item in members: mean = mean + item mean = mean / float(num) for item in...
def filter_providers_by_type(providers, type): """ helper function to filter a list of providers by type :param providers: ``list`` :param type: str :returns: filtered ``dict`` provider """ providers_ = {provider['type']: provider for provider in providers} return providers_.get(type,...
def get_setting(key, paired_attributes, meta=None, default_value="", remove=False): """ Looks at the attributes of the code and the metadata of the document (in that order) and returns the value when it finds one with the specified key. :param key: The key or keys that should be searched for. Only the ...
def generate_objects(columns): """ Reorganizes the table columns into an object-format Args: columns: A list of table columns Returns: List of objects. """ objects = [] for i in range(0, len(columns[0])): this_obj = [] for j in range(0, len(columns)): ...
def sum_diagonals(side_length): """Sums diagonals of a number spiral with given side length.""" total = 25 bottom_corner = 3 for s in range(5, side_length+2, 2): bottom_corner += 4*s - 10 for c in range(4): total += bottom_corner + (s-1)*c return total
def get_variance_level(preprocess_config, model_config, data_loading=True): """ Consider the fact that there is no pre-extracted phoneme-level variance features in unsupervised duration modeling. Outputs: pitch_level_tag, energy_level_tag: ["frame", "phone"] If data_loading is set True, ...
def rename_duplicate_fovs(tma_fovs): """Identify and rename duplicate FOV names in `fov_list` For a given FOV name, the subsequent duplicates get renamed `{FOV}_duplicate{n}` Args: tma_fovs (dict): The TMA run JSON, should contain a `'fovs'` key defining the list of FOVs Returns: ...
def find_duplicates(list_of,name_of): """ """ duplicates=[] duplicates=set([x for x in list_of if list_of.count(x) > 1]) if (len(duplicates)>0): print("duplicate "+name_of+" index found") print(duplicates) return duplicates
def merge_hist(hist1, hist2): """ Merge two hist-dicts. Args: hist1 (dict): Hist dict from fit. hist2 (dict): Hist dict from fit. Returns: outhist (dict): hist1 + hist2. """ outhist = {} for x, y in hist1.items(): outhist.update({x: hist1[x] + hist2[x]}) ...
def decipher_rsa(ct, prk): """ In RSA, a ciphertext `c` is decrypted by computing `c^d` (mod `n`), where ``prk`` is the private key `(n, d)`. Examples ======== >>> from sympy.crypto.crypto import decipher_rsa, rsa_private_key >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) ...
def find_this_ij(k_target, Xlist): """@@@ This one may be basically specific to the single method (scan_for_ss) in Vienna2TreeNode. Anyway, it is able to process objects of class Pair (from Vienna). So, for the moment, I leave it as a Vienna tool for that reason. """ debug_find_th...
def shallow_copy_sets(training_sets): """Return shallow copy of training data, where the numpy arrays are not copied, but the dicts are deep-copied.""" result = {} for name, d in training_sets.items(): result[name] = dict(d) return result
def make_virtual_offset(block_start_offset, within_block_offset): """Compute a BGZF virtual offset from block start and within block offsets. The BAM indexing scheme records read positions using a 64 bit 'virtual offset', comprising in C terms: block_start_offset << 16 | within_block_offset Here blo...
def getchapter(chapter): """To change chapter number into desired format for saving""" chapter = str(chapter) if int(chapter) < 10: chapter = '00' + chapter elif int(chapter) < 100: chapter = '0' + chapter return chapter
def _unpack_parameters(parameters, key): """Unpacks the values from a dictionary containing various parameters for pymaws Parameters ---------- parameters : dict planetary parameters dict with keys: angular_frequency: float, (rad/sec) gravitational_acceleration: floa...
def _depth_count(x): """Return maximum depth of the returned list. Parameters ---------- x : list. Return ------ ans : int maximum depth. """ return int(isinstance(x, list)) and len(x) and 1 + max(map(_depth_count, x))
def clamp(v: float, minVal: float, maxVal: float): """ Component-wise clamp In case v is smaller than minVal, minVal is returned. If v is larger than maxVal, maxVal is returned. :param v: vector to clamp :param minVal: minimal value (component-wise) :param maxVal: m...
def _merge(a: str, b: str) -> str: """ Merge two sides of the card into a single piece of markdown """ return '\n---\n'.join([a, b])
def add_vectors(vec_1, vec_2): """ adds two vectors: non-array results vec_1 & vec_2: XYZ components of the vectors. returns: list of resulting vector """ return [a+b for (a, b) in zip(vec_1, vec_2)]
def test_decorated_function_with_defaults(a, b=2, c='Hello'): """Test Decorated Function With Defaults Docstring.""" return [a, b, c]
def list2dict(listvar): """Transform list to dict :param listvar: [description] :type listvar: [type] :return: [description] :rtype: [type] """ resultdict = {} for item in listvar: key = list(item.keys())[0] resultdict[key] = item[key] return resultdict
def data_ref_type_str(dref_enum): """ Translate an ``enum DataRefTypes`` value into a string representation. """ if dref_enum == 0x9000: return 'unknown' elif dref_enum == 0x9001: return 'integer' elif dref_enum == 0x9002: return 'fp' else: return 'INVALID'
def remove_unencodable(str_): """ :type str_: str :param str_: string to remove unencodable character :return: string removed unencodable character """ s = str_.replace('\xb2', '') s = s.replace('\u2013', '') s = s.replace('\u2019', '') return s
def trap2(height): """ Solution 2: Dynamic programming """ if height is None or len(height) == 0: return 0 result = 0 size = len(height) max_left = [0 for i in range(size)] max_left[0] = height[0] for i in range(1, size): max_left[i] = max(max_left[i - 1], height[i]) ...
def compute_nodes(nworker, taskproc, nodeprocs): """Compute number of nodes for the number of workers. Args: nworker (int): The number of workers. taskproc (int): The number of processes per task. nodeprocs (int): The number of processes per node. Returns: (int): The nu...
def keyfunc(l1): """ Splitter function to customize the results of groupby. This splits a group up and then runs keyfunc on each split up part. """ l1=l1+'B' return l1
def extract_notes(record, reverse=False): """ Synthesize notes from record fields. """ notes = "" sep = "" if record["Type"] == "PP": if reverse: notes += "(Reversed) to {}, {}".format( record["Start City"], record["Start State"]) else: n...
def energyConversion(energy,unit): """ Returns the energy in keV """ if unit == 'keV': return float(energy) elif unit == 'MeV': return float(energy)*1000 elif unit == 'eV': return float(energy)/1000 else: raise ValueError('Unkown unit {}!'.format(unit))
def calc_padding_1d(input_size, kernel_size, stride=1, dilation=1): """ Calculate the padding. """ # i = input # o = output # p = padding # k = kernel_size # s = stride # d = dilation # the equation is # o = [i + 2 * p - k - (k - 1) * (d - 1)] / s + 1 # give that we want...
def pandoc_command(event, verbose=True): #@+<< pandoc command docstring >> #@+node:ekr.20191006153547.1: *4* << pandoc command docstring >> """ The pandoc command writes all @pandoc nodes in the selected tree to the files given in each @pandoc node. If no @pandoc nodes are found, the command loo...
def extract_container_id_removal(line): """ Extract container id from a Removing line Removing intermediate container 816abeca3961 """ parts = line.strip().split(' ') if len(parts) == 4: return parts[3] else: raise Exception("Unrecognized docker removing line: " + l...
def convert_str_to_list(input_string): """ Convert string to list """ l = input_string.split(",") return [item.strip(' ') for item in l]
def get_params_description(doc): """Get the parameters description from the docstring""" params_description = {} if doc is not None: doc = doc.split('\n') for line in doc: if ':' in line: line = line.split(':') line[0] = line[0].strip() ...
def parseQclass(qclass): """ parseQclass(qclass): Get a text label for our class """ if qclass == 1: retval = "IN" else: retval = "Unknown! (%s)" % qclass return(retval)
def checkUniqueness(some_list): """ Verifies that every entry in a list is unique. If it is not, it returns non-unique values. """ unique_list = dict([(x,[]) for x in some_list]).keys() repeated_entries = [u for u in unique_list if len([s for s in some_list if s == u])...
def _snake_to_dromedary_case(string): """Convert snake_case to dromedaryCase. >>> _snake_to_dromedary_case('snake_case') 'snakeCase' >>> _snake_to_dromedary_case('longer_snake_case_name') 'longerSnakeCaseName' """ words = string.split("_") if len(words) > 1: words[1:] = [w.title...
def sequential(inputs, layers, ): """Applies a sequence of layers to an input.""" output = inputs for layer in layers.values(): output = layer(output) return output
def get_stage_id_for_convnext(var_name, max_stage_id): """Get the stage id to set the different learning rates in ``stage_wise`` decay_type. Args: var_name (str): The key of the model. max_stage_id (int): Maximum stage id. Returns: int: The id number corresponding to different ...
def compare_math_formula(query, formula): """Compares two math tuples Parameters: query: the query math tuple (str) formula: the formula math tuple (str) Returns: same: True if tuples are considered equal (boolean) """ if "'*'" in query: # break on the wild card ...
def reverseWords(s): """ :type s: str :rtype: str """ words = s.split() return ' '.join(words[::-1])
def is_trueish(expression: str) -> bool: """True if string and "True", "Yes", "On" (ignorecase), False otherwise""" expression = str(expression).strip().lower() return expression in {'true', 'yes', 'on'}
def update_eval_values(tp: int, tn: int, fp: int, fn: int, predicted_target:bool, real_target:bool): """ Updates matrix of _________________________________ | True Positive | False Positive | --------------------------------- | False Negative | True Negative | ___________________...
def bb_iou(boxA, boxB, format="coco"): """ based on https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ """ if format == "coco": boxA = [float(boxA[0]),\ float(boxA[1]),\ float(boxA[0]+boxA[2]),\ float(boxA[1]...
def scale_from_proportional(valueslist,bounds): """ The opposite of _scale_to_proportional: returns values scaled between bounds NB if values are not first scaled to between 0 and 1, the results are confusing... """ lowbound,highbound=bounds return [((highbound-lowbound)*v) +lowbound for v...
def response(hey_bob): """ Returns Bob's response to what we say Parameters ---------- hey_bob: String What is said to Bob Returns ------- String Bob's response """ hey_bob = hey_bob.rstrip() if hey_bob.endswith('?'): if hey_bob.isupper(): ...
def edit_distance(s1, s2): """Calculates the Levenshtein distance between two strings.""" if s1 == s2: # if equal, then distance is zero return 0 m, n = len(s1), len(s2) # if one string is empty, then distance is the length of the other string if not s1: return n elif not s2: ...
def getHashStateSet(object_list, state): """ Used to compare prior node state to current """ return set( [hash(obj) for obj in object_list if obj.Status == state])
def frequencies(colorings): """ Procedure for computing the frequency of each colour in a given coloring. :param colorings: The given coloring. :return: An array of colour frequencies. """ maxvalue = -1 frequency = [0] * (len(colorings)) for i in colorings: maxvalue = max(maxvalu...
def cleanup_code(content): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n')
def _transpose_if_needed(*args, transpose=False, section=slice(None)): """ This function takes a list of arrays and returns them (or a section of them), either untouched, or transposed, according to the parameter. Parameters ---------- args : sequence of arrays The input arrays. tr...
def primes(imax): """ Returns prime numbers up to imax. Parameters ---------- imax: int The number of primes to return. This should be less or equal to 10000. Returns ------- result: list The list of prime numbers. """ p = list(range(10000)) result = [] ...
def is_weekend_worked(x, wkend_type, i): """ Determine if i'th weekend is worked (full or half) for a given weekend pattern x and weekend type, :param x: list of 2-tuples representing weekend days worked. Each list element is one week. The tuple of binary values represent the fi...
def check_subset_sum(items, target_sum): """ Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. """ size = len(items) ''' subset[i][j] will be true if there is a subset of set[0..j-1] whose sum is target_sum ''' subset = [...
def CubicTimeScaling(Tf, t): """Computes s(t) for a cubic time scaling :param Tf: Total time of the motion in seconds from rest to rest :param t: The current time t satisfying 0 < t < Tf :return: The path parameter s(t) corresponding to a third-order polynomial motion that begins and ends a...
def _get_switch_info(switch_info, host_id): """Get the chassis IP and server ID the host_id belongs to.""" for switch_ip in switch_info: if host_id in switch_info[switch_ip]: info = switch_info[switch_ip][host_id].split(",") return (switch_ip, info[0], info[1:]) return (None,...
def dms2dd(dms): """ d must be negative for S and W. """ d, m, s = dms return d + m/60. + s/3600.
def get_single_regex(filters, ids): """given a list of filters and ids returns a single regex for matching""" filters = [] if filters is None else filters ids = [] if ids is None else ["{}[.][0-9]+[.]xml".format(x) for x in ids] return "|".join(filters + ids) if filters is not None else ""
def onestring(scaffold_key, has_inchikey=False): """ This function can be used to convert scaffold key into a fixed-length string so it can be used to sort scaffold keys simply alphanumerically. """ tmp = scaffold_key.split(' ') tmp2 = [] res = '' if has_inchikey: tmp2 = tmp[:-1...
def align_seq_to_model(domains, sequence): """ align result of hmmscan with uniprot sequence """ hmmfrom = domains["alihmmfrom"] hmmto = domains["alihmmto"] consensus = domains["alimodel"] aliseq = domains["aliaseq"] alisqfrom = domains["alisqfrom"] alisqto = domains["alisqto"] ...
def list_average(score_list): """ Utility function to get the average of a list. Args: score_list: List containing real numbers that must be averaged Returns: Float representing the average of the values in the provided list """ if len(score_list) == 0: return -100 ...
def _extract_version(version): """From a raw version string, extract the semantic version number. Input: `Swift Package Manager - Swift 5.4.0` Output: `5.4.0` Args: version: A `string` which has the semantic version embedded at the end. Returns: A `string` representing the semanti...
def int_median_cutter(lower_bound: int, upper_bound: int, value: int): """ Simple function for cutting values to fit between bounds Args: lower_bound (int): lower cutting bound upper_bound (int): upper cutting bound value (int): value to fit between bounds Returns: ...
def ClearFlag(arg): """Clear the value for a flag.""" del arg return None
def _dict_to_scss(data): """Create a scss variables string from a dict.""" lines = [] template = "${}: {};" for key, value in data.items(): line = template.format(key, value) lines.append(line) return '\n'.join(lines)
def get_fields_for_l3_plot(product: str, model: str) -> list: """Return list of variables and maximum altitude for Cloudnet quicklooks. Args: product (str): Name of product, e.g., 'iwc'. model (str): Name of the model, e.g., 'ecmwf'. Returns: list: List of wanted variables """ ...
def __eval_all_locators(input_list, return_exec=False, return_exec_name="evaluated_locators"): """ :param input_list: :type list of namedtuple(locator,key,value). An example of this is the ValueFinder tuple :param return_exec: :type boolean: flag for whether to return a code string that can be run through e...
def discreteGridPosToID(x: int, y: int = 0, width: int = 0, z: int = 0, height: int = 0): """Returns a unique number of based on the x, y and z coordinates entered. Uniqueness is dimension dependent""" return (z * width * height) + (y * width) + x
def mp_ab_vs_cd(a, b, c, d): # <<< """Tests rigorously if ab is greater than, equal to, or less than cd, given integers (a, b, c, d). In most cases a quick decision is reached. The result is +1, 0, or -1 in the three respective cases. See mpmath.pdf (item 33).""" if a*b == c*d: return 0 ...
def filter_item_properties(items, propertyNames): """Filters properties from items by propertyName""" filtered = [] for item in items: filtered.append( { propertyName: item[propertyName] for propertyName in propertyNames } ) return ...
def clean_empty(d): """ recurse through the hierarchy deleting empty dicts """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (clean_empty(v) for v in d) if v] return {k: v for k, v in ((k, clean_empty(v)) for k, v in d.items()) if v}
def error_in_flux(e_magnitude, flux): """Calculate the error from flux from the error in magnitude. Parameters ---------- e_magnitude: float The error in the magnitude calculation. flux: float The value of the flux. Returns ------- error: float The error in the ...
def is_arm(s): """Return whether s is a arm.""" return type(s) == list and len(s) == 3 and s[0] == 'arm'
def validate_build_argument(string, is_secret): """Extracts a single build argument in key[=value] format. """ if string: comps = string.split('=', 1) if len(comps) > 1: return {'type': 'DockerBuildArgument', 'name': comps[0], 'value': comps[1], 'isSecret': is_secret} return ...
def parse_int(val): """ C99-Section 6.4.4.1 """ if val.startswith("0x"): return int(val, base=16) elif val.startswith("0"): return int(val, base=8) else: return int(val)
def rename_candidate_hugo(candidate, renamings): """Renames a candidate name according to a renaming map.""" candidate_split = candidate.split("_") name_expr = candidate_split[0].split(".") base_name = name_expr[0] if base_name in renamings: base_name = renamings[base_name] name_expr[0] ...
def get_expected_scaling_method(training_config): """ get expected scaling method from the parsed training configuration (description.json) """ dataset_props = training_config.get("dataset_props") if not dataset_props: return preprocess_options = dataset_props.get("preprocess") if no...
def parse_priv_from_db(db_privileges): """ Common utility function to parse privileges retrieved from database. """ acl = { 'grantor': db_privileges['grantor'], 'grantee': db_privileges['grantee'], 'privileges': [] } privileges = [] for idx, priv in enumerate(db_priv...
def get_shortstr(s): """ Return the first part of a string before a semicolon. Extract the first, highest-ranked protein ID from a string containing protein IDs in MaxQuant output format: e.g. P07830;P63267;Q54A44;P63268 :param s: protein IDs in MaxQuant format :type s: str or unicode :re...
def validate_template_uid(uid): """ Validates that template have valid name """ # now that we can reference template just with the name, # just return true here, and more validation will happens # later when instantiating services return True
def compute_single_layer_rf(out, f, s): """ compute receptive field of single layer :param out: number of neurons in output :param f: kernel size :param s: stride :return: """ return s * (out - 1) + f
def should_ensure_cfn_bucket(outline, dump): """Test whether access to the cloudformation template bucket is required. Args: outline (bool): The outline action. dump (bool): The dump action. Returns: bool: If access to CF bucket is needed, return True. """ return not outli...
def get_n_minutes(row): """ Cleans chat time data from H:M to just minutes """ time_components = row.split(':') if len(time_components) == 2: return int(time_components[0]) * 60 + int(time_components[1]) elif len(time_components) == 3: return int(time_components[0]) * 1440 + int(...
def cached_fibo_rec(num): """Recursive Fibo.""" return num if num <= 1 else cached_fibo_rec(num - 1) + cached_fibo_rec(num - 2)
def pick_wm_prob_2(probability_maps): """Returns the white matter probability map from the list of segmented probability maps Parameters ---------- probability_maps : list (string) List of Probability Maps Returns ------- file : string Path to segment_prob_2.nii.gz is ret...
def avscale(matrixfile): """Wrapper for the ``avscale`` command. Required options: :arg matrixfile: FLIRT transformation matrix """ cmd = ['avscale', '--allparams', matrixfile] return cmd
def get_item(dictionary, key): """Used to get how much of an item user has in its cart from a template anywhere in the app.""" if dictionary is None: return None return dictionary.get(str(key))
def getbool(value, default=None, truevalues=set((True, 1, '1', 't', 'true')), falsevalues=set((False, 0, '0', 'f', 'false'))): """Convert a given value to True, False, or a default value. If the given value is in the given truevalues, True is retuned. If the given value is i...
def get_year(data): """[We want to remove day and mounth] Args: data ([str]): [Data in Day Mounth Year format] Returns: [str]: [Year] """ return str(data).split()[-1].strip()
def chunk_up_string(string_to_chunk, size_of_chunk=100): """ Function to chunk up a string, and make a list of chunks :type string_to_chunk: String :param string_to_chunk: The string you want to chunk up :type size_of_chunk: Integer :param size_of_chunk: The size of the chunks in characters ...
def is_nova_server(resource): """ checks resource is a nova server """ return ( isinstance(resource, dict) and "type" in resource and "properties" in resource and resource.get("type") == "OS::Nova::Server" )
def validate_float(data): """ Checks if data contains something that can be used as float: - string containing float - int - float itself and converts it to float. Return: - float if possible - 0.0 if empty string - None if float not possible """ if isinstance(data, str): if len(data) > 0: if data.ls...
def _combine_regex(*regexes: str) -> str: """Combine a number of regexes in to a single regex. Returns: str: New regex with all regexes ORed together. """ return "|".join(regexes)
def redact_mobile_number(mobile_string): """Takes a mobile number as a string, and redacts all but the last 3 digits""" return str.format('XXXXX XXX{0}', mobile_string[-3:])
def profile_last_jump_from_step(value): """0 - 99""" return {'step':value}
def count_above(obj, n): """ Return tally of numbers in obj, and sublists of obj, that are over n, if obj is a list. Otherwise, if obj is a number over n, return 1. Otherwise return 0. >>> count_above(17, 19) 0 >>> count_above(19, 17) 1 >>> count_above([17, 18, 19, 20], 18) 2 ...
def _quantize_gq(raw_gq, binsize): """Returns a quantized value of GQ in units of binsize. Args: raw_gq: int. The raw GQ value to quantize. binsize: positive int. The size of bins to quantize within. Returns: A quantized GQ integer. """ if raw_gq < 1: return 0 else: bin_number = (raw_g...
def _rclone_verbosity_flag(verbose: bool) -> str: """ Verbosity flag to use with ``rclone``. """ if verbose: return '-vv' return '-v'
def copy_and_change_list(numbers): """ Returns a copy of the given list, but with the last item in the copy being one larger than the last item in the given list. """ copy = [] for k in range(len(numbers)): copy = copy + [numbers[k]] copy[len(copy) - 1] = copy[(len(copy) - 1)] + 1 ...