content
stringlengths
42
6.51k
def sum_square_difference(n): """Calculates difference between sum of squares and square of sum of first n natural numbers.""" sum_squares = sum([x*x for x in range(1, n+1)]) square_sum = sum([x for x in range(1, n+1)])**2 return square_sum - sum_squares
def get_RIA0(expmips): """ Expmips -> Float[0,1] produce ratio of MIP0/rest-MIPs if rest-MIPs == 0, return MIP0 """ MIP0_mz = [x[0] for x in expmips if x[-1] == 0][0] # get mz-val of x15N == 0 rest_mz = [x[0] for x in expmips if x[-1] != 0] sum_rest_mz = sum(rest_mz) if sum_...
def yes_or_no(true_or_false): """A convenience function for turning True or False into Yes or No, respectively.""" if true_or_false: return "Yes" else: return "No"
def _validate_body(payload): """ :param payload: The received json data in the query. :return: str | None Error message, if any. """ # Not Supported parameters if 'expression' in payload: return 'expression is Not Supported' if 'metadata' in payload: return 'm...
def align_offset(offset:int, align:int): """ Give the upper rounded offset aligned using the align value. input: offset = int input: align = int return offset = int """ if offset % align != 0: offset += align - (offset % align) return offset
def _ras_symmetric_difference_ ( self , another ) : """Get a difference fot two sets >>> set1 = ... >>> set2 = ... >>> set3 = set1.symmetric_difference( set2 ) """ Type = type ( self ) result = Type () for arg in self : if not arg in another : result.add ( arg ) for ar...
def v1_lstrip(iterable, strip_value): """Return iterable with strip_value items removed from beginning.""" stripped = [] is_beginning = True for item in iterable: if is_beginning and item == strip_value: continue is_beginning = False stripped.append(item) return s...
def key_vector(rows): """ Empty key vector :param rows: :return: """ return [None] * rows
def extract_char_tokens(word_counts): """Extracts all single-character tokens from word_counts. Args: word_counts: list of (string, int) tuples Returns: set of single-character strings contained within word_counts """ seen_chars = set() for word, _ in word_counts: for char...
def newton_sqrt(x: int): """uses the Newton method to return square root""" val = x while True: last = val val = (val + x /val) * 0.5 if abs(val - last) < 1e-9: break return val
def parse_config_str(config_str): """Parses config string. For example: config_str = "a=1 b='hello'", the function returns {'a': 1, 'b': 'hello'}. Args: config_str: A config string. Returns: A dictionary. """ ans = {} for line in config_str.split('\n'): k, v = line.partition('=')[::2] ...
def perform_libio_property_check(expected_properties, properties, property_name): """Return true if the selected Libio property should be checked.""" return expected_properties or property_name in properties
def RungeKutta(f, x, dt): """4th order RungeKutta integration of F starting at X.""" a = f(x) b = f(x + dt / 2.0 * a) c = f(x + dt / 2.0 * b) d = f(x + dt * c) return x + dt * (a + 2.0 * b + 2.0 * c + d) / 6.0
def getSwaggerPaginationDef(resultsPerPage): """Build swagger spec section for pagination""" return { "name": "page", "type": "int", "in": "query", "description": "The page number for this paginated query ({} results per page)".format(resultsPerPage) }
def pkcs7pad(cipher_text, block_size, value=b'\x04'): """Return ciphertext padded with value until it reach blocksize length. :param cipher_text: bytes :param block_size: int :param value: bytes :return: bytes """ length = len(cipher_text) pad = block_size - (length % block_size) ret...
def validate_user_input(url, count): """ :param url: :param count: :return: """ err_msg = '' if 'www.youtube.com/' not in url: err_msg = "URL provided in not valid!" return False, err_msg elif count > 50: err_msg = "View count exceeding the limit!" ...
def summ_n(i1, i2): """Return the summation from i1 to i2 of n""" return ((i2 * (i2+1)) / 2) - (((i1-1) * i1) / 2)
def replaceSubstr(s, start, end, newSubStr): """Replace the contents of `s' between `start' and `end' with `newSubStr'.""" return s[:start] + newSubStr + s[end:]
def have_hash_symbol(l): """Check if hash symbol is present""" if "#" in str(l): return 1 else: return 0
def specified_kwargs(names=(), items={}): """ (names:tuple(str), items:dict) -> dict Returns a dict with the *names* subset of entries in *items* for which the value is not None. """ return dict([ (n, items[n]) for n in names if items[n] is not None ])
def parse_syntax(line): """ >>> parse_syntax('syntax: glob') 'glob' >>> parse_syntax('syntax: regexp') 'regexp' >>> parse_syntax('syntax: none') Traceback (most recent call last): ... Exception: Unknown syntax "none" """ line = line.replace(':', ' ') _, syntax = line.spli...
def __none_mult(x, y): """PRIVATE FUNCTION, If x or y is None return None, else return x * y""" if x is not None and y is not None: return x * y return None
def lerp(a, b, scalar): """Lerp - Linearly interpolates between 'a' when 'scalar' is 0 and 'b' when 'scalar' is 1. a = number or Vector b = number or Vector scaler = number between 0 and 1 """ return (a + scalar * (b - a))
def _get_invoker_url(platform: str, location: str, project: str, deployment_name: str, solution_prefix: str) -> str: """Returns the url to invoke the cloud function for the specific platform. Args: platform: the target platf...
def gauss(A, B): """Solve A*X = B using the Gauss elimination method""" n = len(A) s = [0.0] * n X = [0.0] * n p = [i for i in range(n)] for i in range(n): s[i] = max([abs(x) for x in A[i]]) for k in range(n - 1): # select j>=k so that # |A[p[j]][k]| / s[p[i]] >= |...
def arrow_area(a, b): """ An arrow is formed in a rectangle with sides a and b by joining the bottom corners to the midpoint of the top edge and the centre of the rectangle. :param a: an integer value. :param b: an integer value. :return: the arrow area of a triangle. """ return (a * b) ...
def is_disc_aligned(disc, time_counter, align_offset): """Check if disc is aligned.""" return ((disc['cur_position'] + time_counter + align_offset) % disc['positions'] == 0)
def transform_results(results, keys_of_interest): """ Take a list of results and convert them to a multi valued dictionary. The real world use case is to take values from a list of collections and pass them to a granule search. [{key1:value1},{key1:value2},...] -> {"key1": [value1,value2]} -> ...
def get_solver_param(sim_param=1): """Get parameters related to this simulation run""" theta = None deadline = None horizon = None solver_type = None if sim_param == 1: theta = 2 deadline = 6 horizon = 3 solver_type = 'central' elif sim_param == 2: t...
def last_replace(s, old, new, number_of_occurrences): """ Replaces last n occurrences of the old string with the new one within the string provided :param s: string to replace occurrences with :param old: old string :param new: new string :param number_of_occurrences: how many occurrences shoul...
def verify_attribute(response): """ This function is intended to make sure we are receiving right fields from dependent APIs. :param response: Response object received from sub APIs. :return: Return response object if valid, otherwise raise exception. """ required_fields = ["title", "link",...
def descend(trace): """ Return reduced trace level. """ return trace and (trace-1)
def _tree_traversal(node, lefts, rights, features, thresholds, values, count): """ Recursive function for parsing a tree and filling the input data structures. """ if "left_child" in node: features.append(node["split_feature"]) thresholds.append(node["threshold"]) values.append([...
def get_package(module_name, is_package): """Returns a string representing the package to which the file belongs.""" if is_package: return module_name else: return '.'.join(module_name.split('.')[:-1])
def get_nodename(soname, nodenames): """Generate DOT nodename.""" if soname in nodenames: return nodenames[soname] nn = len(nodenames) seed = "".join([x if x.isalnum() else "_" for x in soname]) nn = "%s_%d" % (seed, nn) nodenames[soname] = nn return nn
def escape(value): """ Escape a string, which can be user input. Therefore quotes have to be escaped and then wrapped into own quotes. """ escape_map = [('"', '\"'), ("'", "\'")] for escape_pair in escape_map: value = value.replace(escape_pair[0], escape_pair[1]) return value
def last(element): """ A wrapper around element[-1]. params: element: an element that implements __getitem__ """ return element[-1]
def show_subpath(subpath): """ subpath """ # show the subpath after /path/ return 'Subpath %s' % subpath
def _clean(text): """Use this to avoid getting newlines in the output (PRIVATE).""" return text.replace("\n", " ").replace("\r", " ")
def _get_next_line(lines, linenumber): """ Returns the next line but skips over any empty lines. An empty line is returned if read past the last line. """ inc = linenumber + 1 num_lines = len(lines) while True: if inc == num_lines: return '' if lines[inc]: ...
def add_row(content, row_index, row_info=[]): """ From the position of the cursor, add a row Arguments: - the table content, a list of list of strings: - First dimension: the columns - Second dimensions: the column's content - cursor index for col - cursor ...
def epoch_time(start_time, end_time): """Calculate the time for an epoch""" elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs
def roundodd(num): """ Round the given number to the nearest odd number. """ rounded = round(num) if rounded % 2 != 0: return rounded else: if rounded > num: return rounded - 1 else: return rounded + 1
def merge_partials(header, used_partials, all_partials): """Merge all partial contents with their header.""" used_partials = list(used_partials) ret = '\n'.join([header] + [all_partials[u] for u in used_partials]) return ret
def reactor_efficiency(voltage, current, theoretical_max_power): """Assess reactor efficiency zone. :param voltage: voltage value (integer or float) :param current: current value (integer or float) :param theoretical_max_power: power that corresponds to a 100% efficiency (integer or float) :return:...
def char_to_word_index(char_ind: int, sent: str) -> int: """ Convert a character index to word index in the given sentence. """ return sent[:char_ind].count(" ")
def stringtoint(stringdate): """ split mm/dd/yyyy into year, month and day """ first = stringdate.split("T")[0] second = first.split("-") year = int(second[0]) month = int(second[1]) day = int(second[2]) return year, month, day
def mulNDx(v1, v2, limit=0): """Multiplies two nD vectors together, itemwise, ignoring items if they are not numeric, with an option to limit length of tuples to a certain length defined by the `limit` argument""" if limit > 0: return [vv1 * vv2 for i, (vv1, vv2) in enumerate(zip(v1, v2)) ...
def roi_intersect(a, b): """ Compute intersection of two ROIs. .. rubric:: Examples .. code-block:: s_[1:30], s_[20:40] => s_[20:30] s_[1:10], s_[20:40] => s_[10:10] # works for N dimensions s_[1:10, 11:21], s_[8:12, 10:30] => s_[8:10, 11:21] """ def slice_inter...
def user_id_or_guest(user_id): """Validate the input and return the userID, or the guest userID (= 1)""" try: valid_id = int(user_id) except (ValueError, TypeError): valid_id = 1 if valid_id <= 0: valid_id = 1 return valid_id
def ptest_prep_condiments(condiments): """Here the caller passes a mutable object, so we mess with it directly.""" try: del condiments["steak sauce"] except KeyError: pass condiments["spam sauce"] = 42 return f"Now this is what I call a condiments tray!"
def start_end_hour(data: list, sh: float, eh: float): """Remove wea data entries outside of the start and end hour.""" if sh == 0 and eh == 0: return data def filter_hour(dataline): return sh <= float(dataline[2]) <= eh return filter(filter_hour, data)
def locations_of_substring(string, substring): """Return a list of locations of a substring.""" substring_length = len(substring) def recurse(locations_found, start): location = string.find(substring, start) if location != -1: return recurse(locations_found + [location], loc...
def evaluate_precision_neg(tn: int, fn: int) -> float: """Negative precision, aka Negative Predictive Value (NPV). $NPV=\dfrac{TN}{TN + FN}$ Args: tn: True Negatives fn: False Negatives """ try: return tn / (tn + fn) except ZeroDivisionError: return 0.0
def smooth_timedelta(secs): """Convert seconds into Days, Hours, Minutes, Seconds.""" if isinstance(secs, str): secs = int(secs) timetot = "" if secs > 86400: # 60sec * 60min * 24hrs days = secs // 86400 if int(days) == 1: timetot += "{} day".format(int(days)) ...
def inexact(pa, pb, pc): """Direction from pa to pc, via pb, where returned value is as follows: left: + [ = ccw ] straight: 0. right: - [ = cw ] returns twice signed area under triangle pa, pb, pc """ detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]) detright = (pa[1] - pc[1]) * (pb[...
def list_inorder(listed_files, flag_str): """" List the files in order based on the file name """ filtered_listed_files = [fn for fn in listed_files if flag_str in fn] listed_files = sorted(filtered_listed_files, key=lambda x: x.strip().split(".")[0]) return listed_files
def get_element_count(the_list): """ get depth of model :param the_list: input model config :return: depth of model """ count = sum(len(x) for x in the_list) return count
def tmp_c(tet): """This function is an assistant for the byte_utf8_converter """ if tet == None or len(tet) == 0: return None try: return tet.decode('utf-8') except UnicodeDecodeError: return None
def sanitizeStr(data): """ Escape all char that will trigger an error. Parameters ---------- data: str the str to sanitize Returns ------- str The sanitized data. """ data = " ".join(data.split()) new_msg = [] for letter in data: ...
def stringify(args): """Join a list of arguments in a string.""" return " ".join(map(str, args))
def winner(board): """This function accepts the Connect Four board as a parameter. If there is no winner, the function will return the empty string "". If the user has won, it will return 'X', and if the computer has won it will return 'O'.""" for row in range(7): count = 0 last = ''...
def example_function(arg1: int, arg2: int =1) -> bool: """ This is an example of a docstring that conforms to the Google style guide. The indentation uses four spaces (no tabs). Note that each section starts with a header such as `Arguments` or `Returns` and its contents is indented. Arguments: ...
def any(iterable): """ Return True if at least one element is set to True. This function does not support predicates explicitly, but this behavior can be simulated easily using list comprehension. >>> from sympy import any >>> any( [False, False, False] ) False >>> any( [False, True...
def get_conv_outsize(in_size, ker_size, stride, pad): """ Calculate output size of conv operation. Kalculate for either height or width each. Parameters ---------- in_size: int input size ker_size: int kernel size stride: int stride pad: int padding """ retu...
def _TransformOperationName(resource): """Get operation name without project prefix.""" # operation name is in the format of: # operations/projects/{}/instances/{}/.../locations/{}/operations/{} operation_name = resource.get('name') results = operation_name.split('/') short_name = '/'.join(results[3:]) re...
def _get_reward_for_key_hash(key_hash: str, rec: list) -> int: """Get reward value for key hash in ledger state snapshot record.""" for r in rec: if r[0]["key hash"] != key_hash: continue rew_amount = 0 for sr in r[1]: rew_amount += sr["rewardAmount"] retu...
def chunk_stargazers(seq, num): """ Divide the huge User set into smaller lists. l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print (chunk_stargazers(l, 3)) print (chunk_stargazers(l, 2)) output: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] """ avg = le...
def get_intensity_matrix(pixels, option): """Set the measure of brightness to be used depending upon the option chosen, we chose between three measures namely luminance, lightness and average pixel values """ intensity_matrix = [] for row in pixels: intensity_matrix_row = [] for ...
def drop_columns(tabular, n): """drops first n items from each row and returns new tabular data >>> drop_columns([[1, 2, 3], [21, 22, 23], [31, 32, 33]], 1) [[2, 3], [22, 23], [32, 33]] """ return [row[n:] for row in tabular]
def decode(value): """Python 2/3 friendly decoding of output""" if isinstance(value, bytes): return value.decode("utf-8") return value
def has_letters_in_row(string): """Check if string has any letter repeating in row.""" return any( char == string[index + 1] for index, char in enumerate(string[:-1]) )
def convert_iface(iface): """Convert iface string like 'any', 'eth', 'eth0' to route iface naming like *, eth+, eth0. """ if iface == 'any': return '*' else: # append '+' quantifier to iface if not iface[-1].isdigit(): iface += '+' return iface
def i_b(i_ep=0,i_br=0,i_cp=0): """ Base current in a Bipolar Junction Transistor Parameters ---------- i_ep : TYPE, optional DESCRIPTION. The default is 0. i_br : TYPE, optional DESCRIPTION. The default is 0. i_cp : TYPE, optional DESCRIPTION. The default is 0. ...
def _join_list(lst, oxford=True): """Join a list of words in a grammatically correct way.""" if len(lst) > 2: s = ', '.join(lst[:-1]) if oxford: s += ',' s += ' and ' + lst[-1] elif len(lst) == 2: s = lst[0] + ' and ' + lst[1] elif len(lst) == 1: s = l...
def truncatewords(s, n, ellipsis=' [...]'): """ Truncates the string `s` to at most `n` words. """ words = s.split() if len(words) > n: return ' '.join(words[:n]) + ellipsis else: return ' '.join(words)
def format_uptime(uptime_in_seconds): """formats uptime seconds into days hours minutes""" (days, remainder) = divmod(uptime_in_seconds, 24 * 60 * 60) (hours, remainder) = divmod(remainder, 60 * 60) (minutes, remainder) = divmod(remainder, 60) return f"{days}d {hours}h {minutes}m"
def exchangeCols(M, c1, c2): """Intercambia las columnas c1 y c2 de M""" for k in range(len(M)): M[k][c1] , M[k][c2] = M[k][c2], M[k][c1] return M
def interaction_dictionary(interaction_types): """ Create index dictionary for interactions. """ interaction_i = range(0, len(interaction_types)) interaction_dict = dict(zip(interaction_types, interaction_i)) return interaction_dict
def get_style(is_white_cell, is_white_piece, is_selected, is_targeted): """Returns the associated style for the provided combination of piece and cell""" if is_white_cell: return 'white_cell' elif is_targeted: return 'magenta_cell' elif is_selected: if is_white_piece: return 'red_cell_white_piec...
def _cast(value, schema_type): """Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A s...
def cauchy2(x0, y0, gx, gy, x, y): """2-D Cauchy""" #return INVPI * gx/((x-x0)**2+gx**2) * gy/((y-y0)**2+gy**2) return (gx*gy)**2 / ((x-x0)**2 + gx**2) / ((y-y0)**2 + gy**2)
def SVGParseFloat(s, i=0): """ Parse first float value from string Returns value as string """ start = i n = len(s) token = '' # Skip leading whitespace characters while i < n and (s[i].isspace() or s[i] == ','): i += 1 if i == n: return None, i # Read si...
def get_cdo_genweights_cmd(method): """Define available methods to generate interpolation weights in CDO.""" d = {'nearest_neighbors': 'gennn', 'idw': 'gendis', 'bilinear': 'genbil', 'bicubic': 'genbic', 'conservative': 'genycon', 'conservative_SCRIP': 'gencon'...
def _grouping(data): """Return different scores sorted, grouped scores, and their sample sizes. See `collect_data()`.""" scores = [d['score'] for d in data] labels = [d['label'] for d in data] n_labels = max(labels) + 1 groups = [[] for _ in range(n_labels)] for s, l in zip(scores, labels):...
def delete_empty_keys(dic): """ Deleting every key from a dictionary where the values are empty """ return {k: v for k, v in dic.items() if v is not None}
def inflate(size, margin, mul=1): """ Increase size (a size or rect) by mul multiples of margin margin's items are interpreted as those of a CSS margin. If size is a 4-tuple, its "sides" are moved outwards by the corresponding items of margin; if it is a 2-tuple, it is treated as if it were a rect ...
def points_to_bbox(p): """ from a list of points (x,y pairs) - return the lower-left xy and upper-right xy """ llx = urx = p[0][0] lly = ury = p[0][1] for x in p[1:]: if x[0] < llx: llx = x[0] elif x[0] > urx: urx = x[0] if x[1] < lly: lly = x[1] elif x[1]...
def nameIdHandler(name): """ <@! ID > = pinging user <@& ID > = pinging role Usage - remove the brakets around the ID return - the ID """ if name.startswith('<@!') or name.startswith('<@&'): return name[:-1][3:] return name
def gas_density(temp, pressure, sg, z): """ Calculate Gas Density For range: this is not a correlation, so valid for infinite intervals """ temp = temp + 459.67 R = 10.732 # gas constant in (ft3*psi)/(lb-mol*R) rhogas = (28.97 * sg * pressure) / (z * R * temp) return rhogas
def add(type, valA, valB): """ Sum two vals """ one = ["transmission"] two = ["memory"] three = ["processing"] if type in one: return valA + valB if type in two: return valA + valB if type in three: return valA + valB print("type not found. Exiting.") ...
def _decide_to_log(v): """Hacky workaround for now so we could specify per each which to log online and which to the log""" if isinstance(v, bool) or callable(v): return v elif v in {'online'}: return True elif v in {'offline'}: return False else: raise ValueError...
def concat_strings(a,b, **kwargs): """concatenate strings""" seq = a+b for key in kwargs: seq += kwargs[key] return seq
def removeListIntervals(l, intervals): """ This function will remove portions of text according to string intervals. You have to apply `text = reduceBlank(text, keepNewLines=True)` just after. :example: >>> removeListIntervals(['a', 'b', 'c', 'd', 'e'], [(1, 2), (3, 4)]) ['a', 'c', 'e'] """ newL = [] cur...
def reduce_duplicate_urls(url_list): """ because the shapefiles are in 2 meter, the tiles are 4 fold, therfore make a selection, to bypass duplicates Parameters ---------- url_list : list list of strings with url's of www locations Returns ------- url_list : list redu...
def total_gates(n): """Returns total number of gates without combines.""" return 3*(n//2)*n
def mode_manual(l): """ l: List of integers return mode of list l. if there is more than one mode, then pick lowest """ dict_mode = {} for n in l: i = l.count(n) if i not in dict_mode.keys(): dict_mode[i] = [n] else: dict_mode[i].append(...
def pattern_pos(element_number: int, position: int) -> int: """Return the pattern multiplier for parm element number at parm position.""" region = (position + 1) // element_number quartet = region % 4 output = [0, 1, 0, -1][quartet] return output
def moz_to_unix_timestamp(ts): """Convert Mozilla timestamp to Unix timestamp.""" try: return ts // 1000000 except TypeError: return 0
def strictly_decreasing(L): """ References: http://stackoverflow.com/questions/4983258/python-how-to-check-list-monotonicity """ return all(x > y for x, y in zip(L, L[1:]))