content
stringlengths
42
6.51k
def f1(tp, tn, fp, fn): """ Calculates the F1 Score. """ precision = tp / (1.0 * (tp + fp)) recall = tp / (1.0 * (tp + fn)) return 2.0 * precision * recall / (precision + recall)
def flatten(xxs): """ Take a list of lists and return list of values. .. testsetup:: from proso.list import flatten .. doctest:: >>> flatten([[1, 2], [3, 4]]) [1, 2, 3, 4] """ return [x for xs in xxs for x in xs]
def prefix_suffix_prep(string1, string2): """Calculates starting position and lengths of two strings such that common prefix and suffix substrings are excluded. Expects len(string1) <= len(string2) **Args**: * string_1 (str): Base string. * string_2 (str): The string to compare. **Returns...
def squared_euclidean_distance(p, q): """ N-dimensional squared Euclidean distance. Like Euclidean distance, but squared! Forgoing the square root is a minor optimization but it shaves off a few cycles when only distances need be to compared. Unlike euclidean_distance, the return value is not guaran...
def FF_array_predict_HLS(dw, depth): """Predict the FF resource usage of arrays on Xilinx platform. Parameters ---------- dw: int BRAM port width (in bytes) depth : int BRAM depth """ return dw * 8 * depth
def _joinVerbListIntoText(verbList): """ Combines the verbs in verbList into a single string and returns it. """ return " ".join(verbList)
def getTkColorString(color): """ Print out a Tk compatible version of a color string """ def toHex(intVal): val = int(intVal) if val < 16: return "0" + hex(val)[2:] else: return hex(val)[2:] r = toHex(color[0]) g = toHex(color[1]) b = toHex(col...
def int_checker(string): """ This is a private function used to check to see if the string passed is an int :return: """ for x in range(len(string)): try: int(string[x]) except: return False return True
def format_replication_header(headers): # pragma: no cover """Format replication headers. :param headers: Request headers. :type headers: dict :return: Formatted body. :rtype: dict """ headers = {k.lower(): v for k, v in headers.items()} result = {} if 'x-arango-replication-frompr...
def only_visible(string): """Remove all not visible characters from *string*""" return ''.join(ch for ch in string if 33 <= ord(ch) <= 126)
def bytes2human(num): """ Convert numbers in string readable by humans """ # http://code.activestate.com/recipes/578019 # >>> bytes2human(10000) # '9.8K' # >>> bytes2human(100001221) # '95.4M' symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, symb in enumerate...
def calcVolume(l,w, h): """ >>> calcVolume(2,2,2) 8 >>> calcVolume(2, 2, -1) Traceback (most recent call last): ... ValueError """ args = [l,w,h] for arg in args: int(arg) if arg <=0: raise ValueError return l * w * h
def ParseLine(line, new_target): """Parse one line of a GCC-generated deps file. Each line contains an optional target and then a list of space seperated dependencies. Spaces within filenames are escaped with a backslash. """ filenames = [] if new_target and ':' in line: line = line.split(':', 1)[1...
def add_object_ids(scenes): """Adds object ids field for input scenes. Args: scenes: List of CLEVR scene graphs Returns: scenes: Adds object_id field for the objects in the scene graph inplace """ for scene_id, scene in enumerate(scenes['scenes']): for obj_id, _ in enumerate(scene['objects']): ...
def blend_union(da, db, r): """ Returns a smooth union of the two elements da, db with blend radius blend_radius. """ e = max(r - abs(da - db), 0) return min(da, db) - e * e * 0.25 / r
def filter_on_diagnosis(section): """Filter, sort, prioritize function""" filtered_section = [ d for d in section if d["score"] == 1] return filtered_section
def xyz_handedness(xy_axes: str, z_inc_down: bool): """Return xyz true handedness as 'left', 'right' or 'unknown'.""" if xy_axes is None or z_inc_down is None: return 'unknown' xy_axes_split = xy_axes.lower().split() if len(xy_axes_split) != 2: return 'unknown' if xy_axes_split not ...
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: List of dictionaries. Structured data with the following schema: [ { "state": string, ...
def out_of_range(n: int) -> bool: """ Return True if `n` could not be represented as either a 16-bit signed or unsigned integer. """ return n < -32768 or n >= 65536
def bool_str(b: bool) -> str: """Converts boolean to string ('0' or '1')""" return '1' if b else '0'
def key_value_arg_type(arg): """Simple validate/transform function to use in argparse as a 'type' for an argument where the argument is of the form 'key=value'.""" k, v = arg.split("=", 1) return (k, v)
def rgb_wheel(pos): """b->g->r color wheel from 0 to 1020, to (r, g, b)""" if pos < 255: return (0, pos, 255) elif pos < 510: pos -= 255 return (0, 255, 255 - pos) elif pos < 765: pos -= 510 return (pos, 255, 0) elif pos <= 1020: pos -= 765 ret...
def listing(word): """ :param word: str, the word which user wants to find anagrams :return: list, list of every characters in s """ word_list = [] for ch in word: word_list.append(ch) return word_list
def validate_ip(ip_address): """An IP address consists of 32 bits, shown as 4 terms of numbers from 0-255 represented in decimal form """ terms = ip_address.split(".") if len(terms) != 4: return False for octet in range(0,4): if not terms[octet].isdecimal(): return False elif (in...
def finite_fault_factor(magnitude, model="BT15"): """ Finite fault factor for converting Rrup to an equivalent point source distance. Args: magnitude (float): Earthquake moment magnitude. model (str): Which model to use; currently only suppport "BT15". Retur...
def nearest(items, pivot): """Find nearest element. Examples -------- >>> nearest(np.array([2,4,5,7,9,10]), 4.6) 5 """ return min(items, key=lambda x: abs(x - pivot))
def get_windows_shell_eval(env): """ Return a shell-evalable string to setup some environment variables. """ return "\n".join(('set "{0}={1}"'.format(k, v) for k, v in env.items()))
def gather(word_list: list, start_with: str, end_with: list) -> list: """ Extract proper statements """ Gather: list = [] allowed: bool = False for sentence in word_list: if sentence == start_with: allowed = True if sentence in end_with: ...
def convert_sqr(sqr): """ Converts index (0,63) to 2d indices of (0,7) """ #r = 7 - r #7-r flips rows so array looks like chess board return 7 - (sqr // 8), sqr % 8
def ping(host): """ Returns True if host responds to a ping request """ import subprocess, platform # Ping parameters as function of OS ping_str = "-n 1" if platform.system().lower()=="windows" else "-c 1" args = "ping " + " " + ping_str + " " + host need_sh = False if platform.system...
def clean_data(data): """ Return data after removing unnecessary special character. """ for strippable in ("'", '"', '[', ']',): data = data.replace(strippable, '') return data.strip()
def directions_match(org, dst): """Check function for fluxes direction: they should match. Default is down""" direction_org = org.get('direction', 'down') direction_dst = dst.get('direction', 'down') if direction_org != direction_dst: factor = -1. else: factor = 1. return factor
def FirstFree(seq, base=0): """Returns the first non-existing integer from seq. The seq argument should be a sorted list of positive integers. The first time the index of an element is smaller than the element value, the index will be returned. The base argument is used to start at a different offset, i.e...
def capfirst(text): """Uppercase the first character of text.""" if not text: return text return text[0].upper() + text[1:]
def selection_sort(alist): """ Sorts a list using the selection sort algorithm. alist - The unsorted list. Examples selection_sort([4,7,8,3,2,9,1]) # => [1,2,3,4,7,8,9] a selection sort looks for the smallest value as it makes a pass and, after completing the pass, places it in ...
def rect_contains_point(rect, point): """ Check if rectangle contains a point. """ if (rect[0] <= point[0] and rect[1] <= point[1] and rect[0] + rect[2] >= point[0] and rect[1] + rect[3] >= point[1]): return True return False
def has_len(obj): """ Checks if :param obj: has a __len__ attribute. """ try: obj.__len__ return True except AttributeError: return False
def compareNoteGroupings(noteGroupingA, noteGroupingB): """ Takes in two note groupings, noteGroupingA and noteGroupingB. Returns True if both groupings have identical contents. False otherwise. """ if len(noteGroupingA) == len(noteGroupingB): for (elementA, elementB) in zip(noteGroupingA, n...
def flat_list(l): """ Flattens an input list made by arbitrarily nested lists. :param l: the input list :return: the flattened list """ if not isinstance(l, list): return [l] else: return [e for k in l for e in flat_list(k)]
def calculate_color_temperature(r, g, b): """Converts the raw R/G/B values to color temperature in degrees Kelvin.""" # 1. Map RGB values to their XYZ counterparts. # Based on 6500K fluorescent, 3000K fluorescent # and 60W incandescent values for a wide range. # Note: Y = Illuminance or lux X = ...
def lcs(s1, s2): """Longeset Common Sequence between s1 & s2""" # source: https://stackoverflow.com/questions/48651891/longest-common-subsequence-in-python if len(s1) == 0 or len(s2) == 0: return 0, '' matrix = [["" for x in range(len(s2))] for x in range(len(s1))] for i in range(len(s1)): ...
def rules_cidrs_and_security_groups(rules): """ Return a dict with keys "cidrs" and "sgids" from a list of security group rules. :param rules: list of security group rules :type rules: list :return: Dict with keys "cidrs" and "sgids" :rtype: dict """ cidrs = set( ip_range["...
def addNodeMI(nm_dict, node, value): """ Add motif information to node dictionary. Input: nm_dict: (dictionary) the dictionary of node motif degree node: (int) the id of node value: (int) the change value of node Output: nm_dict: (dictionary) changed ...
def error_message(e, command): """ Detailed explanation of Discord error messages :param command: :param e: :return: """ error = type(e).__name__ if command == "prune": error_lookup = { "Forbidden": "I don't have proper permissions to delete messages", "H...
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args...
def dict_diff(d1, d2, p = 2): """ Compute the difference between dicts """ keys = set.union(set(d1.keys()), set(d2.keys())) diff = 0. for key in keys: diff += abs(d1.get(key, 0.) - d2.get(key, 0.))**p return diff ** (1./p)
def parse_host_port(address, default_port=None): """ Parse an endpoint address given in the form "host:port". """ if isinstance(address, tuple): return address if address.startswith('tcp:'): address = address[4:] def _fail(): raise ValueError("invalid address %r" % (addr...
def cipher(text) -> str: """ Encrypt or Decrypt the text. :param str text: Text to be encrypted or decrypted. :return: Encrypted or Decrypted text. """ result = '' for char in text: result += chr(219 - ord(char)) if char.islower() else char return result
def price_format(price: float, small=False) -> str: """ Returns the number value rounded to two digits, with commas added to disperse large numbers as a string. Larger numbers will be written with letters, such as 10,000 being 10K, etc. """ # Rounds the number price = round(price, 2) if s...
def _generate_bitfill(p): """ pe_A helper function for yield_bits_on to generate the primitive-root lookup table is :param p: prime number which is also a primitive root of 2 Generates a lookup list for powers of two (called here a bitfill). To generate a valid bitfill, p must be prime and 2 must ...
def make_abbr(text, title): """ Make a 'abbr' html element from body text and its definition (title) Parameters ---------- text : str Text to be definied title : str Definition for text Returns ------- str """ return f'<abbr title="{title}">{text}</abbr>'
def loc17(r5): """ Find r3 st. ((r3 + 1) << 8) > r5. if r5 = (R3 << 8 + x), 0 <= x < 256: then (R3 << 8) <= r5, and (R3 + 1) << 8 > r5 ie, r3 = R3 That is, the result is r5 >> 8. """ return (r5 >> 8) """ r3 = 0 while True: # loc18 r1 = (r3 + 1) << 8 if r1...
def test_function(data, increase_by, sleep=False): """Do some massive stuff with one element from iterable.""" if sleep: from time import sleep sleep(2) return data + increase_by
def doi(record): """ :param record: the record. :type record: dict :returns: dict -- the modified record. """ if 'doi' in record: if 'link' not in record: record['link'] = [] nodoi = True for item in record['link']: if 'doi' in item: ...
def insert_declarations(task_inputs, decls): """Replace the reference to a variable declared in the workflow (e.g. gsnap_filter_input) with all the possible inputs.""" for decl, inputs in decls.items(): for task in task_inputs.keys(): if f"WorkflowInput.{decl}" in task_inputs[task]: ...
def get_os_tag(base): """ Constructs an OS tag based on the passed base. The operating system is described with the version name. If the operating system version is numeric, the version will also be appended. """ os_name = base.split(':')[0] os_version = base.split(':')[1] os_tag = os_name if os...
def compile_rules(s : str): """ Compile rules to dictionary of list of rules acsiom -> nt1 nt2 | nt2 nt2 nt2 -> ( nt2 ) | eps nt2 -> eps """ ss = s.split('\n') rules = {} for srules in ss: arrow_index = srules.find('->') left_nonterm = srules[:arrow_index].strip() ...
def support_count(itemset, transactions): """ Count support count for itemset :param itemset: items to measure support count for :param transactions: list of sets (all transactions) >>> simple_transactions = ['ABC', 'BC', 'BD', 'D'] >>> [support_count(item, simple_transactions) for item in 'AB...
def confopt_posint(confstr, default=None): """Check and return a valid positive integer.""" ret = default try: ret = int(confstr) if ret < 0: ret = default except: pass # ignore errors and fall back on default return ret
def make_response(resp): """ Returns Flask tuple `resp, code` code per http://flask.pocoo.org/docs/0.10/quickstart/#about-responses """ if 'errorMsg' in resp: # Error 162 pertains to "Historical data request pacing violation" if resp['errorCode'] in [None, 162]: return resp, 429 ...
def get_year_set(year_int): """ Given an integer year, get Redcap event names up to and including the year. Redcap event names are formatted as in redcap_event_name returned by Redcap API (i.e. "X_visit_arm_1"). Integer-based year: 0 = baseline, 1 = followup_1y, ... Only allows for full-year ...
def pick_icon(icon): """Convert Dark Sky API icon data-point to weather-icons.css format""" icon = "wi-forecast-io-" + icon return icon
def _properties(source, size, require_staging, remote): """Args: source (str): source of the data size (int): number of rows of the dataset require_staging (bool): whether the file requires staging remote (str): remote path Returns: dict: set of importer properties...
def tfilter(predicate, iterable): """ >>> tfilter(lambda x: x % 2, range(10)) (1, 3, 5, 7, 9) """ return tuple(filter(predicate, iterable))
def anno_parser(annos_str): """Annotation parser.""" annos = [] for anno_str in annos_str: anno = list(map(int, anno_str.strip().split(','))) annos.append(anno) return annos
def colored(string, color): """ Returns the given string wrapped with a ANSI escape code that gives it color when printed to a terminal. Args: string: String to be colored. color: Chosen color for the string. Can be 'r' for red, 'g' for green, 'y' for yellow, 'b' for blue, 'p' for ...
def all_equal(iterable): """are all elements of the iterable equal?""" iterator = iter(iterable) first = next(iterator) for item in iterator: if not item == first: return False return True
def deserialize_date(string): """Deserializes string to date. :param string: str. :type string: str :return: date. :rtype: date """ try: from dateutil.parser import parse return parse(string).date() except ImportError: return string
def get_attrs(node, attrs): """ Returns multiple values from a dictionary in order. Parameters ---------- node: dict The dict from which items should be taken. attrs: collections.abc.Iterable The keys which values should be taken. Returns ------- tuple A tup...
def print_table(input_dict, title='', header=('Key', 'Value'), style=('', '-')): """Print the dict in a table form""" assert input_dict.__class__ is dict, "Only accept class='dict'" if input_dict is None: return None max_string = 110 key_list = list(input_dict.keys()) val_list = list(ma...
def linkgen_sdk_dicter(indict, origtext, newtext): """ Prepare SDK radio/OS dictionaries. :param indict: Dictionary of radio and OS pairs. :type: dict(str:str) :param origtext: String in indict's values that must be replaced. :type origtext: str :param newtext: What to replace origtext wi...
def count_occupied(m: list) -> int: """Return how many seats are occupied in parameter map.""" count = 0 for r in m: for c in r: if c == '#': count += 1 return count
def cosine_similarity(frequencies1, frequencies2): """Finds the distances between two frequency profiles, expressed as dictionaries. Assumes every key in frequencies1 is also in frequencies2 >>> cosine_similarity({'a':1, 'b':1, 'c':1}, {'a':1, 'b':1, 'c':1}) # doctest: +ELLIPSIS 1.0000000000... >>>...
def multiply(*args): """Multiplies list of inputed sys arguments""" mul = 1.0 for arg in args: mul *= arg return mul
def cmake_cache_entry(name, value, comment=""): """Generate a string for a cmake cache variable""" return 'set({0} "{1}" CACHE PATH "{2}")\n\n'.format(name, value, comment)
def signid(buffname, lineno): """signid returns the signid generated from the filename and line number :param buffname: name of the buffer (filename) :param lineno: line number specific to buffer """ return 10 * lineno # return hash(buffname) + lineno
def get_full_function_name(func): """ Return the full name of function, including the associated module e.g. module.my_func() -> "module.my_func" """ return f'{func.__module__}.{func.__name__}'
def remaining_elements(data, low, high): """Display remaining elements of the binary search.""" return ' ' * low + ' '.join(str(s) for s in data[low:high + 1])
def mkdata(title, description, icon='', variants=None, **kwargs): """Return a dictionary initialised for a Search.""" variants = variants or [] d = dict(title=title, description=description, variants=variants) if icon: d['icon'] = icon if 'jsonpath' in kwargs: d['jsonpa...
def make_set(str_data, name=None): """ Construct a set containing the specified character strings. Parameters ---------- str_data : None, str, or list of strs Character string(s) to be included in the set. name : str, optional A name to be used in error messages. Returns ...
def xorSingleChar(bytes, char): """ XORs all input bytes with a single key char Input: bytearray text Output: XORed bytearray text """ result = [] for i in range(len(bytes)): result.append(bytes[i] ^ char) return bytearray(result)
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificty). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positive ...
def fill_image_info(instances, images): """Use image dict to fill in image name for instances.""" for user_id in instances: for instance in instances[user_id]: if images is None: instance['image']['name'] = "Image Info Unavailable" else: for image ...
def str_strip_end(name, strip): """ :param name: :param strip: :return: """ if name[len(name)-len(strip):len(name)] == strip: return name[0:len(name)-len(strip)] return name
def remove_leading_indentation(s): """ Custom Jinja filter which removes leading indentation (= exactly four spaces) from a string and returns the result. If the input string does not start with four spaces it is returned unchanged). """ if s.startswith(" "): return s[4:] else: ...
def accuracy(tp,fp,tn,fn): """ Compute binary classifier accuracy. :param tp: True positives (TP) :param fp: False positives (FP) :param tn: True negatives (TN) :param fn: False negatives (FN) :return: Classifier accuracy in [0,1] """ return (tp+tn)/float(tp+fp+tn+fn)
def get_backend_url(config, hub, group, project): """ Util method to get backend url """ if ((config is not None) and ('hub' in config) and (hub is None)): hub = config["hub"] if ((config is not None) and ('group' in config) and (group is None)): group = config["group"] if ((conf...
def z2lin(array): """dB to linear values (for np.array or single number)""" return 10 ** (array / 10.)
def time_format_picker(timeframe): """ format of time for each time frame for changing time from timestamp """ time_dict = { "1d": "%Y-%m-%d", "4h": "%Y-%m-%d %H:%M", "1h": "%Y-%m-%d %H:%M", "30m": "%Y-%m-%d %H:%M", "15m": "%Y-%m-%d %H:%M", "5m": "%Y-%...
def parseAddress(address): """ Resolve the IP address of the device :param address: :return: add_str """ add_list = [] for i in range(4): add_list.append(int(address.hex()[(i * 2): (i + 1) * 2], 16)) add_str = ( str(add_list[0]) + "." + str(add_list[1]) ...
def choose(paragraphs, select, k): """Return the Kth paragraph from PARAGRAPHS for which SELECT called on the paragraph returns true. If there are fewer than K such paragraphs, return the empty string. """ # BEGIN PROBLEM 1 list = [] for i in range(0, len(paragraphs)): s = i ...
def aumentar(preco, fator): """ --> Aumenta em uma dada porcentagem o valor inserido. :param preco: valor a ser aumentado :param fator: fator de aumento, em porcentagem :return: valor aumentado """ final = (preco * (1 + fator/100)) return final
def str_or_none(x): """Type to pass python `None` via argparse Args: x (str) Returns: str or `None` """ return None if x == 'None' else x
def kv_dump(obj: dict) -> str: """Get a string representation of a dictionaries key value pairs. Args: obj: dictionary to get string of """ return "\n " + "\n ".join([f"{k}: {v}" for k, v in obj.items()])
def list_to_string(mylist): """[ A simple function to convert a list of values to a string of values with no separators ] Args: s ([list]): [list of values] Returns: [string]: [joint values from list] """ return ' '.join(str(word) for word in mylist)
def compare_version(lhs, rhs): """Compare two versions. Parameters ---------- lhs : tuple tuple of three integers (major, minor, patch) rhs : tuple tuple of three integers (major, minor, patch) Returns ------- int Returns 0 if lhs and rhs are equal, 1 if lhs is bigger than rhs, otherwise...
def goalexpand(goalt): """ Expand a goal tuple until it can no longer be expanded >>> from logpy.core import var, membero, goalexpand >>> from logpy.util import pprint >>> x = var('x') >>> goal = (membero, x, (1, 2, 3)) >>> print(pprint(goalexpand(goal))) (lany, (eq, ~x, 1), (eq, ~x, 2), (e...
def rotCode(data): """ The rotCode function encodes/decodes data using string indexing :param data: A string :return: The rot-13 encoded/decoded string """ rot_chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', '...
def validate_user_url(value): """Validate that a URL is a valid URL for a hydroshare user.""" err_message = '%s is not a valid url for hydroshare user' % value if value: url_parts = value.split('/') if len(url_parts) != 4: raise ValueError(err_message) if url_parts[1] != ...
def overlapping_bases(coords0, coords1): """ complete coverage of coords0 by coords1, and coords0 can be tol larger. if coords0 is contained by coords1, then return the number of overlapping basepairs """ if coords0[1] > coords1[0] and coords1[1] > coords0[0]: return min(coords1[1], coords0[1]) - max(coords1[0],...