content
stringlengths
42
6.51k
def sizeof_fmt(num, suffix='B'): """ Convert Memory Usage To Byte size """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def parseEnviron(text): """ split Environ data into desc, addr, val arrays """ env_desc, env_addr, env_vals = [], [], [] for eline in text: eline = eline.replace('\t',' ').strip() desc, val = [i.strip() for i in eline[1:].split('=')] addr = '' if '(' in desc: n = ...
def op_dup(stack) -> bool: """ Duplicates an element on the stack """ if len(stack) < 1: return False stack.append(stack[-1]) return True
def _eglFunc(name, method, static=None, public=False, inheader=None, prefix="dispatch_", extension=None, retval=None): """ A convenience function to define an entry in the EGL function list. """ if static is None: static = (not public and method != "custom") if inheader is None: inhe...
def f1score(precision_value, recall_value, eps=1e-5): """Calculating F1-score from precision and recall to reduce computation redundancy. Args: precision_value: precision (0-1) recall_value: recall (0-1) eps: epsilon to use Returns: F1 score (0-1) """ numerator = 2 ...
def paranteza_deschisa(paranteza): """ Functia returneaza, pentru un tip de paranteza inchisa, acelasi tip de paranteza dar deschisa. Astfel: ')' => '(', ']' => '['. """ if paranteza == ')': return '(' if paranteza == ']': return '['
def google_get_category(types_array): """ Parameters: types_array consists of the "types" field that can be found in the google raw_response Output: categories_string: string Returns a concatenated string of the different types """ categories_string = None if types_array: c...
def tokens_to_text(token_list): """Convert a list of binja tokens to plain text Mostly useful for testing """ return ''.join([tok.text for tok in token_list])
def make_cluster_values_adjacent(in_clustering): """ Reduces a cluster distribution to one where every cluster number is adjacent to another, starting at 0. This means that if there are n=10 clusters, every cluster will be guaranteed to be the values 0 to 9. Parameters ---------- in_clustering ...
def vote(sequence, weights=None): """Return a list of unique objects from the *sequence* sorted by frequency. :rtype: list[(obj, count, freq)] """ cands = {} for o, w in zip(sequence, weights if weights else iter(lambda: 1, 2)): cands[o] = cands.get(o, 0) + w cnt = sum(cands.values()) ...
def build_fe_heapbyte_metrics(fe): """Build FE Server HeapBytes""" metrics = [] for f in fe: metric = ["System/Windows", "ManagedHeapBytes", "InstanceId", f.get('InstanceId')] metrics.append(metric) return metrics
def format_price(price): """Formats price by inserting a decimal point in the appropriate place.""" return "${:.2f}".format(float(price)/100.0)
def alpha(d, Re): """Heat transfer coefficient Keyword arguments: Re -- Reynolds number d -- Diameter of cooling channel """ alpha = (0.031395 / (d*10**-3)) * (Re**0.8) return alpha
def apply_replace(x): """Replace latex commands in cells""" _replace = [r'\textbf{', '}', r'\bf'] if isinstance(x, str): for _r in _replace: x = x.replace(_r, '') return x else: return x
def clean_library_name(assumed_library_name): """ Most CP repos and library names are look like this: repo: Adafruit_CircuitPython_LC709203F library: adafruit_lc709203f But some do not and this handles cleaning that up. Also cleans up if the pypi or reponame is passed in instead of the...
def numstr(number, decimalpoints: int) -> str: """ Add commas, and restrict decimal places """ fmtstr = '{:,.%sf}' % str(decimalpoints) return fmtstr.format(number)
def learning_rate(initial_lr, epoch): """Sets the learning rate to the initial LR decayed by a factor of 10 every N epochs""" lr = initial_lr * (0.975 ** (epoch// 2)) return lr
def is_player_out_of_bounds(zone_on, grid_length, side, depth): """ Check if a player is outside the bounds of the map. :param zone_on: The zone the player is currently on. :param grid_length: The length of the grid, determined at the beginning of the match. :param side: The side we are checking if ...
def calculate_error(k_means_matrix): """Calculate the sum of distance from each point to its nearest cluster center Args: k_means_matrix: distance matrix of point to cluster center Returns: Sum of distance from each point to its nearest cluster center """ return sum([min(dist) for ...
def get_average_plot_values(values, names, agglomeration): """ values = instance_name --> [((key=prefix + metric), value), ...] """ result = dict() for name in names: # prepare lists result[name] = list() for _, v in values.items(): # aggregate over all instances for name, value in v: ...
def to_bool(cfg_value): """Convert config file booleans to Python booleans.""" if cfg_value in {"0", "false", "False", "no"}: return False if cfg_value in {"1", "true", "True", "yes"}: return True raise ValueError("Value {} in config file must be boolean in" " a form...
def _find_sequence_indices(container, value): """Find indices of value in container. The indices will be in reverse order, to allow safe editing. """ indices = [] for i in range(len(container)-1, -1, -1): if container[i] is value: indices.append(i) return indices
def normalize_json_fields(result_list): """ Makes sure that each json contains the same fields. Adds them with None as value if any field is missing. """ found_keys = set() for item in result_list: found_keys.update(item.keys()) for item in result_list: for key in f...
def shift(matrix, direction, dist): """ Shift a 2D matrix in-place the given distance of rows or columns in the specified (NONE, UP, DOWN, LEFT, RIGHT) direction and return it. """ NONE, UP, DOWN, LEFT, RIGHT = 'unshifted', 'up', 'down', 'left', 'right' if dist and direction in (UP, DOWN, LEFT, ...
def add_tab(num_tabs): """ Add given number of tabs and return the string """ curr_str = "\t" * num_tabs return curr_str
def spg_line_search_step_length(current_step_length, delta, f_old, f_new, sigma_one=0.1, sigma_two=0.9): """Return next step length for line search.""" step_length_tmp = (-0.5 * current_step_length ** 2 * delta / (f_new - f_old - current_step_length * delt...
def assoc_in(d, keys, value, factory = dict): """ Update value in a (potentially) nested dictionary This function was inspired by toolz.update_in and adopted for bazel. Source: https://github.com/pytoolz/toolz/blob/master/toolz/dicttoolz.py Args: d: dictionary on which to operate ...
def dedup_and_title_case_names(names): """Should return a list of title cased names, each name appears only once""" names = [n.title() for n in set(names)] return names
def is_fullname_suffix(s): """ Returns Trus if S is a full name suffix """ return s.upper().strip() in ['JUNIOR', 'SENIOR', 'JR', 'JR.', 'SR', 'SR.', 'DR', 'DR.', 'PHD', "PHD.", "SIR", "ESQ", "ESQ.", "I", "II", "III", "IV", "V", "VI", "1ST", "2ND", "3RD", "4TH", "5TH", "6TH"]
def ismultlist(x: list): """ Verify if a list is multidimensional :param list x: list itself :return: whether list is multidimensional """ if x: return ((isinstance(x, list)) and isinstance(x[0], list)) else: return False
def calc_price_to_sell(price, fee:float): """Calculate the fee to sell.""" fee_perc = fee / 100 return (1 + fee_perc) / (1 - fee_perc) * price
def load_word_list(filename): """ Loads a list of the words from the url, removing all non-alpha-numeric characters from the file. """ handle = open('data.txt', 'r') # Load a list of whitespace-delimited words from the specified file raw_text = handle.read().strip().split() # Strip non-a...
def isbn_13_check_digit(twelve_digits): """Function to get the check digit for a 13-digit ISBN""" if len(twelve_digits) != 12: return None try: int(twelve_digits) except Exception: return None thirteenth_digit = 10 - int(sum((i % 2 * 2 + 1) * int(x) for i, x in enumer...
def get_first_word(tabbed_info): """ Get the first word in a sentence, this is useful when we want to get file type, for instance, >> get_first_word('bigBed 6 +') will return 'bigBed' :param tabbed_info: the string (e.g. 'bigBed 6 +') :returns: the first word in the string """ return tab...
def total_polarizability(tensor): """ Calculate the total static polarizability value from the tensor which is given in x,y,z coordinates (Bohr). Assumes that value is an average of the xx, yy, zz components. :param tensor: 3x3 polarizability tensor in XYZ coords (Bohr) :type tenso...
def function_(x): """ example for this topic caculus f(x) = 3 * x^2 - 4 * x """ return 3 * x ** 2 - 4 * x
def compareRecord(recA , recB, attr_comp_list): """Generate the similarity vector for the given record pair by comparing attribute values according to the comparison function and attribute numbers in the given attribute comparison list. Parameter Description: recA : List of firs...
def get_abos_options(clang_version_info): """ Get options to enable aggressive-binary-operation-simplification. Returns list of options which enables aggressive-binary-operation-simplification option (which is needed for the iterator checker) if the Clang version is greater then 8. Otherwise return...
def extract_config(config, prefix): """return all keys with the same prefix without the prefix""" prefix = prefix.strip('.') + '.' plen = len(prefix) value = {} for k, v in config.items(): if k.startswith(prefix): value[k[plen:]] = v return value
def check_help_flag(addons: list) -> bool: """Checks to see if a help message needs to be printed for an addon. Not all addons check for help flags themselves. Until they do, intercept calls to print help text and print out a generic message to that effect. """ addon = addons[0] if any(arg in a...
def set_size(width, fraction=1): """ Set aesthetic figure dimensions to avoid scaling in latex. Parameters ---------- width: float Width in pts fraction: float Fraction of the width which you wish the figure to occupy Returns ------- fig_dim: tuple D...
def bubble_sort(array): """ Sort array in ascending order by bubble sort Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent pairs and swaps them if they are in the wrong order. - Best-case time perform...
def create_command_line(args): """ @param args:list of arguments @return: the field names and values This function will take an arbitrary list of field naes and values and properly create a string that is used to insert the data into the database. """ numparamsleft = len(args) fieldna...
def filt_all(list_, func): """Like filter but reverse arguments and returns list""" return [i for i in list_ if func(i)]
def axis_helper(y_shape, x_shape): """ check which axes the x has been broadcasted Args: y_shape: the shape of result x_shape: the shape of x Return: a tuple refering the axes """ res = [] j = len(x_shape) - 1 for i in range(len(y_shape) - 1, -1, -1): if ...
def day_of_week_one_line(y, m, d): """Oneliner just for fun.""" return (y-(m<3)+(y-(m<3))//4-(y-(m<3))//100+(y-(m<3))//400+ord('-bed=pen+mad.'[m])+d)%7
def comma_separate(elements) -> str: """Map a list to strings and make comma separated.""" return ", ".join(map(str, elements))
def nbSyllables(word, sep): """ Counts the number of syllables in a word @param String word: the word @param String sep: the separator to use """ return len(word.split(sep))
def guessFont(fname): """Given a font name (like Tahoma-BoldOblique) guess what it means. Returns (family, x) where x is 0: regular 1: italic 2: bold 3: bolditalic """ if '-' not in fname: return fname, 0 italic = 0 bold = 0 family, mod = fname.split...
def concatenate(symbs): """ ['C','H','H','H','H'] --> 'CH4' """ ns = len(symbs) formula = '' groups = [[],] cntg = 0 cnt = 0 while True: if cnt > ns - 1: break gs1 = groups[cntg] gs2 = [] sj = symbs[cnt] if sj not in gs1: ...
def _split_deps(deps): """ Split the provider deps into Jvm and JS groups. """ jvm_deps = [] js_deps = [] for d in deps: # There is no good way to test if a provider is of a particular type so here we are # checking existence of a property that is expected to be inside the provider. ...
def _cookie_to_set_cookie_value(cookie): """Given a cookie defined as a dictionary with name and value keys, and optional path and domain keys, return the equivalent string that can be associated to a ``Set-Cookie`` header.""" decoded = {} for key in ("name", "value", "path", "domain"): if c...
def expand_partial(_ctx, partial_name): """Filter for expanding partial path from name of partial.""" return '/partials/{0}/{0}.html'.format(partial_name)
def manhattan_distance(board_state, size=3): """Sum up the manhattan distance of all numbers in the board.""" diff = 0 for y in range(size): for x in range(size): idx = board_state[y][x] - 1 if idx != 8: diff += abs(idx % size - x) + abs(idx // size - y) r...
def parse_int_list(par_list): """ Formates the raw input from ConfigParser (e.g. '[1, 2, 4, 8]') to [1, 2, 4, 8] """ return [int(i) for i in par_list.strip('[').strip(']').split(',')]
def einstein_sum_s_norm(a, b): """ Einstein sum s-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns einstein sum s-norm of a and b Examples -------- >>> a = random.random(10,) >>> b...
def color_distance(c1, c2): """ Metric to define the visual distinction between two (r,g,b) colours. Inspired by: https://www.compuphase.com/cmetric.htm :param c1: (r,g,b) colour tuples. r,g and b are values between 0 and 1. :param c2: (r,g,b) colour tuples. r,g and b are values between 0 and 1. ...
def asciiupper(s): """convert a string to uppercase if ASCII Raises UnicodeDecodeError if non-ASCII characters are found.""" s.decode('ascii') return s.upper()
def filter_linker_flavour(args): """Remove `-flavor gnu`.""" new_args = [] ignore = False for arg in args: if ignore: ignore = False # ignore this argument else: if arg == '-flavor': ignore = True else: new_args.append(a...
def _add_deprecation_to_docstring(doc, date, instructions): """Adds a deprecation notice to a docstring.""" if not doc: lines = ['DEPRECATED FUNCTION'] else: lines = doc.splitlines() lines[0] += ' (deprecated)' notice = [ '', 'THIS FUNCTION IS DEPRECATED. It will be removed after %s.' %...
def go_left(x: int, y: int) -> tuple: """ Go 1 unit in negative x-direction :param x: x-coordinate of the node :param y: y-coordinate of the node :return: new coordinates of the node after moving a unit in the negative x-direction """ return x - 1, y
def BaseNotation(N, base, max_power): """ We get power of base and digit multiplier. Eg. if N = 346, base = 10 we return [3.46, 2] because 3.46 * 10^2 = 346 Args: N: int, number to find bounds for. MUST BE > 0 base: int max_power: int (limit so function doesn't ru...
def get_data(data, var): """Adjust data units if required""" if var in ['precipitation_flux', 'water_evaporation_flux', 'precipitation minus evaporation flux']: data = data * 86400 return data
def isBrightSpeckleStar(starPeak, imagePeak): """ Can this star have halo speckles? If it's half the peak brightness, it is assumed yes. """ return (starPeak > (0.5 * imagePeak))
def intersection(ls1, ls2): """ This function returns the intersection of two lists without repetition. This function uses built in Python function set() to get rid of repeated values so inputs must be cast to list first. Parameters: ----------- ls1 : Python list The first l...
def get_country(x): """ returns the int value for the ordinal value country """ if x == 'United-States': return 1 elif x == 'Philippines': return 2 elif x == 'Puerto-Rico': return 3 elif x == 'Mexico': return 4 elif x == 'Dominican-Republic': return 5...
def range_of_sample(*variables): """Return the range of a sample. Input: *float (all variables as arguments) Output: int """ return max(variables) - min(variables)
def f3(n): """Returns the c_n element of the sequence.""" Cn = 0 for k in range(1, int(n)+1): k = float(k) Cn += k**(-4.0) Cn *= 90.0 Cn **= .25 return Cn
def have_mentioned_vp(prods, mentions): """ Heursitics to make sure that mentioned entities and propertied are predicted """ if len(mentions["exact"]["property"]) > 0 and not all( any(v in prod for prod in prods) for v in mentions["exact"]["property"] ): em_p_flag = False else: ...
def toExport8F8(op): """Converts number to exportable 8.8 signed fixed point number.""" return int(round(op * 256.0))
def git_refs_find_deltas(previous_refs, current_refs): """Finds new or updated git refs. Identifies the new git refs and the git refs whose commit hashes are different in current refs. Git refs present in previous_refs but missing from current_refs are ignored. Args: previous_refs: Dictionary of git ref...
def compute_relevance(length): """ Return a computed ``relevance`` given a ``length`` and a threshold. The relevance is a integer between 0 and 100 where 100 means highly relevant and 0 means not relevant at all. The relevance is computed base on the rule or detection ``length`` using a relevan...
def list_math_division(a, b): """! @brief Division of two lists. @details Each element from list 'a' is divided by element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematic division. @param[in] b (list): List of elements that supports mathematic div...
def transpose_list(l): """ Transpose a list. :param l: List to transpose :return: Transposed list """ result = [list(x) for x in zip(*l)] return result
def format_num_3(num): """ Format the number to 3 decimal places. :param num: The number to format. :return: The number formatted to 3 decimal places. """ return float("{:.3f}".format(num))
def QuinticTimeScaling(Tf, t): """Computes s(t) for a quintic time scaling :param Tf: Total time of the motion in seconds from rest to rest :param t: The current time t satisfying 0 < t < Tf :return: The path parameter s(t) corresponding to a fifth-order polynomial motion that begins and ends at zero velocit...
def __get_f_from_idx(idx, f): """ Returns the value of f from the index Parameters ---------- idx: array array with indices for which frequencies are required Returns ------- f: array array with frequencies corresponding to idx ...
def _largest_valid_index(spans, limit): """return largest valid index""" for idx, _ in enumerate(spans): if spans[idx][1] >= limit: return idx return len(spans)
def filter_default(items): """Remove from a list the automated created project for a user. This project is created during the user registration step and is needed for the user to be able to perform operations in the cloud, as a work around the Keystone-OpenStack project behaviour. We don't want the user...
def create_pdic_param(name, values): """ Create a fake procpar dictionary element of with given name and values. """ dic = dict() dic["Dgroup"] = '1' dic["Ggroup"] = '2' dic["active"] = '1' dic["basictype"] = '1' dic["enumerable"] = '0' dic["intptr"] = '64' dic["maxvalue"] = ...
def accion_matriz_vector(m,v): """(list, list) -> list Accion de un vector sobre una matriz""" if len(m[0]) == len(v): r = [0 for i in range(len(v))] for i in range(len(m)): for k in range(len(v)): r[i] += round(m[i][k] * v[k], 3) ...
def get_node_with_children(node, model): """ Return a short list of this top node and all its children. Note, maximum depth of 10. """ if node is None: return model new_model = [node] i = 0 # not really needed, but keep for ensuring an exit from while loop new_model_changed = True w...
def get_neighborhood(cell, occ_map_shape): """ @params cell - cell coordinates occ_map_shape - shape of the occupancy map returns - list of neighbor coordinate tuples """ result = [] for i in [-1, 0, 1]: for j in [-1, 0, 1]: x = cell[0] + i y ...
def is_maxheap_sorted(heap): """Confirm that heap is maxheap sorted.""" for i in range(len(heap)): try: if heap[i] < heap[(2*i + 1)]: return False if heap[i] < heap[(2*i) + 2]: return False except IndexError: return True
def likes(ar): """Return a string of who likes the post. input = string with name(s) output = string with name + like(s) this ex: likes [] // must be "no one likes this" likes ["Peter"] // must be "Peter likes this" likes ["Jacob", "Alex"] // must be "Jacob and Alex like this" l...
def get_stars_dict(stars): """ Transform list of stars into dictionary where keys are their names Parameters ---------- stars : list, iterable Star objects Return ------ dict Stars dictionary """ x = {} for st in stars: try: x[st.name] = ...
def field_to_check_mark(predicate, false_value=''): """Change the value of a field to a check mark base on a predicate. :param predicate: bool value / expression. :param false_value: customizable value if predicate evaluates to false. """ return ( '\u2713' if predicate else fals...
def num_char(lista): """ Return the number of characters in a list """ all_c = "" for i in lista: all_c += str(i) return len(all_c)
def update_mean_std(existingAggregate, newValue): """Welford's Online algorithm for computing mean and std of a distribution online. mean accumulates the mean of the entire dataset. m2 aggregates the squared distance from the mean. count aggregates the number of samples seen so far. Arguments: ...
def get_all_unique_location_ids(market_datas): """ Get all unique location ids from the market data :param market_datas: the market data dictionary :return: list of locations ids """ location_ids = [] for _, market_data in market_datas.items(): for order in market_data: l...
def is_number(string): """Check if a string can be converted into a float number.""" try: float(string) return True except ValueError: return False
def is_valid(value, cast_fn, expected_data_type, allow_none=False): """ Checks whether a value can be converted using the cast_fn function. Args: value: Value to be considered cast_fn: Function used to determine the validity, should throw an exception if it cannot e...
def ip_int_to_str(val): """ That function takes a 0..2**32 interger and converts it into a string IP address. For example: 16909060 aka (1<<24)+(2<<16)+(3<<8)+4 will return 1.2.3.4 """ if not isinstance(val, int): raise TypeError('ip_int_to_str expects a number') if val < 0 or val >...
def first_true_cond(cond, arr): """ Return the index of the first element such that cond(element) returns True. The other way to do this would be where(map(cond, arr))[0][0], of where(cond(arr))[0][0] if cond is vectorized, but in some cases (large array, few cond(element) == True)) this function is qui...
def parse_wildcards(props): """ Pull out the wildcard attributes from the Component props Parameters ---------- props: dict Dictionary with {propName: propMetadata} structure Returns ------- list List of Dash valid wildcard prefixes """ list_of_valid_wildcard_at...
def create_pair(label=None, value=None): """Create a label, value Celery Script node.""" pair = {} pair['label'] = label pair['value'] = value return pair
def extract_task(tsk, tsk_lst): """ Searches for a task in the task lst and if found: the corresponding keywords and values will be returned Function only works if task is present in the list one time. :param tsk: task to extract information for :type tsk: str :param tsk_ls...
def paths_prob_to_edges_flux(paths_prob): """Chops a list of paths into its edges, and calculate the probability of that edge across all paths. Parameters ---------- paths: list of tuples list of the paths. Returns ------- edge_flux: dictionary Edge tuples as keys, and ...
def efficientnet_params(model_name): """Get efficientnet params based on model name.""" params_dict = { # (width_coefficient, depth_coefficient, resolution, dropout_rate) 'efficientnet_b0': (1.0, 1.0, 224, 0.2), 'efficientnet_b1': (1.0, 1.1, 240, 0.2), 'efficientnet_b2': (1.1, 1....
def get_pattern_enumerate(guess, solution): """generates the patterns for a guess""" hint = "" for index, letter in enumerate(guess): if not letter in solution: hint += "b" else: if letter == solution[index]: hint += "g" else: ...