content
stringlengths
42
6.51k
def get_maximum_with_tolerance(value, tolerance): """Helper function that takes a value and applies the tolerance above the value Args: value: a float representing the mean value to which the tolerance will be applied tolerance: a float representing a percentage (between 0.0 ...
def flatten_d(d): """ collects and flattens nested dicts ( unnesting ) :param d: nested dict :return: unnested dict """ mergeddict = dict() for k, v in d.items(): if type(v) is dict: mergeddict.update(v) dd = {**d, **mergeddict} return dd
def fusion_processes_to_events(process_list): """ Define fusion processes between compartments. Parameters ========== process_list : :obj:`list` of :obj:`tuple` A list of tuples that contains fission rates in the following format: .. code:: python [ (c...
def _add_missing_keys(dictionary): """If the user leaves these keys blank, add them with these default values. Parameters ---------- dictionary : Dictionary of user input argument settings. Returns ------- dictionary Python dictionray of user input settings. """ dictionary[...
def cast_var(item, klass, arg=None): """Attempt to cast `item` to an instance of `klass`. Args: item: The object to cast. klass: The class to cast to. arg: The kwarg name to use for the `klass` ``__init__()`` parameter. If ``None``, a positional argument will be used. "...
def common_relpath(path_a, path_b): """ Returns common end-path for two identical filepaths with different root-directories. Args: path_a (str): ``(ex: '/path/src/neat/file.txt')`` path_b (str): ``(ex: '/another/path/dst/neat/file.txt')`` Returns: str: ``'neat/file.txt'`` "...
def format_time(seconds: int) -> str: """ Return *seconds* in a human-readable format (e.g. 25h 15m 45s). Unlike `timedelta`, we don't aggregate it into days: it's not useful when reporting logged work hours. """ out = [] if seconds > 3599: out.append("%sh" % (seconds // 3600)) ...
def parse_device_type(device_type): """ **Parse the the deviceType string** Parses only the deviceType portion of the device type string :param device_type: Full device type string :return: Parsed device type :rtype: str """ return device_type.split(':')[3:][0]
def intervalCoverage(interval): """ Calculates the base pairs covered by an interval. :param interval: :return: """ coverage = 0 for i in interval: coverage = coverage + (i[1] - i[0]) return coverage
def flatten(dictio, output=None, parent=()): """ Function to flatten a nested dictionnary. :param dictio: nested dictionnary to flatten :type dictio: dict :param output: list containing the flatten dictionnary. In the first call, the output should not be set as the flatten dictionnary is given ...
def get_value(item: str, json_package: dict) -> dict: """Return dict item.""" return_dict = {} if item in json_package: return_dict[item] = json_package[item] return return_dict
def decode_ids(ids, vocab): """Decode the ids to the corresponding characters. """ out = [] for _id in ids: out.append(vocab[_id]) return out
def change(current, previous): """Calculate the percent change between `current` and `previous`. """ if current == previous: return 0 try: v = ((current - previous) / previous) * 100.0 if v > 0: return "+{:.2f}".format(v) return "{:.2f}".format(v) except Z...
def unlines(strings): """ lines :: [String] -> String unlines is an inverse operation to lines. It joins lines, after appending a terminating newline to each. """ return "\n".join(strings)
def get_exmsg(exobj): # pragma: no cover """ Return exception message (Python interpreter version independent). :param exobj: Exception object :type exobj: exception object :rtype: string """ msg = str(exobj) if (msg[0] == "<") and (msg[-1] == ">") and (exobj._excinfo): exobj...
def fibonacci_top_down_1(n): """ Args: n: Returns: """ if n <= 2: return 1 # Setting the cache variable that is 'attached' to this function if not hasattr(fibonacci_top_down_1, "cache"): fibonacci_top_down_1.cache = {}
def is_gcs(path): """ Check if path is to a google cloud storage directory or a local one. Determined from the presence of 'gs' at the beginning of the path. Arguments: path (str): path to assess Returns: bool: True if path is on gcs and False if local """ if path[:2] == "...
def h_dateclean(in_date): """4/1'2008 or 12/31'2009 format in 2009-12-31 returned""" sp1 = str(in_date).split("'") # [0] = 4/1, [1] = 2008 sp2 = sp1[0].split("/") # [0] = 4(month), [1] = 1(day) return sp1[1] + '-' + sp2[0].zfill(2) + '-' + sp2[1].zfill(2)
def levenshtein_distance(string_a: str, string_b: str) -> int: """Return the Levenshtein distance between two strings.""" if not string_a or not string_b: return 0 head_a, tail_a = string_a[0], string_a[1:] head_b, tail_b = string_b[0], string_b[1:] if head_a == head_b: return leve...
def cleaniddfield(acomm): """make all the keys lower case""" for key in list(acomm.keys()): val = acomm[key] acomm[key.lower()] = val for key in list(acomm.keys()): val = acomm[key] if key != key.lower(): acomm.pop(key) return acomm
def findpivot(A, i, j): """Not-so-good pivot selection: always choose the middle element.""" return (i + j) // 2
def strip_newsgroup_header(text): """ Given text in "news" format, strip the headers, by removing everything before the first blank line. Parameters ---------- text : str The text from which to remove the signature block. """ _before, _blankline, after = text.partition("\n\n") ...
def is_in(var, obj): """ If the contents of "var" is equivalent to the value in obj.name. :param var: The value to look for. :type var: str :param obj: The object to iterate over. :type obj: dict/class :returns: True, False """ r = False for o in obj: if var == o.name: ...
def pf_from_a(a): """Pulsed fraction from fractional amplitude of modulation. If the pulsed profile is defined as p = mean * (1 + a * sin(phase)), we define "pulsed fraction" as 2a/b, where b = mean + a is the maximum and a is the amplitude of the modulation. Hence, pulsed fraction = 2a/(1+a)...
def rm_snp_annot(var): """ Returns the SNP variant string, nicely formatted with annotation stripped. This includes ()'s, !, and lowercase bases. Args: var: A variant string representing a SNP Returns: The variant string with annotation removed. """ if var.startswith('('): ...
def determine_rescaled_bounds(prior_min, prior_max, x_min, x_max, invert): """ Determine the values of the prior min and max in the rescaled space. Parameters ---------- prior_min : float Mininum of the prior prior_max : float Maximum of the prior x_min : float Ne...
def mask_lattice(names): """ names: [self, self.training, self.model, optimizer] """ def is_prefixed_by(name, prefix): if len(prefix) >= len(name): return False name = name[0:len(prefix)] for l,r in zip(name, prefix): if l != r: return Fals...
def simpcluded(spx, simplices): """Is a simplex in a list of simplices?""" isIncluded = False for s in simplices: if s == spx: isIncluded = True break return isIncluded
def on_image(imagine, row, column): """ Functia verifica daca punctul, descris de coordonatele sale - row si column, este pe imagine. Returneaza True daca se afla pe imagine, False - in caz contrar. """ return not ((row < 0) or (row > len(imagine) - 1) or (column < 0) or (colum...
def __transform_name(name: dict) -> dict: """ Transform a name from Cognito format to our format. """ result = {} f_name = name.get('First') m_name = name.get('Middle') l_name = name.get('Last') title = name.get('Prefix') suffix = name.get('Suffix') if title: result['tit...
def _GenerateJsDoc(args, return_val=False): """Generate JSDoc for a function. Args: args: A list of names of the argument. return_val: Whether the function has a return value. Returns: The JSDoc as a string. """ lines = [] lines.append('/**') lines += [' * @param {} %s' % arg for arg in ar...
def word_frequency(words): """Returns frequency of each word given a list of words. >>> word_frequency(['a', 'b', 'a']) {'a': 2, 'b': 1} """ frequency = {} for w in words: frequency[w] = frequency.get(w, 0) + 1 return frequency
def human_format(number): """Convert number to kilo / mega / giga format.""" if number < 1024: return "%d" % number kilo = float(number) / 1024.0 if kilo < 1024: return "%.2fk" % kilo meg = kilo / 1024.0 if meg < 1024: return "%.2fM" % meg gig = meg / 1024.0 retur...
def binary_search_iterative(array, item): """Return index of item in sorted array or None if item is not found.""" # set large and small pointers (each end of arr) small = 0 large = len(array) - 1 # while pointers are not the same while small != large: # set middle index mid = (s...
def getIslandCount(grid,i,j): """ This function sink the current island Args: grid: a 2d grid map of '1's (land) and '0's (water) i: x-axis coordinate j: y-axis coordinate Returns: 1 if there is an island """ # check coordinates in bound if (i<0) or (i>=len(grid)) or (j<0) or...
def relerr(expected, actual): """Relative error between `expected` and `actual`: ``abs((a - e)/e)``.""" return abs((actual - expected)/expected)
def is_unique(l): """Check if all the elements in list l are unique.""" assert type(l) is list, "Type %s is not list!" % type(l) return len(l) == len(set(l))
def merge_wv_t1_eng(where_str_tokens, NLq): """ Almost copied of SQLNet. The main purpose is pad blank line while combining tokens. """ nlq = NLq.lower() where_str_tokens = [tok.lower() for tok in where_str_tokens] alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789$' special = {'-LRB-': '(...
def unique(a): """ remove duplicates from a list. @param a::[] = an array of something (contents must be hashable) @return::[] = same as (a) but with duplicates removed """ inserted = set() r = [] for e in a: if e not in inserted: r.append(e) inserted.add(e) ...
def jdnDate(jdn): """ Converts Julian Day Number to Gregorian date. """ a = jdn + 32044 b = (4*a + 3) // 146097 c = a - (146097*b) // 4 d = (4*c + 3) // 1461 e = c - (1461*d) // 4 m = (5*e + 2) // 153 day = e + 1 - (153*m + 2) // 5 month = m + 3 - 12*(m//10) year = 100*b + d - 48...
def convert_to_int(val): """ Converts string to int if possible, otherwise returns initial string """ try: return int(val) except ValueError: pass try: return float(val) except ValueError: return val
def multiply_even_numbers(nums): """Multiply the even numbers. >>> multiply_even_numbers([2, 3, 4, 5, 6]) 48 >>> multiply_even_numbers([3, 4, 5]) 4 If there are no even numbers, return 1. >>> multiply_even_numbers([1, 3, 5]) 1 """ ...
def decodeLowerRow(lowerValue, debug=False): """ Decodes the dropper lower row value and returns 2 lists: included and excluded. If returned an empty list, the input value is invalid. """ if not isinstance(lowerValue, int): if debug: print("ERROR: the function must be called with an int...
def is_basestring(value): """ Checks if value is string in both Python2.7 and Python3+ """ return isinstance(value, (type(u''), str))
def to_str(s, encoding="utf8"): """Convert data to native str type (bytestring on Py2 and unicode on Py3).""" if type(s) is bytes: s = str(s, encoding) elif type(s) is not str: s = str(s) return s
def sorted_container_nodes(containers): """Returns a sorted iterable of containers sorted by label or id (whatever is available) Arguments: containers (iterable): The the list of containers to sort Returns: iterable: The sorted set of containers """ return sorted(containers, key=la...
def remove_closed_range_from_list(the_list, from_index, to_index): """ Removes closed range from 'the_list', elements with indexes 'from_index' and 'to_index' are also removed.""" doc_len = len(the_list) if from_index < 0: from_index = 0 if to_index < from_index: to_index = from_inde...
def _ForwardingRuleTarget(forwarding_rule): """Gets the API-level target or backend-service of the given rule.""" backend_service = forwarding_rule.get('backendService', None) if backend_service is not None: return backend_service else: return forwarding_rule.get('target', None)
def px(x, y): """Convert a raw value (x/y) to a pixel value, clamping negative values""" return 0 if x <= 0 else round(x / y)
def len_in_bits(n): """ Return number of bits in binary representation of @n. """ try: return n.bit_length() # new in Python 2.7 except AttributeError: if n == 0: return 0 return len(bin(n)) - 2
def find_in_listdict(listdict, search_key, val, return_key): """ For a given listdict (list of dictionary), if dict[search_key] is equal to val, return dict[return_key]. Return None if no match is found. """ search_key_exists = False for _ in listdict: if search_key in _: s...
def midpoint(start, end): """Find the mid-point between two points.""" x0, y0 = start x1, y1 = end return (x0+x1)/2, (y0+y1)/2
def filter_content(content): """Filters and seperates jinja text from yaml content Args: content (str): Text representing yaml content Returns: list: Containing jinja_text and yaml_text """ jinja_text = content[:2] yaml_text = content[2:] return jinja_text, yaml_text
def compare(a, b): """ Compare items in 2 arrays. Returns sum(abs(a(i)-b(i))) """ s=0 for i in range(len(a)): s=s+abs(a[i]-b[i]) return s
def FlattenList(inputList): """ Method to take a list of lists and produce one overall list :return: """ opList = list() for ii in range(len(inputList)): opList = opList + inputList[ii] return opList
def num_boxes_greater_than_ratio(boxes, debug=False, ratio=0.8): """ check if the number of boxes passed in are greater than the specified threshold :param boxes: the bounding boxes :type boxes: list :param debug: Whether or not to print debug messages :type debug: Bool :param ratio: the rat...
def make_list_response(reponse_list, cursor=None, more=False, total_count=None): """Creates reponse with list of items and also meta data useful for pagination Args: reponse_list (list): list of items to be in response cursor (Cursor, optional): ndb query cursor more (bool, optional): w...
def check_odd_even(n): """Return True if even.""" if n % 2: # Odd return True else: # Even return False
def component_masses_to_chirp_mass(mass_1, mass_2): """ Convert the component masses of a binary to its chirp mass. Parameters ---------- mass_1: float Mass of the heavier object mass_2: float Mass of the lighter object Return ------ chirp_mass: float Chirp ...
def escape(text: str, input_type='pyku'): """ Escape all the color tokens in the given text chunk, so they can be safely printed through the color parser """ if text is None or text == '': return text if input_type == 'i3': text = text.replace('%^', '%%^^') elif input_type ==...
def stack_projection_args(cli_args): """ Converts the flat processing options into nested JSON Args: cli_args (dict): arguments parsed from the CLI Returns: dict: nested dictionary grouped by types/usage Example: >>> stack_projection_args({'target_projection': 'utm', 'zone': 1...
def find_unit_clause_int_repr(clauses, model): """ Same as find_unit_clause, but arguments are expected to be in integer representation. >>> from sympy.logic.algorithms.dpll import find_unit_clause_int_repr >>> find_unit_clause_int_repr([set([1, 2, 3]), ... set([2, -3]), set([1, -2])], {1: ...
def decodeUTF8( string ): """Decode bytes of data if it is 'utf-8'""" try: decoded = string.decode('utf-8') return decoded except UnicodeError: return None
def create_error_response(code, jrpc_id, msg): """ Creates JSON RPC error response. Parameters : code: Error code jrpc_id: JSON RPC id msg: Error message Returns : JSON RPC error response as JSON object. """ error_response = {} error_response["jsonrpc"] = "2....
def convert_list2dict(keys, values): """ Convert general key-values list to specific Baxter's dictionary for joints. """ j_command = { keys[0]: values[0], keys[1]: values[1], keys[2]: values[2], keys[3]: values[3], keys[4]: values[4], keys[5]: values[5], ...
def concat_list(str_list): """Return concat string of string list""" return_string = '' start = True for str_value in str_list: if not start: return_string + " " else: start = False return_string += str_value return return_string
def pop_recursive(d, key, default=None): """dict.pop(key) where `key` is a `.`-delimited list of nested keys. >>> d = {'a': {'b': 1, 'c': 2}} >>> pop_recursive(d, 'a.c') 2 >>> d {'a': {'b': 1}} """ nested = key.split(".") current = d for k in nested[:-1]: if hasattr(curre...
def __curse_list_flatten(self): """ Flatten a list. Only the type `list` is affected. >>> [1, [2], [[3]], (4, 5)].flatten() [1, 2, 3, (4, 5)] """ def __flatten(x): return __flatten(x[0]) + (__flatten(x[1:]) if len(x) > 1 else []) if type(x) is list else [x] return __flatten(self)
def set_values_by_hash_count(values, key, hash, count=1): """Find any hash counts with a score of 1 and set their value in the cell key.""" for hashKey in hash.keys(): if hash[hashKey]['count'] == count: setKey = hash[hashKey]['key'] values[key] = hashKey return values
def merge_two_dicts(x, y): """Merge two dictionary.""" z = x.copy() z.update(y) return z
def parse_json(json_dict): """ @param json_dict: should have keys: minus_1, minus_2, output @return: strings of minus_1, minus_2, output """ try: return str(json_dict['minus_1']), str(json_dict['minus_2']), str(json_dict['output']) except Exception: raise KeyError('Error while pa...
def lines(a, b): """Return lines in both a and b""" same_lines = [] # creating a list with all the lines in file1 linesA = a.split("\n") linesA = [i.rstrip("\r") for i in linesA] # creating a list with all the lines in file2 linesB = b.split("\n") linesB = [i.rstrip("\r") for i in lin...
def bounds(measurement, uncertainty): """Return resolved bounds based on measurement and uncertainty.""" if uncertainty: return measurement - uncertainty, measurement + uncertainty else: return measurement, measurement
def get_key_from_dimensions(derived): """ Translate dimensionality into key for DERIVED_UNI and DERIVED_ENT dicts. """ return tuple((i["base"], i["power"]) for i in derived)
def get_provenance_record(caption: str, ancestors: list): """Create a provenance record describing the diagnostic data and plots.""" record = { 'caption': caption, 'domains': ['global'], 'authors': [ 'smeets_stef', 'aerts_jerom', ], 'projects': [ ...
def get_elife_doi(article_id): """ Given an article_id, return a DOI for the eLife journal """ doi = "10.7554/eLife." + str(int(article_id)).zfill(5) return doi
def get_ranges(pool): """ convert ASN pool list to dict format :param pool: list :return: dict """ return [{"first": r[0], "last": r[1]} for r in pool]
def get_index(point, list_vertices, shift=0): """Index the vertices. The third option is for incorporating a local index (building-level) to the global one (dataset-level).""" global vertices """Unique identifier and indexer of vertices.""" if point in list_vertices: return list_vertices.index(point) + 1 + shift...
def combine_scorevectors(vec_1, vec_2): """Combining two entity-scores, e.g. (e_1, s_1, a_1) and (e_2, s_2, a_2)""" total_agreements = vec_1[2] + vec_2[2] normed_sentiment = (vec_1[1] * vec_1[2] + vec_2[1] * vec_2[2]) / total_agreements return (vec_1[0], normed_sentiment, total_agreements)
def is_right(side1, side2, side3): """ Takes three side lengths and returns true if triangle is right :param side1: int or float :param side2: int or float :param side3: int or float :return: bool """ return False # TESTS #Feel free to add your own tests as needed!
def id_cleaner(docker_id: str, prefix: str = 'sha256:') -> str: """Get 1st 10 characters in id created by docker :param docker_id: id of docker object :param prefix: defaults to 'sha256:' :return: shorter id """ return docker_id[docker_id.startswith(prefix) and len(prefix) :][:10]
def find_repeat(start_pattern, function, n_iter=None): """ Returns when a NONSPECFIED repeating pattern has been found Returns steps, pattern """ if not n_iter: n_iter = round(10e20) seen = {start_pattern} current = start_pattern for i in range(1,n_iter): current = functi...
def str_to_bool(s): """ Convert a string to a boolean. Args: s (str): String to convert. """ if s.lower() == 'true': return True else: return False
def listofobjs(values, obj): """ Create a list of objects """ temp = [] for key in values: temp.append(obj(key)) return temp
def valid(m: list, i: int, j: int, cell: int) -> bool: """Determine if a value is valid for a cell. Args: m (list): The board i (int): Column number j (int): Row number cell: Value to verify Returns: bool: True if valid, else False """ for it in range(9): ...
def to_capitalized_camel_case(snake_case_string): """ Convert a string from snake case to camel case with the first letter capitalized. :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string. """ parts = snake_case_string.split(...
def x_www_form_urlencoded(post_data): """ convert origin dict to x-www-form-urlencoded Args: post_data (dict): {"a": 1, "b":2} Returns: str: a=1&b=2 """ if isinstance(post_data, dict): return "&".join( ["{}={}".format(key, value) for key...
def parse_output_table(txt): """ Returns list of dictionary values that maps tsv output with a header row """ lines = txt.splitlines() header = lines[0].lower() tokens = [h.replace(" ", "_") for h in header.split()] parse_list = [] for token in tokens: i_token = header.index(to...
def verbose_name_plural(obj): """Trata de encontrar el verbose_name_plural atributo del obj.""" try: return obj.model._meta.verbose_name_plural except (AttributeError): try: return obj.__class__._meta.verbose_name_plural except (AttributeError): try: ...
def make_arguments(**params): """ Create a script argument string from dictionary """ param_strings = ["--{} '{}'".format(key, params[key]) for key in params.keys()] return ' '.join(param_strings)
def map_e(func, oplist): """Eager version of map, returns list. May be slower or more resource hungry than builtin genrator/lazy version.""" return list(map(func, oplist))
def filter_volatile_dates(response, json_response): """Patches volatile dates, and push them into the future, otherwise the app will think the token/whatever is expired. """ if "expiry_time" in json_response: json_response["expiry_time"] = "2050-09-03T00:00:00+00:00" return response, json_re...
def encode_for_env_var(value) -> str: """Environment names and values need to be string.""" if isinstance(value, str): return value elif isinstance(value, bytes): return value.decode() return str(value)
def dirname(p): """Returns the dirname of a path. The dirname is the portion of `p` up to but not including the file portion (i.e., the basename). Any slashes immediately preceding the basename are not included, unless omitting them would make the dirname empty. Args: p: The path whose dirname...
def getUnigram(words): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram """ assert type(words) == list return words
def say_hello(name=None): """Return a greeting to the caller Returns "Hello ..." or "Hello, World!" if a name is not supplied Keyword Arguments: name {str} -- The callers name (default: {None}) Returns: str -- A simple greeting """ if name is None: return "He...
def active_marker(session, Type='String', RepCap='', AttrID=1150058, buffsize=2048, action=['Get', '']): """[Active Marker <string>] Establishes the active marker output connector. Once the output marker is selected, it may be configured by setting one of the four marker attributes which determine the mark...
def average_precision(ranked_list, ground_truth): """Compute the average precision (AP) of a list of ranked items """ hits = 0 sum_precs = 0 for index in range(len(ranked_list)): if ranked_list[index] in ground_truth: hits += 1 sum_precs += hits / (index + 1.0) if...
def _get_oss_path_prefix(prefix, epoch, test_set): """ Get full path with epoch and subset Args: prefix (str): path prefix. epoch (int): epoch number of these proposals test_set (str): training or validation set """ return prefix + "_ep{}_{}".format(epoch, test_set)
def get_transformers(train_dataset): """Get transformers applied to datasets.""" transformers = [] # transformers = [ # deepchem.trans.LogTransformer(transform_X=True), # deepchem.trans.NormalizationTransformer(transform_y=True, # dataset=train_dataset)] return t...