content
stringlengths
42
6.51k
def build_intent_for_api(intent_name, questions, answer): """Build structure of intent for dialogflow API. :param intent_name: str, name of intent :param questions: iterable, iterable of questions :param answer: str, answer to question :return: dict, intent for api """ intent = {'display_nam...
def get_contrast(file): """ Get contrast from BIDS file name :param file: :return: """ return 'dwi' if file.split('_')[1] == 'dwi' else 'anat'
def greet(name): """Return a welcome message for the given person. @type name: str @rtype: str >>> greet('David') Hello, David! Welcome to CSC148. Hope you have a great time this term. :) """ return ('Hello, {}! Welcome to CSC148.'.format(name) + ' Hope you have a great time th...
def rename_column(name: str) -> str: """ Removes illegal column characters from a string :param name: String to format :return: """ illegals = [ ' ', ',', ';', '{', '}', '(', ')', '\t', '=', '/', '\\', ...
def _measure(line): """ Parse a measure line. Parse a measure line. Looks similar to the following: '# Measure BrainSeg, BrainSegVol, Brain Segmentation Volume, 1243340.000000, mm^3' Parameters ---------- line: string A stats line. Returns ------- list of strings A...
def flesch_reading_ease(n_syllables, n_words, n_sents, lang=None): """ Readability score usually in the range [0, 100], related (inversely) to :func:`flesch_kincaid_grade_level()`. Higher value => easier text. Note: Constant weights in this formula are language-dependent; if ``lang`` is ...
def _is_heater(name): """ returns true if the given name matches the heater name """ return name.strip().lower() == 'heater'
def without_last_method(form): """ Return a new form without last method from methods_stack """ stack = form[4][:-1] return form[:4] + (stack,)
def merge_dicts(x): """A quick function to combine dictionaries. Parameters ---------- x : list or array-like A list of dictionaries to merge. Returns ------- dict The merged dictionary. """ z = x[0].copy() # start with keys and values of x for y in x[1:]: ...
def genomic_dup5_abs_38(genomic_dup5_loc): """Create test fixture absolute copy number variation""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.BUEI9XPTvjBvNUoREsXRsm8THNuR5Fe7", "subject": genomic_dup5_loc, "copies": {"type": "Number", "value": 4} }
def ilen(iterator): """Return the size of an iterator.""" return sum(1 for i in iterator)
def calc_metric(predict_entities, ground_trues, entity_type): """ Calculate metric. @predict_entities: [[(entity_name, entity_type),...], ...] @ground_trues: [[(entity_name, entity_type),...], ...] """ assert len(predict_entities) == len(ground_trues) TP, FP, FN = 0, 0, 0 for pred, ...
def find_max_index(array): #INEFFICIENT """ """ max_val = None max_index = None for i in range(len(array)): if array[i] == None: max_index=i return max_index else: if (max_val == None) or (array[i]>max_val): max_val ...
def cross(x, eta_inf=0.001, eta_0=1.0, n=0.5, gammadot_crit=1.0): """cross Model Note: .. math:: \sigma= \dot\gamma \eta_{inf} + \dot\gamma (\eta_0 - \eta_{inf})/(1 + (\dot\gamma/\dot\gamma_c)^n) Args: ystress: yield stress [Pa] K : Consistency index [Pa s^n] n : Shea...
def _get_imm(asm_str): """return int for immediate string and check proper formatting (e.g "#42")""" if len(asm_str.split()) > 1: raise SyntaxError('Unexpected separator in immediate') if not asm_str.startswith('#'): raise SyntaxError('Missing \'#\' character at start of immediate') if n...
def assign_species(complexes): """ The nuskell naming standard for all types of species. """ fuels = [x for x in complexes.values() if x.name[0] == 'f'] wastes = [x for x in complexes.values() if x.name[0] == 'w'] intermediates = [x for x in complexes.values() if x.name[0] == 'i'] signals = [x for x...
def parse_start_byte(byte_val: int) -> int: """Start register""" assert 0 <= byte_val < 8 return byte_val
def sum_numbers(upper: int) -> int: """Calculate the sum of integers less than upper.""" n = upper - 1 return n * (n + 1) // 2
def minloc(seq): """ Return the index of the (first) minimum in seq >>> assert minloc(range(3)) == 0 """ return min(enumerate(seq), key=lambda s: s[1])[0]
def selectResults(resDataAll, X, ligIDs): """ Make a selection of the top X VS results, also as optional ligIDs """ # First select the top X ligands resDataTop = [row for row in resDataAll[0:X]] # If the ligID flag was used, select by ligIDs, the ligID is in row[1] # and return a combined ...
def newton_poly(coef, x_data, x): """ evaluate the Newton polynomial at x """ n = len(x_data) - 1 p = coef[n] for k in range(1,n+1): p = coef[n-k] + (x -x_data[n-k])*p return p
def remap_to_range(x, x_min, x_max, out_min, out_max): """convert x (in x_min..x_max range) to out_min..out_max range""" if x < x_min: return out_min elif x > x_max: return out_max else: ratio = (x - x_min) / (x_max - x_min) return out_min + ratio * (out_max - out_min)
def getPointOnLine(x1, y1, x2, y2, n): """Returns the (x, y) tuple of the point that has progressed a proportion n along the line defined by the two x, y coordinates. Copied from pytweening module. """ x = ((x2 - x1) * n) + x1 y = ((y2 - y1) * n) + y1 return (x, y)
def compile_tries(tries: dict) -> str: """Return a compilation of all the tries in a session. Argument(s): tries: dict -- a dictionary of all the tries in a session """ result = "\n" for index in tries: result += index + "\n" result += str(tries[index]) + "\n" return resul...
def architecture_is_64bit(arch): """ Check if the architecture specified in *arch* is 64-bit. :param str arch: The value to check. :rtype: bool """ return bool(arch.lower() in ('amd64', 'x86_64'))
def round_half(x): """Rounds a floating point number to exclusively the nearest 0.5 mark, rather than the nearest whole integer.""" x += 0.5 x = round(x) return x-0.5
def combined_group_name(stack_value, group_value): """Compute combined group name. :returns: Name of the combined group. :rtype: str """ return 'stack_{}_{}'.format(stack_value, group_value)
def category_name(value): """Maps category value to names""" return { 0: "idle", 1: "unassigned", 2: "work", 3: "private", 4: "break", }.get(value, "?")
def harmonic(n_numbers): """Calculate harmonic series, used for calculating MRR""" return sum([1.0/(i + 1) for i in range(n_numbers)])
def getLast(text, signs): """ Returns a position of the sign which occurs the last. @param {string} text. @param {Array.<string>} signs. @return {number} Position. """ positions = [text.rfind(sign) for sign in signs if text.rfind(sign) != -1] if positions: retur...
def parse_aunt_line(aunt_line): """ parse_aunt_line parses a string and return the aunt id and its attributes """ aunt_id = int(aunt_line[4:aunt_line.find(':')]) attributes = aunt_line[aunt_line.find(':')+1:].split(',') aunt = {} for attribute in attributes: name = attribute[:attribu...
def JoinOptionsList(cmd): """ For spawning processes using os.spawnv() to call Python, the options between double quotes (") must be put into just one element of the list. Turn the 'cmd' string into a list and consolidate all options between double quotes into one element. Currently not used, b...
def prepara_nome(nome): """prepara string para comparacao.""" return nome.replace(" ", "").replace("_", "").lower()
def cmp(a, b): """Compare two numbers.""" return (a > b) - (a < b)
def allowed_file(filename): """Check if file is a csv.""" return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ['csv']
def distance(strand_a, strand_b): """Calculates the Hamming distance between two strands. Args: strand_a: A string representing a DNA strand. strand_b: A string representing a DNA strand. Returns: An integer representing the Hamming Distance between the two strands. """ if ...
def append_to_argument(arguments, key, value, delimiter=","): """Looks for an argument of the form "key=val1,val2" within |arguments| and appends |value| to it. If the argument is not present in |arguments| it is added. Args: arguments: List of arguments for the shell. key: Identifier of the argument,...
def validate_params(params): """ Validate the parameters passed to KBParallel.run_batch Also refer to the type def for run_batch in KBParallel.spec """ if 'tasks' not in params or not params['tasks']: raise ValueError('"tasks" field with a list of tasks is required.') if 'runner' not in ...
def f12d3p(f, h, f0 = None): """ A three-point finite difference stencil. This function does either two computations or three, depending on whether the 'center' value is supplied. This is done in order to avoid recomputing the center value many times. The first derivative is evaluated using...
def make_tree(words): """ Method to transform parser data into a trie DS (keys stored as BST), aka nested hash map time complexity : O(M*logN), where M - max. string length, N - number of items, search - O(M) penalty - storage requirements """ ## creates our root dict() trie = dict() ...
def get_words(string): """ Extract individual words from a string. Discard blank words, and URLs """ all_words = [item.strip() for item in string.split(" ") if item] all_words = [item for item in all_words if len(item) >= 2 or item in {"i", "a"}] return [item for item in all_words if no...
def _create_tf_matrix(freq_matrix): """get term frequency Args: frequency matrix (dict) Returns: term frequency matrix """ tf_matrix = {} # frequency divide by length of document for sent, f_table in freq_matrix.items(): tf_table = {} count_words_in_...
def convert_to_hex(number, n=9): """ Convert number to hexadecimal notation Parameters ---------- number: :obj:`int` Number that has to be converted. n: :obj:`int`. Optional Length of the hexadecimal number. Default is 9. Returns ------- hex: :obj:`str` Hexadeci...
def flatten_list(my_list): """Flatten a list of lists into a single list.""" return [num for elem in my_list for num in elem]
def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ if len(L) == 0: return float('NaN') summ = 0 for i in L: summ += len(i) mean = summ / float(len(L)) tot = 0.0 ...
def save(data_array): """call save on each value in data_array then return data_array. Used for convenience""" for data in data_array: data.save() return data_array
def add_one(arr): """ :param: arr - list of digits representing some number x return a list with digits represengint (x + 1) """ counter = 0 arrLen = len(arr) while counter < arrLen: if arr[arrLen-counter-1] < 9: arr[arrLen-counter-1] += 1 return arr e...
def capitalize_fn(x): """ Takes "high_point", returns "High Point". Bad implementation, should have been taken care in keys() method and above get_unique_combinations() method. Needs too many changes to have same effect now. """ return x.replace("_", " ").title()
def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): # changed from xrange ntok *= n ktok *= t n -= 1 return ntok // ...
def tail_factorial( number: int, accumulator: int = 1, ) -> int: """Tail Recursive Factorial Function Args: number (int): [description] accumulator (int, optional): [description]. Defaults to 1. Returns: int: factorial of the number """ if number == 0: return accumulator ret...
def build_fnln_contact(individual_contact): """ Expected parameter format for individual_contact ('My Name', 'myname@gmail.com') Sample output: {'email': 'myname@gmail.com', 'name': 'My Name'} """ return { "email": individual_contact[-1], "name": individual_...
def convert_timeout(timeout, def_timeout=60): """Checks is timeout is numeric and return it, otherwise returns DEF_TIMEOUT.""" try: return float(timeout) except (TypeError, ValueError): return def_timeout
def create_pattern_neighbors_ca1d(width, n_states=2): """ Returns a list with the weights for 'neighbors' and 'center_idx' parameters of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...). The weights are responsible to calculate an unique number for each different neighborhood pattern. P...
def sort_dict(dict1): """ Takes a dictionary Returns a dictionary """ new_dict = {} alist = [] for keys in dict1: alist.append(keys) alist.sort() for i in alist: new_dict[i] = dict1[i] return new_dict
def split_numeric(s): """ Split a string into numeric and non-numeric parts """ num, alpha = [], [] for c in s: if c.isdigit(): num.append(c) else: alpha.append(c) return ''.join(num), ''.join(alpha)
def _locations_tolist(x): """Transforms recursively a list of iterables into a list of list. """ if hasattr(x, '__iter__'): return list(map(_locations_tolist, x)) else: return x
def get_percent_diff(old_value, new_value): """100(1 - old/new) gives percent diff""" return round(100 * (1 - old_value/new_value), 2)
def wants_other_orders(responses, derived): """ Return whether or not the user wants other orders """ return 'Other orders' in derived['orders_wanted']
def remoteAddAuthor(author): """ Creates an Author dictionary :param author: Author instance :return: Dict """ author_dict = dict() author_dict['id'] = author.get('id') author_dict['host'] = author.get('host') author_dict['displayName'] = author.get('displayName') author_dict['g...
def find_representative_points(representative_points_coll, service_area, logger=None): """Given a standard service_area, return corresponding representative points from db.""" key_map = {'countyName': 'ServiceArea.CountyName', 'zipCode': 'ServiceArea.ZipCode'} try: area = dict((key_map[k], v) for k,...
def dh2hms(dh, format="{:02d}:{:02d}:{:06.3f}"): """Decimal hours as HH:MM:SS.SSS, or similar. Will work for degrees, too. Parameters ---------- dh : float format : string, optional Use this format, e.g., for [+/-]HH:MM, use "{:+02d}:{:02d}". Returns ------- hms : string ...
def tooltip_content_id(some_text): """ Generate a tooltip ID. :param str some_text: some text for the id suffix :return: tooltip id """ return 'tooltip-{}'.format(some_text.lower().replace('_', '-'))
def radius(R, H, h): """ find the horizontal distance of the intersection at y = h of the line from (0, H) to (R, 0) """ if 0 <= h <= H: r = R - (R * h) / H return r else: print("radius function: height is not in range")
def _findbits(fp, bitsperint): """Find which bits are set in a list/vector. This function is used by the Fingerprint class. >>> _findbits([13, 71], 8) [1, 3, 4, 9, 10, 11, 15] """ ans = [] start = 1 for x in fp: i = start while x > 0: if x % 2: ...
def _insert_branch_specs(bspecs, lengths): """Given a list of lengths, sequentially assign values to the max length of each cluster size, beginning with pairs. :bspecs: dict :lengths: list of float :returns: dict """ clust_sizes=[i+2 for i in range(len(lengths))] bspecs["orbit_branch_s...
def create_collapsible(results): """Creates a collapsible html element for a search result Args: - results (dict): mapping of result attributes Returns: - collapsible_data (list): list result attributes in order for collapsible element """ collapsible_data = [] for i ...
def get_missing_params_msg(param_name): """Util function to return error response when a parameter is missing :param param_name: the missing parameter :type param_name: str """ import json return json.dumps({'success': False, 'message': 'Missing parameter: {}'.format(param_name)}).encode('utf-8...
def process_sequence(sequence, word_to_n, word_freq): """ Generates a list of numbers from list of words or list of list of numbers from list of list of words """ if type(sequence[0]) == list: return [process_sequence(s, word_to_n, word_freq) for s in sequence] result = [] for w in seque...
def default_freeze_dataset_task_spec(dtool_config): """Provide default test task_spec for FreezeDatasetTask.""" return { 'dtool_config': dtool_config, 'stored_data': True, }
def apply_feat_fns(tuple1, tuple2, feat_dict): """ Apply feature functions to two tuples. """ # Get the feature names feat_names = list(feat_dict['feature_name']) # Get the feature functions feat_funcs = list(feat_dict['function']) # Compute the feature value by applying the feature func...
def plurality(d): """ Return, for input dict d mapping vids to (real) counts, vid with largest count. (Tie-breaking done arbitrarily here.) """ max_cnt = -1e90 max_vid = None for vid in d: if d[vid]>max_cnt: max_cnt = d[vid] max_vid = vid return max_vid
def count_evens(nums): """ Count even numbers. Return the number of even integers in the given array. Args: nums (Array): Array with integers items """ count = 0 for num in nums: if num % 2 == 0: count += 1 return count
def get_token_list(text): """Returns a list of tokens. This function expects that the tokens in the text are separated by space character(s). Example: "ca n't , touch". This is the case at least for the public DiscoFuse and WikiSplit datasets. Args: text: String to be split into tokens. ...
def dict_invert(d): """inverts a dictionary with immutable values Takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is ...
def reverter_palavras2(frase: str): """ >>> reverter_palavras('the sky is blue') 'blue is sky the' :param frase: :return: """ palavras_separadas = frase.split(' ') # ['the', 'sky', 'is', 'blue'] palavras_separadas.reverse() # ['blue', 'is', 'the', 'sky'] r...
def is_sequence(arg): """Returns True is passed arg is a list or a tuple""" return isinstance(arg, list) or isinstance(arg, tuple)
def Binary(string: str) -> bytes: # pylint: disable=invalid-name """constructs an object capable of holding a binary (long) string value.""" return string.encode()
def get_sample_labels_value(sample): """Extract the labels and values of a sample. prometheus_client 0.5 changed the sample type to a named tuple with more members than the plain tuple had in 0.4 and earlier. This function can extract the labels and value from the sample for both sample types. Arg...
def f(x, y=0, z=0): """ A module-level function so that it can be spawn with multiprocessing. """ return x ** 2 + y + z
def preprocess_sentence(sentence: str) -> str: """ The idea is to have this as clean as possible to match the embeddings. In the meantime I'll just keep alphabetic characters amd remove all white space chars. """ return ''.join([c for c in ' '.join(sentence.split()) if c.isalpha...
def normURLPath(path): """ Normalise the URL path by resolving segments of '.' and '..'. """ segs = [] pathSegs = path.split('/') for seg in pathSegs: if seg == '.': pass elif seg == '..': if segs: segs.pop() else: seg...
def is_bool(val): """Checks that value is a boolean. Args: val (str): string value verify. Returns: bool: True if value stands for boolean, False otherwise. """ return val.lower() in ["true", "false"]
def FIT(individual): """Sphere test objective function. F(x) = sum_{i=1}^d xi^2 d=1,2,3,... Range: [-100,100] Minima: 0 """ y=sum(x**2 for x in individual) return y
def first_item(value, separator): """ It returns the key part of a string. """ return value.split(separator, 1)[0]
def dicom_strfname( names: tuple) -> str: """ doe john s -> dicome name (DOE^JOHN^S) """ return "^".join(names)
def is_valid_parentheses(s: str) -> bool: """ >>> is_valid_parentheses('()[]{}') True """ if not s or len(s) % 2 != 0: return False stk = [] for bracket in s: if bracket not in "({[)]}": return False if bracket in "({[": stk.append(bracket) ...
def world2pixel(x,y,w,h,bbox): """Converts world coordinates to image pixel coordinates""" # Bounding box of the map minx,miny,maxx,maxy=bbox # world x distance xdist=maxx-minx # world y distance ydist=maxy-miny # scaling factors for x,y xratio = w/xdist yratio = h/ydist # Calculate ...
def _getWordCount(start, length, bits): """ Get the number of words that the requested bits would occupy. We have to take into account how many bits are in a word and the fact that the number of requested bits can span multipe words. """ newStart = start % bits newEnd = newStart...
def find_interaction_type(value): """Finds name of interaction from shorthand interaction value. Parameters ---------- value: str Two character string referring to an interaction type. """ if value == 'in': value = 'inhibition' elif value == 'co': ...
def ips_to_metric(d, min_depth, max_depth): """ https://github.com/fyu/tiny/blob/4572a056fd92696a3a970c2cffd3ba1dae0b8ea0/src/sweep_planes.cc#L204 Args: d: inverse perspective sampling [0, 1] min_depth: in meter max_depth: in meter Returns: """ return (max_depth * min_...
def attributes_to_codes(attributes): """Convert a set of attributes to ANSI escape codes.""" return [int(attr.value) for attr in attributes]
def _parse_regulon_string(model, s): """ The Bacillus microarray dataset uses [] to create unusually complicated TF strings. This function parses those, as a helper to _get_reg_genes for imdb_regulon_venn_df. Parameters ---------- model : :class:`~pymodulon.core.IcaData` IcaData obj...
def abbrv(num): """ Shortens the amount so it will have a letter at the end to indicate the place value of the number (e.g. 1,500 -> 1.5K) This goes upto trillion. """ abbrv = {"T": 1_000_000_000_000, "B": 1_000_000_000, "M": 1_000_000, "K": 1000} for abbrv_value in abbrv.values(): if nu...
def perfLocked(host, cmdSsh, cmdSudo, cmdRun): """This is a host command modifier that takes a performance lock using 'perflock' while the remote RPC server is running.""" if cmdSudo: # Hosts always make a regular connection before a root # connection and we wouldn't want to deadlock with o...
def _combine_parsed_configs(old_payload): """ Combines config files into one by using include directives. :param old_payload: payload that's normally returned by parse() :return: the new combined payload """ old_configs = old_payload['config'] def _perform_includes(block): for stmt...
def hits_at_k(preds, ans, k): """accepts list of predictions and answers""" preds_k = preds[:k] any_in = lambda a, b: bool(set(a).intersection(b)) return any_in(preds_k, ans)
def does_have_links(text): """Returns True if a link is present in the text. Else returns False""" link = "http" if link in text: return "1" else: return "0"
def F_to_C(val): """ Convert Farenheit value to Celsius Inputs: ------- val -> numeric value (hopefully in F) Outputs: -------- -> converted value """ return (val-32.)*5./9.
def HPX_grid_size(Nside): """Return the size of the pixel grid (Nx, Ny) for a given Nside""" Nx = 8 * Nside Ny = 4 * Nside + 1 return Nx, Ny
def p_prefix(pre): """ Get instruction prefix string :param pre: True if prefix present :return: prefix string """ return ' lock ' if pre else ''