content
stringlengths
42
6.51k
def propose(prop, seq): """wrapper to access a dictionary even for non present keys""" if seq in prop: return prop[seq] else: return None
def _find_run_id(traces, item_id): """Find newest run_id for an automation.""" for trace in reversed(traces): if trace["item_id"] == item_id: return trace["run_id"] return None
def encode_ark(ark): """Replaces (encodes) backslashes in the Ark identifier.""" return ark.replace('/', '%2f')
def name_all_arguments(all_parameters, args, kwargs): """ This function merges positional and keyword arguments into one dictionary based on the declared names of the function's parameters. """ merged = {**kwargs} for arg_name, arg in zip(all_parameters, args): merged[arg_name] = arg...
def auth_path(index, height): """Return the authentication path for a leaf at the given index. Keyword arguments: index -- the leaf's index, in range [0, 2^height - 1] height -- the height of the binary hash tree Returns: The authentication path of the leaf at the given index as a list of nod...
def entity_tag(length, tag_fmt="IOB"): """ IO, IOB, or IOBES (equiv. to BILOU) tagging :param tokens: :param is_heads: :param tag_fmt: :return: """ tags = ['O'] * length tag_fmt = set(tag_fmt) if tag_fmt == set("IOB"): tags[0] = 'B' tags[1:] = len(tags[1:]) * "I...
def generator_expression(function, argument_list): """Apply a univariate function to a list of arguments in a serial fashion. Uses Python's built-in generator expressions. Args: function: A callable object that accepts one argument argument_list: An iterable object of input arguments ...
def soft_timing(Nframes, time, fpsmin=10, fpsmax=20): """determines time & fps; aims for target time, but forces fpsmin < fps < fpsmax. example usage: target 3 seconds, but force 10 < fps < 25: import QOL.animations as aqol for i in range(50): code_that_makes_plot_number_i() ...
def generalReplacements(tex): """ Replace the common Latex macros that take in no arguments and all Latex definitions that contain a backslash (which may have unde- fined behavior in the actual manpage). Some text may need to be processed separately if it is followed by a period, which will c...
def _get_guid_from_row(row): """ Given a row from the manifest, return the field representing expected mds guid. Args: row (dict): column_name:row_value Returns: str: guid """ guid = row.get("guid") if not guid: guid = row.get("GUID") return guid
def cloud_comparison(labels_x, labels_y): """Create lists that include all words unique to each of the two clouds""" only_x = [] only_y = [] for label in labels_x: if label not in labels_y: only_x.append(label) for label in labels_y: if label not in labels_x: ...
def insertion_sort(array): """ Insertion sort implementation Arguments: - array : (int[]) array of int to sort Returns: - array : (int[]) sorted numbers """ for i in range(len(array)): j = i while j > 0 and array[j] < array[j-1]: array[j], array[j-1] = a...
def to_identifier(key): """Converts given key to identifier, interpretable by TaskJuggler as a task-identifier Args: key (str): Key to be converted Returns: str: Valid task-identifier based on given key """ return key.replace('-', '_')
def merge_dict(base, delta, merge_lists=False, skip_empty=False, no_dupes=True, new_only=False): """ Recursively merges two dictionaries including dictionaries within dictionaries. Args: base: Target for merge delta: Dictionary to merge into base ...
def perimeterRect(length: float, breadth: float) -> float: """Finds perimeter of rectangle""" perimeter: float = 2 * (length + breadth) return perimeter
def varint(num): """ Bitshares(MIT) varint encoding normally saves memory on smaller numbers yet retains ability to represent numbers of any magnitude """ data = b"" while num >= 0x80: data += bytes([(num & 0x7F) | 0x80]) num >>= 7 data += bytes([num]) return data
def reformat_clip_range(clip_range): """Given the clip_range defined in excel, reformat it to go into ANUGA. This includes treating strings appropriately using very large hard coded numbers """ assert len(clip_range[0]) == 2 l = len(clip_range) output = list() for i in range(l...
def cint(val): """ Returns ------- returns an int value """ try: return int(val) except: return int(0)
def do_calculation(first_operand: int, second_operand: int, operator: str): """ This is a helper function that solves a simple math operation >>> do_calculation(2, 3, "+") 5 """ if operator == "+": return first_operand + second_operand elif operator == "-": return first_oper...
def ret_normalized_vec(vec, length): """Normalize a vector in L2 (Euclidean unit norm). Parameters ---------- vec : list of (int, number) Input vector in BoW format. length : float Length of vector Returns ------- list of (int, number) L2-normalized...
def _ras_contains_ ( self , aname ) : """Check the presence of variable in set """ _v = self.find ( aname ) if not _v : return False return True
def parse_to_int(value): """ Used to remove invalid data from the string :param value: A String value, perhaps with quotes :return: An integer representing the alue """ return int(value.strip().strip("\""))
def fahrenheit(celsius): """Converts celsius to fahrenheit""" return (celsius * (9/5)) + 32
def coron_detector(mask, module, channel=None): """ Return detector name for a given coronagraphic mask, module, and channel. """ # Grab default channel if channel is None: if ('210R' in mask) or ('SW' in mask): channel = 'SW' else: channel = 'LW' ...
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: return (None, None) min = ints[0] max = ints[0] for num in ints: if num < min: ...
def __query_territories(territories): """ Formats the query based on number of territories selected """ if len(territories) > 1: return f'WHERE combined_key IN {tuple(territories)}' return f"WHERE combined_key = '{territories[0]}'"
def t_tdma(arr): """ tdma - throughput (utilization) """ if arr>1: return 1 return arr
def get_wells(job): """ Read the summary file and add the wells to the chemid list """ try: summary = open(job + '/summary_' + job + '.out', 'r').readlines() except: return 0 with open('chemids', 'r') as f: jobs = f.read().split('\n') jobs = [ji for ji in jobs if ji !...
def stripQuotes(s): """Remove surrounding quotes if there are any. The function returns the string without surrounding quotes (i.e. '"foo"' -> 'foo'). If there are no quotes the string is returned unchanged. """ if s[0]=='"': return s[1:-1] return...
def _find_original_entity(ent, base_ents): """Find the original entity referenced by $ref entity.""" try: id = ent["$ref"] return next(bent for bent in base_ents if ("$id" in bent) and bent["$id"] == id) except StopIteration: return ent
def get_resid_from_name(name: str): """Converts name of node in mesh to residue_id.""" entities = name.split("_") chain_id = entities[0] res_pos = int(entities[1]) insertion = entities[2] if insertion == "x": insertion = " " res_id = (" ", res_pos, insertion) return (chain_id,...
def list_get(li: list, idx: int, default): """Safe index retrieval from list.""" try: return li[idx] except IndexError: return default
def get_variants_sorted_by_count(variants): """ From the dictionary of variants returns an ordered list of variants along with their count Parameters ---------- variants Dictionary with variant as the key and the list of traces as the value Returns ---------- var_count ...
def list_i2str(ilist): """ Convert an integer list into a string list. """ slist = [] for el in ilist: slist.append(str(el)) return slist
def create_sim_matching_string(parsed_host: dict): """ Fill the matching string with all text that contains information about the OS. """ def add_if_exists(obj: dict, field: str): """ Add a dict value to the matching string if its key exists in the dict. """ nonlocal ma...
def _handler_match(license, handler): """ Determine if the supplied license matches the handler arguments: license -- the license extracted from the bibjson record handler -- the name of the handler to match (can be None) returns: """ # if handler is none, treat as a ...
def derive_form_imported(config, data): """ This derives the form imported field """ forms = config['forms'] form_names = [form['form_name'] for form in forms] form_importeds = [form['form_imported'] for form in forms] for record in data: for name, imported in zip(form_names, form_im...
def build_speechlet_response(title, output, reprompt_text, should_end_session): """ Build Speechlet Response :param title: :param output: :param reprompt_text: :param should_end_session: :return: """ return { 'outputSpeech': { 'type': 'PlainText', ...
def get_images(num): """get sample images Args: num(int): number of images to return Returns: list: list of sample images """ img_info = "SAMPLE" return [img_info for i in range(num)]
def map_certainty_to_variance(certainty): """ Let's just fit a line with these endpoints: 7 --> 0.001 1 --> 0.07 (the max possible value, when \alpha=\beta=1, is 0.08133333) """ return 0.0815 - (0.0115 * certainty)
def selection_with_period(raw, only_1516=False, only_17=False, only_18=False): """Augment a selection to require a specific data taking period. Parameters ---------- raw : str Raw selection string. only_1516 : bool Require 2015/2016 only_17 : bool Require 2017 only_1...
def trim(x): """Removes (strips) whitespace from both ends of the string""" return x.strip()
def convert_comment_block(html): """ Convert markdown code bloc to Confluence hidden comment :param html: string :return: modified html string """ open_tag = '<ac:placeholder>' close_tag = '</ac:placeholder>' html = html.replace('<!--', open_tag).replace('-->', close_tag) return h...
def save_file(content, file_path: str) -> str: """Save file in a directory Arguments: content {[type]} -- file content file_path {str} -- target path where file will be saved Returns: str -- path to saved file """ with open(file_path, 'wb') as f: f.write(content) ...
def xy2irishgrid(x, y): """ Convert x and y coordinate integers into irish grid reference string """ x = str(x) y = str(y) grid = [("V", "W", "X", "Y", "Z"), ("Q", "R", "S", "T", "U"), ("L", "M", "N", "O", "P"), ("F", "G", "H", "J", "K"), ("A", "B...
def dsmr_transform(value): """Transform DSMR version value to right format.""" if value.isdigit(): return float(value) / 10 return value
def rFixSize(s, n): """ Return a string of size (n) chars, containing the text in (s). If (s) is bigger than (n) chars, cut off the right-hand end. If (s) is smaller than (n), move it to the right of the resultant string. @param s [string] @param n [int] @return [int] """ s = s[:n] p...
def scrub_whitespace(_, text): """ Replaces all whitespace with a single space each. """ return " ".join(text.split()) if text is not None else ""
def dot_product(vec1, vec2): """Dot product of two vectors is a scalar that, when normalized, measures how colinear are the two input vectors. e.g. vec1.vec2/|vec1||vec2| = -1 implies they are aligned exactly opposite to each other, while a value of 1 implies that they are aligned in the same direction....
def hello(name=''): """ return "Hello, World!" - there are no tests with name not empty """ if name: return "Hello, {}!".format(name) return "Hello, World!"
def is_snap(name, filename): """Test is snap file >>> is_snap('mybackup', 'mybackup-snar-0') True >>> is_snap('mybackup', 'mybackup-snar-1') True """ ln = len(name) return filename[:ln] == name\ and filename[ln:ln + len('-snar-')] == '-snar-'
def newman_conway(num, memo=None): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if num == 0: raise ValueError if num == 1: return '1' if memo is None: memo = [0, 1, 1] while num >=...
def studSaveStrComp(ref: str, other: str, strip: bool = True, ignoreCase: bool = True, ignoreNonAlNum=True): """ Student save compare between strings. Converts both to lower, strips them and removes all non alphanumeric chars before comparison. """ # Strip: if strip: ref = ref.strip(...
def variable_set_up_user(num): """Return the user's choice""" if num == 1: return 'You chose rock.' elif num == 2: return 'You chose paper.' elif num == 3: return 'You chose scissors.'
def ceiling(n): """Return the integer rounded towards +infinitum of n.""" from math import ceil return int(ceil(n))
def split_authority(authority): """ Basic authority parser that splits authority into component parts >>> split_authority("user:password@host:port") ('user', 'password', 'host', 'port') """ if '@' in authority: userinfo, hostport = authority.split('@', 1) else: use...
def I_form(n): """ returns Identity matrix of order n """ I=[] item=[] for i in range(n): for j in range(n): if i==j: item.append(1) else: item.append(0) I.append(item) item=[] return I
def _maybe_singleton(it): """unpack single-entry collection to single value""" if len(it) == 1: return it[0] return it
def wrap_words(words, length, sep=',', newline='\n'): """Join words by sep, no more than count in each line.""" lines = [] line = [] cur_length = 0 while True: if not words: lines.append(line) break if cur_length + len(line) > length: lines.append...
def get_package_type(package_link: str) -> str: """ :returns the package type ["pypy_package"|"git_package"|"weblink"] >>> assert get_package_type('pip') == 'pypy_package' >>> assert get_package_type('https://github.com/pypa/pip.git') == 'git_package' >>> assert get_package_type('git+https://github...
def safe_length(var): """ Exception-safe length check, returns -1 if no length on type or error """ output = -1 try: output = len(var) except: pass return output
def reverseString(s): """ :type s: str :rtype: str """ r = list(s) i, j = 0, len(r) - 1 while i < j: r[i], r[j] = r[j], r[i] i += 1 j -= 1 return "".join(r)
def lists_to_html_table(a_list): """ Converts a list of lists to a HTML table. First list becomes the header of the table. Useful while sending email from the code :param list(list) a_list: values in the form of list of lists :return: HTML table representation corresponding to the values in the li...
def DwordToBits(srcDword): """ Converts a dword into an array of 32 bits """ bit_array = [] h_str = "%08x" % srcDword h_size = len(h_str) * 4 bits = (bin(int(h_str,16))[2:]).zfill(h_size)[::-1] for bit in bits: bit_array.append(int(bit)) return bit_array
def parse_flarelabels(label_file): """ Parses a flare-label file and generates a dictionary mapping residue identifiers (e.g. A:ARG:123) to a user-specified label, trees that can be parsed by flareplots, and a color indicator for vertices. Parameters ---------- label_file : file A flare...
def removecommongaps(s1, s2): """Remove common gap characters between the two sequences. Return s1, s2 with these characters removed. """ if len(s1) != len(s2): raise ValueError('Sequences must be same length') return ( ''.join(b1 for b1, b2 in zip(s1, s2) if b1 != '-' or b2 != '-'),...
def coulomb_force(r_in, pot_matrix): """ Calculate the coulomb potential and force between two particles. Parameters ---------- r_in : float Distance between two particles. pot_matrix : numpy.ndarray It contains potential dependent variables. Returns ------- U : fl...
def chunk_sent(text1:str, n_words_per_chunk:int, n_prev:int): """ Chunks sentences into chunks having n_words_per_chunk using a window that considers the last n_prev words of the previous chunk >>> some_text = "w1 w2 w3 w5. w6 w7 w8" >>> chunk_sent(some_text, 3,1) ['w1 w2 w3', 'w3 w5. w6', ...
def _merge_dicts(one, two, resolvefn): """Merges two dicts. The algorithm is to first create a dictionary of all the keys that exist in one and two but not in both. Then iterate over each key that belongs in both while calling the resovlefn function to ensure the propery value gets set. :param one: The...
def h_index(publications): """ :param publications: list of number of views of publications :return: int """ publications = sorted(publications) N = len(publications) if N > 1: maxrange = min([N, max(publications)]) + 1 for h in range(1, maxrange)[::-1]: if public...
def _SubPaths(paths, first_part): """Returns paths of sub-tests that start with some name.""" assert first_part return ['/'.join(p.split('/')[1:]) for p in paths if '/' in p and p.split('/')[0] == first_part]
def _filter_keys(d, pred): """Filter the dict, keeping entries whose keys satisfy a predicate.""" return dict((k, v) for k, v in d.items() if pred(k))
def list_of_lists_to_list(lst_of_lst): """Flatten a list of lists.""" return [x for lst in lst_of_lst for x in lst]
def convert_ms2frames(fps, ms): # taken from https://github.com/atvKumar/Scene_Cut_Detection/blob/93622d250dc38907ee7d3ee8d925c4bfb76129b6/timecode_utils.py' # I am worried that this does not produce 100% accurate values, however # when the returned value is used as the source for convert_timecode(), #...
def format_time(num_seconds): """ Given a number of seconds, return a string with `num_seconds` converted into a more readable format (including minutes and hours if appropriate). """ hours = int(num_seconds / 3600.0) r = num_seconds - 3600 * hours minutes = int(r / 60.0) seconds = ...
def binomial_coef_v2(n, k): """Computes the k-th coefficient of n-th degree binomial. Args: n (int): The degree of binomial. k (int): The order of binomial coefficient. Returns: (int): The k-th coefficient of n-th degree binomial. """ tbl = [[0] * (k + 1) for _ in range(n +...
def in_list(needles, haystack): """ return True if any of the strings in string array needles is in haystack """ for needle in needles: if needle in haystack: return True return False
def _equal_phases(downloaded_phase, calculated_phase): """ Compare calculated and downloaded phases. If the downloaded_phase is -1, this function returns True, otherwise, the phases are compared and True is returned if they are equal. >>> _equal_phases(0, 0) True >>> _equal_phases(-1, 1) ...
def string2simple(s): """ If s is not a string, it is returned asis. Otherwise, it's eval'd in an attempt to create a simple object (bytes, bool, float, int, None, str). The eval will raise an EXCEPTION if the source does not represent a simple object or is an unquoted object reference. **...
def get_missing_letters (dictionary, alphabet): """ `get_missing_letters()` gets every word from the dictionary that uses at least one letter that is not in the alphabet. * **dictionary** (*list*) : the input dictionary (while processing) * **alphabet** (*list*) : the used alphabet (from input fil...
def calc_tpr(tp: float, fn: float) -> float: """ :param tp: true positive or hit :param fn: false negative miss :return: sensitivity or true positive rate """ try: calc = tp / (tp + fn) except ZeroDivisionError: calc = 0 return calc
def safe_identifier_length(identifier_name, max_length=64): """https://dev.mysql.com/doc/refman/8.0/en/identifier-length.html.""" return identifier_name[:max_length]
def is_valid_algorithm(algorithm: str) -> bool: """check if the input algorithm is valid :param algorithm: algorithm name :type algorithm: str :return: True if the algorithm is valid :rtype: bool """ available_algorithms = [ 'Histogram Equalization', 'Contrast Stretching', ...
def _find_equivalent(searched_dict, dicts_list): """ Finds the item in the given list which has the same ID than the given dictionary. A dictionary is equivalent to another if they have the same value for one of the following keys: 'id', 'uid', 'name'. :param searched_dict: The diction...
def create_metadata(config, md5s): """Compute metadata for a manifest file Parameters ---------- config : dict Dictionary of metadata attributes that include experiment_accession, description, and library_accession. md5s : list((filename, md5 hexdigest)) List of filename and...
def pickname(*args): """ Picks the first string non null in the list. @param l list of string @return string """ for s in args: s = s.strip() if s: return s raise ValueError( # pragma: no cover "Unable to find a non empty string in {0}".fo...
def get_resource_types(resources): """ jinja2 helper fuction to get the list of unique resource types """ return set( resource["resource_type"] for resource in resources )
def p2f(x): """http://stackoverflow.com/questions/25669588/convert-percent-string-to-float-in-pandas-read-csv""" if isinstance(x, float): return x x = x.encode('ascii', 'ignore') x = x.split('-')[0] x = x.strip('N') return float(x.strip('%'))/100
def detect_anomaly( ratio: float, pre_eggs_list: list, post_eggs_list: list ) -> dict: """ If the ratio of pre-eggs to post-eggs is less than 0.5 or greater than 2.0, then the decision is to keep the pre-eggs. If the ratio is between 0.5 and 2.0, then the decision is to keep neither. If the ratio is...
def convert_size(size=1.0, from_unit='pt', to_unit='in'): """ Convert the size/length of an object into another unit. Parameters ---------- size : float Size/length of an object. If you would like to set the size of a figure to fit in a text column of a LaTeX document, determine the...
def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ length = 1 while n != 1: print(n) if n % 2 == 0: n = n // 2 # Integer division prevents "...
def about_me(your_name): """ Return the most important thing about a person. Parameters ---------- your_name A string indicating the name of the person. """ return "The wise {} loves Python.".format(your_name)
def sort_cim_files(file_names): """ Sorts the CIM files in the preferred reading order :param file_names: lis of file names :return: sorted list of file names """ # sort the files lst = list() nn = len(file_names) for i in range(nn - 1, -1, -1): f = file_names[i] if '...
def sum(a, b): """In order to complete the round you need to implement the following method: sum(Integer, Integer) -> Integer Where: - param[0] = a positive integer between 0-100 - param[1] = a positive integer between 0-100 - @return = an Integer representing the sum of the two numbers...
def events_filter_pretty(events, handler=None, indent=" "): """ Augment an XML event list for pretty printing. This is a filter function taking an event stream and returning the augmented event stream including ignorable whitespaces for an indented pretty print. the generated events stream is stil...
def serialize_string(input_string): """apply a serial counter to a string""" s = input_string.strip().split() last_token = s[-1] all_other_tokens_as_string = input_string.replace(last_token, '') if last_token.isdigit(): value = '%s%s' % (all_other_tokens_as_string, int(last_token) + 1) ...
def _param_to_dict(params): """Returns the values of params as a dictionary. If params is empty, an empty dictionary is returned """ paramsdict = {} if params: params = params.split(',') for param in params: key, value = param.split('=') paramsdict[key.strip()...
def get_slot_value(intent, slot_name, default=None, avoid=[""]): """Function to safely return a slot value from the dictionary. Only returns non-default value if intent contains a value for the slot, and that value is not an empty string. """ if slot_name in intent['slots'] and "value" in intent['s...
def swap(board, i, j): """ Simula lo de mover las piezas del tablero """ boardL = list(board) boardL[i], boardL[j] = boardL[j], boardL[i] return tuple(boardL)
def one_to_three(one): """ Take a score -1, 0, or 1, and return the three vector of labels """ return ((1, 0, 0), (0, 1, 0), (0, 0, 1))[one + 1]