content
stringlengths
42
6.51k
def emoji_usage(emoji_list, output_dict): """ Collect emoji usage """ for emo in emoji_list: if emo not in output_dict: output_dict[emo] = 1 else: output_dict[emo] += 1 return output_dict
def split_paragraphs(text, min_length=30): """Extract a list of paragraphs from text Return a list of strings. Paragraphs are separated by double "new-line" characters. Any paragraph shorter than min_length is dropped. Any whitespaces at the beginning or ending of paragraphs are trimmed. """ ...
def get_spec_assets(balances, assets): """ Select only coins which user wants to calculate for final asset. """ your_balances = {} choosed_assets = [a.upper() for a in assets] for balance in balances: asset = balance["asset"] if asset in choosed_assets: your_balances[...
def parse_ip(ip_str): """ Parse an IP address Parse an IP address '.' separated string of decimal digits to an host ordered integer. '172.24.74.77' => @param ip_str The string to convert @return Integer value """ array = map(lambda val: int(val), ip_str.split(".")) val = 0 for...
def analyseWords(mywords, additionals=''): """Analyse mywords and return all used characters. The characters are sorted by occurence (descending). """ mydict = {} moreletters = [] for word in mywords: # create dict with occurence of letters in all words for letter in word.lower(): ...
def clean_context(context): """ This function take a dictionary and remove each entry with its key starting with 'default_' """ return {k: v for k, v in context.items() if not k.startswith('default_')}
def bits(s, e, byte): """ Extract bits start, end, byte Ex. bits(4,2,27) == 0b110 (extracting bits 4, 3 and 2) """ byte = byte>>e return byte & [1, 3, 7, 15, 31, 63, 127, 255][s-e]
def make_path(wname, wdate, sname, sdate): """Create the api path base string to append on livetiming.formula1.com for api requests. The api path base string changes for every session only. Args: wname: Weekend name (e.g. 'Italian Grand Prix') wdate: Weekend date (e.g. '2019-09-08') ...
def transform_feature_on_popularity(feature: str, feature_popularity: dict) -> str: """ INPUT feature - any categorical feauture (e.g., Developer, full-stack; Developer, back-end) feature_popularity - a dictionary mapping the feature to popularity OUTPUT transformed feature - the more popular fe...
def elf_hash(name): """ ELF hashing function. See figure 2-15 in the ELF format PDF document. """ h = 0 for c in name: h = (h << 4) + ord(c) g = h & 0xF0000000 if g: h ^= g >> 24 h &= ~g assert h >= 0 return h
def convert_list2str(list_data, space_mark = ''): """ :param list_data: One-dimensional list data :param space_mark: The spacing symbol between string :return: List of converted strings """ s = "" list_len = len(list_data) for i in range(list_len): data = list_data[i] s +...
def force_list_to_length(list, length): """ Force a list to be a certain list in order that it can be stacked with other lists to make an array when working out epidemiological outputs. No longer used because was for use in model_runner to make all the new data outputs the same length as the first. ...
def allindex(value, inlist): """ Mathematica Positions -equivalent :param value: :param inlist: list from which to find value :return: all indices """ # indices = [] # idx = -1 # while True: # try: # idx = qlist.index(value, idx+1) # indices.append(idx...
def _nuke_newlines(p_string): """ Strip newlines and any trailing/following whitespace; rejoin with a single space where the newlines were. Trailing newlines are converted to spaces. Bug: This routine will completely butcher any whitespace-formatted text. @param p_string: A string with embedde...
def suppressMultipleSpaces(x): """ Returns the string X, but with multiple spaces (as found in Metro Transit return values) with single spaces. """ while x.find(" ") >= 0: x = x.replace(" "," ") return x
def html_decode(s): """ Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like <p>. """ htmlCodes = (("'", '&#39;'), ('"', '&quot;'), ('>', '&gt;'), ('<', '&lt;'), ('&', '&amp;'),(' ','&nbsp;'),('"','&#34;')) for code in htmlCodes:...
def output_clock_freq(session, Type='Real64', RepCap='', AttrID=1150004, buffsize=0, action=['Get', '']): """[Output Clock Frequency <real64>] This READ-ONLY attribute is used to ascertain the current clock frequency. Changes to the clock frequency must be accomplished with the OutputConfigureSampleClock f...
def join_(str_, iterable): """functional version of method join of class str """ return str_.join(map(str,iterable))
def dict_list_search(l, keys, value): """ Search a list of dictionaries of a common schema for a specific key/value pair. For example: l = [{'a': foo, 'b': 1, 'c': 2}, {'a': 'bar', 'b': 3, 'c': 4}] If `keys='a'` and `value='foo'` then the first dict in the list would be returned. """ v...
def transpose_list(list_of_dicts): """Transpose a list of dicts to a dict of lists. :param list_of_dicts: to transpose, as in the output from a parse call :return: Dict of lists """ res = {} for d in list_of_dicts: for k, v in d.items(): if k in res: res[k].a...
def _translate_time(time): """ Translate time from format: Feb 8 01:44:59 EST 2013 to format: 2013/03/06-00:17:54 """ # get all parts time_parts = time.split() # do we have the correct number of parts? if len(time_parts) != 5: raise Exception("Unexpected number of parts in time: " + time) # v...
def highlight_pos(cell): """ helper function for pd.DataFrame display options. It changes color of text in cell to green, red, orange depending on value Parameters ---------- cell: value in pd.DataFrame cell Returns ------- str : color of text in cell """ ...
def removeprefix(prefix: str, string: str) -> str: """Remove the prefix from the string""" return string[len(prefix) :] if string.startswith(prefix) else string
def bucket_bin(item, ndivs, low, width): """ Return the bin for an item """ assert item >= low, Exception("negative bucket index") return min(int((item - low) / width), ndivs-1)
def binary_range(bits): """Return a list of all possible binary numbers in order with width=bits. It would be nice to extend it to match the functionality of python's range() built-in function. """ l = [] v = ['0'] * bits toggle = [1] + [0] * bits while toggle[bits] != 1...
def print_summary(targets): """ Return 0 if all test passed Return 1 if all test completed but one or more failed Return 2 if one or more tests did not complete or was not detected """ passed = 0 failed = 0 tested = 0 expected = 0 return_code = 3 print("---------------------...
def group_consecutives(vals, step=1): """ Return list of consecutive lists of numbers from vals (number list). References: Modified from the following https://stackoverflow.com/questions/7352684/ how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy """ ...
def evapor_channel(Vc0, ETo, W, X): """Compute the evaporation from a channel store. Calculate the evaporation loss from a channel store. The function attempts to remove the demand from the open water potential evaporation from the channel store, if there isn't sufficient water in the store then th...
def shout_echo(word1,echo=1,intense=False): """Concatenate echo copies of word1 and three exclamation marks at the end of the string.""" # Concatenate echo copies of word1 using *: echo_word echo_word = word1 * echo # Capitalize echo_word if intense is True if intense is True: # Capitali...
def _dict_diff(old: dict, new: dict) -> dict: """ Recursive find differences between two dictionaries. :param old: Original dictionary. :param new: New dictionary to find differences in. :return: Dictionary containing values present in :py:attr:`new` that are not in :py:attr:`old`. """...
def generate_resource_url( url: str, resource_type: str = "", resource_id: str = "", version: str = "v1" ) -> str: """ Generate a resource's URL using a base url, the resource type and a version. """ return f"{url}/{resource_type}/{resource_id}"
def get_igmp_status(cli_output): """ takes str output from 'show ip igmp snooping | include "IGMP Snooping" n 1' command and returns a dictionary containing enabled/disabled state of each vlan """ search_prefix = "IGMP Snooping information for vlan " vlan_status={} counter = 0 line_list ...
def get_RB_data_attribute(xmldict, attr): """Get Attribute `attr` from dict `xmldict` Parameters ---------- xmldict : dict Blob Description Dictionary attr : string Attribute key Returns ------- sattr : int Attribute Values """ try: ...
def euler_tour_dfs(G, source=None): """adaptation of networkx dfs""" if source is None: # produce edges for all components nodes = G else: # produce edges for components with source nodes = [source] yielder = [] visited = set() for start in nodes: if start...
def _is_str(text): """Checks whether `text` is a non-empty str""" return isinstance(text, str) and text != ""
def mergeHalves(leftHalf, rightHalf): """ Merge two halves and return the merged data list """ sortedData = list() while leftHalf and rightHalf: smallerDataHolder = leftHalf if leftHalf[0] < rightHalf[0] else rightHalf minData = smallerDataHolder.pop(0) sortedData.append(minData) ...
def FilterKeptAttachments( is_description, kept_attachments, comments, approval_id): """Filter kept attachments to be a subset of last description's attachments. Args: is_description: bool, if the comment is a change to the issue description. kept_attachments: list of ints with the attachment ids for a...
def node_para(args): """ Node parameters. :param args: args :return: node config or test node config list """ node_list = [] i = 0 if args.find("//") >= 0: for node in args.split("//"): node_list.append([]) ip, name, passwd = node.split(",") n...
def new_value(seat: str, neighbors: str): """ Returns the new state of one seat. """ occupied_count = neighbors.count("#") if seat == "L" and occupied_count == 0: return "#" elif seat == "#" and 4 <= occupied_count: return "L" else: return seat
def find_digits(n): """Hackerrank Problem: https://www.hackerrank.com/challenges/find-digits/problem An integer d is a divisor of an integer n if the remainder of n / d = 0. Given an integer, for each digit that makes up the integer determine whether it is a divisor. Count the number of divisors occur...
def _GetExceptionName(cls): """Returns the exception name used as index into _KNOWN_ERRORS from type.""" return cls.__module__ + '.' + cls.__name__
def fib(n): """ Calculate a fibonacci number """ a, b = 0, 1 for _ in range(n): a, b = b, a + b return a
def relative_target_price_difference(side: str, target_price: float, current_price: float) -> float: """ Returns the relative difference of current_price from target price. Negative vallue could be considered as "bad" difference, positive as "good". For "sell" order: relative_target_price_difference = ...
def iou(box1, box2): """ From Yicheng Chen's "Mean Average Precision Metric" https://www.kaggle.com/chenyc15/mean-average-precision-metric helper function to calculate IoU """ x11, y11, x12, y12 = box1 x21, y21, x22, y22 = box2 w1, h1 = x12-x11, y12-y11 w2, h2 = x22-x21, y...
def padded_slice_filter(value, page_number): """ Templatetag which takes a value and returns a padded slice """ try: bits = [] padding = 5 page_number = int(page_number) if page_number - padding < 1: bits.append(None) else: bits.append(pag...
def merge(left: list, right: list) -> list: """Merges 2 sorted lists (left and right) in 1 single list, which is returned at the end. Time complexity: O(m), where m = len(left) + len(right).""" mid = [] i = 0 # Used to index the left list. j = 0 # Used to index the right list. while i < ...
def resolve_name_obj(name_tree_kids): """Resolve 'Names' objects recursively. If key 'Kids' exists in 'Names', the name destination is nested in a hierarchical structure. In this case, this recursion is used to resolve all the 'Kids' :param name_tree_kids: Name tree hierarchy containing kid needed to ...
def array_check(lst): """ Function to check whether 1,2,3 exists in given array """ for i in range(len(lst)-2): if lst[i] == 1 and lst[i+1] == 2 and lst[i+2] == 3: return True return False
def num(mensurationString): """Transform the characters 'p' and 'i' to the values '3' and '2', respectively, and return the appropriate numeric value. Arguments: mensurationString -- one-character string with two possible values: 'i' or 'p' """ strings_for_mensuration = ['p', 'i'] numbers_for_m...
def b2s(b): """ Binary to string. """ ret = [] for pos in range(0, len(b), 8): ret.append(chr(int(b[pos:pos + 8], 2))) return "".join(ret)
def interval_to_milliseconds(interval): """Convert a Bitrue interval string to milliseconds :param interval: Bitrue interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: None if unit not one of m, h, d or w None if string not in correc...
def cubeSum(num): """assumes num is an int returns an int, the sum of cubes of the ints 1 to n""" cube_sum = 0 for i in range(1, num+1): cube_sum += i**2 return cube_sum
def find_cnc_loc(code): """get CNC's location""" if code in [1, 2]: cnc_loc = 0 elif code in [3, 4]: cnc_loc = 1 elif code in [5, 6]: cnc_loc = 2 else: cnc_loc = 3 return cnc_loc
def reverseNumberv3(num): """assumes num is a int returns an int, the reverse of num""" holding_num = num return_num = 0 while holding_num > 0: return_num += (holding_num % 10) * (10 ** (len(str(holding_num)) - 1)) holding_num //= 10 return return_num
def check_valid_relname(schema, relname, tables_in_table_file, schemas_in_schema_file=None): """ check if relation is valid (can be from schema level restore) """ if ((schemas_in_schema_file and schema in schemas_in_schema_file) or (tables_in_table_file and (schema, relname) in tables_in_table_fi...
def add_strings(a, b): """Add two floats that are stored as strings""" return sum(map(float, (a, b)))
def iswinner(board, piece: str) -> int: """ piece - string - Either an "X" or "O" Checks if win conditions are met. Could check only relevant squares but not as readable. """ # Checks each row, then each col, and then the diagonals for line in [[x + 3 * y for x in range(3)] for y in range(3)...
def compare_lists(la, lb): """Compare two lists.""" if len(la) != len(lb): return 1 for i in range(0, len(la)): sa = la[i] sb = lb[i] if sa != sb: return 1 return 0
def SanitizeJs(s): """Sanitizes JS input""" return s.lower().replace('script', 'span')
def combine_exif(exif_data, lut, d): """ Add extracted exif information to master list of HP data :param exif_data: dictionary of data extracted from an image :param lut: LUT to translate exiftool output to fields :param fields: master dictionary of HP data :return: fields - a dictionary with up...
def quaternary_spherical(rho, phi): """Zernike quaternary spherical.""" return 252 * rho**10 \ - 630 * rho**8 \ + 560 * rho**6 \ - 210 * rho**4 \ + 30 * rho**2 \ - 1
def clamp_str(string, **kwargs): """Returns 'foo...' for clamped strings. Args: maxlen: limits of the string length eat_lf: if True, replaces \n with their textual representation <Ignores other arguments> """ maxlen = kwargs.get('maxlen', 50) if maxlen > 3 and len(string) >= (maxl...
def _are_all_ints(arr): """Check whether all elements in arr are ints.""" for a in arr: if not isinstance(a, int): return False return True
def index_of(lst, search_item) -> int: """ Returns the index of the item in the list or -1. Args: lst: The list. search_item: The item to search for. Returns: The index in the list of the item or -1. """ for idx, item in enumerate(lst): if item == search_item: ...
def roll(x, n): """ The roll function Lifted from https://www.johndcook.com/blog/2019/03/03/do-the-chacha/ """ return ((x << n) & 0xffffffff) + (x >> (32 - n))
def prepare_update_sql(list_columns, list_values, data_code=100): """ Creates a string for the update query :param list_columns: columns that are in need of an update :param list_values: values where the columns should be updated with :param data_code: data code to add to the columns :return: st...
def is_hidden(method_name): """Return `True` if not an interface method.""" return method_name.startswith('_')
def IsSubclass(candidate, parent_class): """Calls issubclass without raising an exception. Args: candidate: A candidate to check if a subclass. parent_class: A class or tuple of classes representing a potential parent. Returns: A boolean indicating whether or not candidate is a subclass of parent_cl...
def make_scored_lexicon_dict(read_data): """ Convert lexicon file to a dictionary """ lex_dict = dict() for line in read_data.split('\n'): if not(line.startswith('#')): (word, measure) = line.strip().split('\t')[0:2] lex_dict[word] = float(measure) return lex_dict
def get_comp_optional_depends_r(comp_info, comps, mandatory_comps): """ Get comp optional depends recursively from comp index """ depends = [] """ comps are optional dependency list from last layer """ for comp in comps: # print("comp name is:", comp["comp_name"]) if comp["comp_name"] no...
def relative_roughness(roughness, diameter): """Returns relative roughness. :param roughness: roughness of pipe [mm] or [m] (but the same as diameter) :param diameter: diameter of duct or pipe [mm] or [m] """ return round(roughness / diameter, 8)
def convert(item, cls, default=None): """ Convert an argument to a new type unless it is `None`. """ return default if item is None else cls(item)
def make_layer_list(arch, network_type=None, reg=None, dropout=0): """ Generates the list of layers specified by arch, to be stacked by stack_layers (defined in src/core/layer.py) arch: list of dicts, where each dict contains the arguments to the corresponding layer functi...
def stub_all(cls): """Stub all methods of a class.""" class StubbedClass(cls): pass method_list = [ attribute for attribute in dir(StubbedClass) if callable(getattr(StubbedClass, attribute)) and (attribute.startswith("__") is False) ] for method ...
def desi_target_from_survey(survey): """ Return the survey of DESI_TARGET as a function of survey used (cmx, sv1, sv2, sv3, main).""" if survey == 'special': # to avoid error, return one of the column, SV2_DESI_TARGET should be full of 0. return 'SV2_DESI_TARGET' if survey == 'cmx': ...
def stripcounty(s): """ Removes " County" from county name :param s: a string ending with " County" :return: """ if s.__class__ == str: if s.endswith(" County"): s = s[0:len(s)-7] return s
def as_list(obj): """Wrap non-lists in lists. If `obj` is a list, return it unchanged. Otherwise, return a single-element list containing it. """ if isinstance(obj, list): return obj else: return [obj]
def _is_bright(rgb): """Return whether a RGB color is bright or not. see https://stackoverflow.com/a/3943023/1595060 """ L = 0 for c, coeff in zip(rgb, (0.2126, 0.7152, 0.0722)): if c <= 0.03928: c = c / 12.92 else: c = ((c + 0.055) / 1.055) ** 2.4 L +...
def create_tag_body(tag, trigger_mapping): """Given a tag, remove all keys that are specific to that tag and return keys + values that can be used to clone another tag https://googleapis.github.io/google-api-python-client/docs/dyn/tagmanager_v2.accounts.containers.workspaces.tags.html#create :param ta...
def triarea(x, y, dir=0): """RETURNS THE AREA OF A TRIANGLE GIVEN THE COORDINATES OF ITS VERTICES A = 0.5 * | u X v | where u & v are vectors pointing from one vertex to the other two and X is the cross-product The dir flag lets you retain the sign (can tell if triangle is flipped)""" ux = x[1] ...
def approx_derivative(f, x, delta=1e-6): """ Return an approximation to the derivative of f at x. :param f: function that is differentiable near x :param x: input to f :param delta: step size in x :return: df/dx """ df = (f(x + delta) - f(x - delta))/2 #order 2 approximation ...
def ben_graham(eps, next_eps, bond_yield=4.24): """ Gets, or tries to get, the intrinsic value of a stock based on it's ttm EPS and the corporate bond yield. """ # growth_rate = (next_eps - eps) / eps # growth_rate *= 100 growth_rate = next_eps # The top part of the fraction: EPS x (8.5...
def funny_string(S): """A string is funny if S[i]-S[i-1] == R[i]-R[i-1] for all i > 0 where R is the reverse of S """ S = S.lower() R = "".join(reversed(S)) for i, s in enumerate(S[1:], 1): d1 = abs(ord(S[i - 1]) - ord(s)) d2 = abs(ord(R[i - 1]) - ord(R[i])) if d2 ...
def _broadcast_shapes(s1, s2): """Given array shapes `s1` and `s2`, compute the shape of the array that would result from broadcasting them together.""" n1 = len(s1) n2 = len(s2) n = max(n1, n2) res = [1] * n for i in range(n): if i >= n1: c1 = 1 else: ...
def longestSubsequence(list1, list2): """ NxM array len list1 by len list2 matches[i][j] shows num matches between first i+1 elements of list1 and first j+1 elements of list2 Initialize by locating where the first matches between first elements occur """ matches = [] for i in range(0, l...
def close(x, y, rtol, atol): """Returns True if x and y are sufficiently close. Parameters ---------- rtol The relative tolerance. atol The absolute tolerance. """ # assumes finite weights return abs(x-y) <= atol + rtol * abs(y)
def doc_modifier(doc): """ """ return doc.replace( 'delay_shift (bool, optional): flag to simulate spike propagation ' 'delay from one layer to next. Defaults to True.', 'delay_shift (bool, optional): flag to simulate spike propagation ' 'delay from one layer to next. Default...
def hex_to_bin(txt: str) -> str: """Convert hexadecimal string to binary string.Useful for preprocessing the key and plaintext in different settings.""" return bin(int(txt,16))[2:]
def batch_size(batch): """ Calculates the size of a batch. Args: batch: A list of dictionaries representing mutations. Returns: An integer specifying the size in bytes of the batch. """ size = 0 for mutation in batch: size += len(mutation['key']) if 'values' in mutation: for value in ...
def is_plain_lambda(mod): """check for the presence of the LambdReduce block used by the torch -> pytorch converter """ return 'Lambda ' in mod.__repr__().split('\n')[0]
def plane_inersection(equation, plane): """ finds the point where a line intersects with a plane :param equation: tuple of two tuples, a point tuple and a direction tuple => (x, y, z) + t*(x_diff, y_diff, z_diff) :param plane: a tuple representing a plane equation (l, m, n, A) => xl + my + nz = A :r...
def casefolding(token): """ This function will turn all the letters into lowercase. """ token_per_sesi = [] for sesi in token: token_per_chat = [] for chat in sesi: token = [] for word in chat: token.append(word.lower()) token_per_chat.appe...
def repeatedString(s, n): """Either 1,000,000,000,000 The length of S could be less than N. The length of S could be greater than N The length of S could be equal to N """ # The number of times the letter 'a' occurs in the string S. num_a = s.count('a') # If the length of S is less tha...
def leading_spaces(s: str) -> int: """Return the number of spaces at the start of str""" return len(s) - len(s.lstrip(" "))
def _height(bbox): """Return the height of a bounding box. Parameters ---------- bbox : tuple 4-tuple specifying ``(min_row, min_col, max_row, max_col)``. Returns ------- int The height of the bounding box in pixels. """ return bbox[2] - bbox[0] + 1
def yel(string): """ Color %string yellow. """ return "\033[33m%s\033[0m" % string
def max_key(dict): """ Returns the maximum key in an integer-keyed dictionary. Args: dict (dict): The integer-keyed dictionary. Returns: int: The maximum key. """ output = 0 for key, value in dict.items(): output = max(output, int(key)) return output
def onroot_vd(t, y, solver): """ onroot function to just continue if time <28 """ if t > 28: return 1 return 0
def recall_interval(recall): """Return the interval of recall classified to 11 equal intervals of 10 (the field range is 0-100)""" return ((recall*10)//1)*10
def range_list(start: int, end: int): """Problem 22: Create a list containing all integers within a given range. Parameters ---------- start : int end : int Returns ------- list A list including all numbers from `start` to `end` Raises ------ ValueError If ...