content
stringlengths
42
6.51k
def fib_modified(a, b, n): """Computes the modified Fiboniacci-style function.""" for _ in range(2, n): a, b = b, a + b * b return b
def multi_text_phrase(context, slug=None, language=None): """ for using this template tag you must enable one of text_phrase context_processors. this templatetag will return list of text phrases that have this phrase_type. if you want single text phrase in special language set the language arg. ...
def inRects(R, x, y): """inRects returns True if (x, y) is in any of the rectangles in R. """ return any(x0 <= x < x1 and y0 <= y < y1 for x0, y0, x1, y1 in R)
def getAndSetNode(nID, ojDict, ojType="L"): """ Utility function to get and set a node to a dictionary ojDict type: "L" for Literal, "U" for URIRef, and "B" for BNode But it is unlikely that we would create BNode this way. """ funcMap = {"L": "Literal", "U": "URIRef", "B": "BNode"} if ojType...
def authentication_failed(err=None): """ Construct a template for SSH connection """ tpl = { 'ssh-event': 'authentication-failed' } if err is not None: tpl['error'] = err return tpl
def _VarsToLines(variables): """Converts |variables| dict to list of lines for output.""" if not variables: return [] s = ['vars = {'] for key, tup in sorted(variables.iteritems()): hierarchy, value = tup s.extend([ ' # %s' % hierarchy, ' "%s": %r,' % (key, value), '', ...
def calc_shift(layout, center_x, center_y): """Shift the x and/or y coordinates so they become centered around zero to improve plots.""" if not center_x and not center_y: # Shift nothing shift_x = shift_y = 0.0 # shift nothing else: # Shift x and/or y min_x = min_y = float('...
def pages_to_article(article, pages): """Return all text regions belonging to a given article.""" try: art_id = article['m']['id'] print("Extracting text regions for article {}".format(art_id)) regions_by_page = [] for page in pages: regions_by_page.append([ ...
def _clamp_window_size(index, data_size, window_size=200): """Return the window of data which should be used to calculate a moving window percentile or average. Clamped to the 0th and (len-1)th indices of the sequence. E.g. _clamp_window_size(50, 1000, 200) == (0, 150) _clamp_window_size(300...
def bubblesort (a): """ another bubbler""" for i in range(len(a)-1): for j in range(i+1, len(a)): if a[i]>a[j]: s = a[j] a[i+1:j+1] = a[i:j] a[i] = s return a
def find_min(nums): """ Find Minimum Number in a List :param nums: contains elements :return: max number in list >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_min(nums) == min(nums) True True True True """ min_num = nums[0] for ...
def grouping_len(grouping): """ Get the length of a grouping. The length equal to the number of scalar values contained in the grouping, which is equivalent to the length of the list that would result from calling flatten_grouping on the grouping value. :param grouping: The grouping value to calcul...
def EscapeWithUnderscores(s: str): """Replaces the non alphanumeric characters in a strings w/ _ escape codes.""" r = '' for c in s: if c == '_': r += '__' elif ('0' <= c <= '9') or ('a' <= c <= 'z') or ('A' <= c <= 'Z'): r += c else: r += f'_{ord(...
def erathostenes_sieve(n: int) -> dict: """ 1.6 Returns a dictionary containing prime numbers It is not recommended to use a list (1) because of reallocation and (2) because of index handling : the prime numbers start at 2 and the list, 0; and because some numbers are removed, the index chan...
def get_bo_trade_details(_trade_signal): """ Returns price, sqaureoff and target for the bracket order """ price = float(_trade_signal["price"]) # target = round((_trade_signal['target'] * 100 / price), 1) # stoploss = round((_trade_signal['stoploss'] * 100 / price), 1) squareoff = round((fl...
def bytes2human(bts: int) -> str: """ http://code.activestate.com/recipes/578019 >>> bytes2human(10000) '9.8K' >>> bytes2human(100001221) '95.4M' """ symbols = "YZEPTGMK" nums = (1 << i for i in range(80, 9, -10)) return next((f"{bts / n:.1f}{s}" for s, n in zip...
def writeGeneralExpr(val,Type): """ format an expression to put into the general section of the iges file; type can be 'str', 'int' or 'dim' """ if Type == 'str': if len(val) > 0: return str(len(val))+'H'+val else: return '' elif Type == 'int': ret...
def temperature_to_heat_flux(temperature: float, ambient_temperature: float = 293.15): """Function returns hot surface heat flux for a given temperature. :param temperature: [K] emitter temperature. :param ambient_temperature: [K] ambient/receiver temperature, 20 deg.C by default. :return heat_flux: [K...
def is_float(value): """Checks if `value` is a float. Args: value (mixed): Value to check. Returns: bool: Whether `value` is a float. Example: >>> is_float(1.0) True >>> is_float(1) False .. versionadded:: 2.0.0 """ return isinstance(value...
def refine_func_map(fm): """Returns a mapping of opcode to my internal list of functions.""" times = 0 while times < 20: times += 1 for fi in fm.keys(): poss = fm[fi] if len(poss) == 1: [to_kill] = poss for fo in fm.keys(): if to_kill in fm[fo] and len(fm[fo]) != 1: ...
def calc_increases(depths): """ calculate the increases """ return sum([1 for x, y in zip(depths, depths[1:]) if y > x])
def escape_to_safe_json(x): """Because XSLT has limited replacement functions, it is done here in python first""" return x.replace('\\', '\\\\').replace('"', '\\"').replace('\r', '\\r').replace('\n', '\\n')
def idx_lst_from_line(line): """ Build a list of indices from a block of tests """ idxs = [] for string in line.strip().split(','): if string.isdigit(): idxs.append(int(string)) elif '-' in line: [idx_begin, idx_end] = string.split('-') idxs.extend(li...
def poly1d(x,coefs): """Evaluate a polynomial in one variable. """ y = 0. for coef in coefs[-1::-1]: y = y*x + coef return y
def filter(dicts, filters): """Returns a subset of the given entries in dicts (a list of dictionaries) for which the fields specified in the filters dictionary have the corresponding values. """ toKeep = [] for d in dicts: isSatisfied = True for f in filters: if f not in d: isSatisfied = False ...
def fileGroupName(filePath): """ Get the group file name. foo.0080 would return foo """ return filePath.split('.')[0]
def valideFloat(values, length): """This function takes a single float, or int or a list of them and a requested length and returns a list of float of length 1 or length.""" if type(values) == float: return [values] elif type(values) == int: return [float(values)] else: if le...
def solve_quadratic_equation(a, b, c, direction='right'): """Solves the quadratic equation of given a, b and c factor. The calculation side can be specified using the "direction" variable (right or left). """ s = b ** 2 - 4 * a * c # Ignore very small negative numbers (to avoid the following negat...
def param_change(name): """ Method to accomodate for param change. https://oceanobservatories.org/renaming-data-stream-parameters/ """ if name == 'pressure_depth': return 'pressure' else: return name
def parseDeviceName(deviceName): """ Parse the device name, which is of the format card#. Parameters: deviceName -- DRM device name to parse """ return deviceName[4:]
def validate_pattern(pattern): """Validate a pattern suppied by the user Parameters ---------- pattern : str Returns ------- tuple bool True/False True if OK, False if error str Returned value or Error """ pattern = pattern.strip() if n...
def canonicalize_power_tuple(power_tuple): """ Entries in `Polynomial` are stored as (exponent tuple): coefficient, where the exponent tuple is required not to have any trailing zeroes. This takes a tuple and rewrites it into that form. """ while len(power_tuple) > 0 and power_tuple[-1] == 0: ...
def find_torrent(info_hash, torrent_list): """Find torrent file in given list of Torrent classes @param info_hash: info hash of torrent @type info_hash: str @param torrent_list: list of L{Torrent} instances (see L{RTorrent.get_torrents}) @type torrent_list: list @return: L{Torrent} instance, ...
def get_alphabet(number): """ Helper function to figure out alphabet of a particular number Remember: * ASCII for lower case 'a' = 97 * chr(num) returns ASCII character for a number e.g. chr(65) ==> 'A' """ return chr(number + 96)
def find_substring(string: str, substring: str) -> int: """ Find substring in a larger string. """ i_str: int = 0 l_str: int = len(string) l_sub: int = len(substring) while i_str <= l_str - l_sub: index = 0 while index < l_sub and string[index + i_str] == substring[index]: ...
def model_first(x, k, y0, y1): """ One-compartment first-order exponential decay model :param x: float time :param k: float rate constant :param y0: float initial value :param y1: float plateau value :return: value at time point """ import math return y0 + (y1 - y0) * (...
def from_hex(value): """Converts RGB tuple to hex string""" color_str = value.lstrip('#') if len(color_str) != 6: raise ValueError('Invalid hex color: {}'.format(value)) for digit in color_str: if digit.upper() not in '0123456789ABCDEF': raise ValueError('Invalid hex color: {...
def get_offer_based_on_quantity(offer_list, quantity): """Fetch specific offer based on offer quantity :param offer_list: List :param quantity: Integer :rtype: Dictionary """ for offer in offer_list: if offer["quantity"] == quantity: return offer
def _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list): """ Constructs a top-down dynamic programming solution for the rod-cutting problem via memoization. Runtime: O(n^2) Arguments -------- n: int, the length of the rod prices: list, the prices for each piece o...
def new_check_knot_vector(degree=0, knot_vector=(), control_points_size=0, tol=0.001): """ Checks if the input knot vector follows the mathematical rules. """ if not knot_vector: raise ValueError("Input knot vector cannot be empty") # Check the formula; m = p + n + 1 if len(knot_vecto...
def frequency(word, histogram): """Return the frequency of that word in the whole dictogram (num_words/total_words).""" return histogram.get(word) / sum(histogram.values())
def divide_toward_zero(x, y): """Divides `x` by `y`, rounding the result towards zero. The division is performed without any floating point calculations. For exmaple: divide_toward_zero(2, 2) == 1 divide_toward_zero(1, 2) == 0 divide_toward_zero(0, 2) == 0 divide_toward_ze...
def _mid_pivot(low, high, array): """Return 'median of three' values.""" if (high - low) % 2 == 0: mid = low + (high - low) // 2 - 1 else: mid = low + (high - low) // 2 if (array[mid] <= array[low] <= array[high - 1]) or ( array[high - 1] <= array[low] <= array[mid] ): ...
def get_max_length(list_): """ Computes the longest element in a given list. Parameters ---------- list_: list A generic list of strings. Returns ------- int The longest element in the list. """ length_elements = [len(element) for element in list_] return m...
def datapath_id(a): """ Convert OpenFlow Datapath ID to human format Args: a: DPID in "8s" format Returns: DPID in human format """ string = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" if isinstance(a, bytes): a = a.decode("latin") dpid = string % (ord(a[0]), or...
def get_digits(number): """ :return: quantity of digits from the number """ count = 0 while number > 0: number = number // 10 count += 1 return count
def total_energy_ejected(t): """ Thermal and kinetic energy released by each type of SN up to the time t after the explosion where tc is the characteristic cooling time of the shell sorrounding the remnant (53000 yrs) from Ferrini & Poggiantti, 1993, ApJ, 410, 44F """ if t <= 0: return ...
def create_dummy_sink(Report_Dealer_Index,Contra_Party_Index): """transform Report_Dealer_Index that are 0 for OLD_Dc_v4""" if str(Report_Dealer_Index) == '0': return 'D' + str(Contra_Party_Index) else: return str(Report_Dealer_Index)
def manhattan(p1, p2): """ @param p1 : a tuple with the coords of a position @param p2 : another tuple with the coords of another position Return manhattan distance between 2 points. """ return abs( p1[0] - p2[0]) + abs(p1[1] - p2[1] )
def filer_elements(elements, element_filter): """Filter elements. Ex.: If filtered on elements [' '], ['a', ' ', 'c'] becomes ['a', 'c'] """ return [element for element in elements if element not in element_filter]
def error(name, function, *args, **kwargs): """ Error handling helping function :param name: Tuple list of the excepting errors :param function: Name of the functions :param args: Normals arguments of the named functions :param kwargs: Keyword arguments """ try: return function(*ar...
def hhmm_to_seconds(time_value: str) -> int: """ This function takes the argument of time_value with the format d/m/y T hh:mm with the T being a separator between date and time. The function extracts the integer values of the hours and minutes, multiplies them by 3600 and 60 respectively, and r...
def one_sided_forward_FD_at(i, h, u, derivative=1, order=1): """ computes the n_th one-sided forward finite difference derivative at x_i on the basis of u_i. Coefficients from https://en.wikipedia.org/wiki/Finite_difference_coefficient d^n u/dn (x_i)= a*u_i + b*u_i+1 + c*u_i+2 + ... :para...
def mySqrt(x): """ :type x: int :rtype: int """ return int(x ** 0.5)
def _applescript_quote(string): """ Creates a double-quoted string for AppleScript :param string: A unicode string to quote :return: A unicode string quoted for AppleScript """ return '"' + string.replace('"', '\\"') + '"'
def parseAnswerTxt(answer, index, data): """ parseAnswerCname(answer, data): Parse a Cname answer. answer - The answer body (no headers) data - The entire response packet """ retval = {} retval["sanity"] = [] # # First byte is the character count, but we already have the exact answer # thanks to rdlengt...
def commits_text(commits): """Returns text in the form 'X commits' or '1 commit'""" plural = "s" if len(commits) != 1 else "" return "{} commit{}".format(len(commits), plural)
def generate_filename(extension): """ Returns sample file from the samples/ folder Arguments: extension - extension of the req doc """ return f'samples/sample_{extension}.{extension}'
def count_positives_sum_negatives2(arr): """ More space efficient, but not as concise as above """ if not arr: return arr count = 0 total = 0 for num in arr: if num > 0: count += 1 else: total += num return [count, total]
def minimumSwaps(arr): """ Args: arr (list): list of numbers. Returns: int: min number of swaps""" i = 0 count = 0 # since we know exact place in arr for each element # we could just check each one and swap it to right position if thats # required while i < len(arr):...
def check_valid(sig, args, kwargs): """ Like ``is_valid_args`` for the given signature spec""" num_pos_only, func, keyword_exclude, sigspec = sig if len(args) < num_pos_only: return False if keyword_exclude: kwargs = dict(kwargs) for item in keyword_exclude: kwargs.po...
def sparseFeature(feat, feat_num, embed_dim=4): """ create dictionary for sparse feature :param feat: feature name :param feat_num: the total number of sparse features that do not repeat :param embed_dim: embedding dimension :return: """ return {'feat_name': feat, 'feat_num': feat_num, '...
def efficientnet_params(model_name): """ Map EfficientNet model name to parameter coefficients. """ params_dict = { # Coefficients: width,depth,res,dropout 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, 0.3), 'efficientnet-...
def clear_start(line: str, chars: list): """ Clears line's beginning from unwanted chars. Parameters ---------- line : str Line to be cleared. chars : list of chars Unwanted chars. Returns ------- line : str Given line, cleared from unwanted chars. """ ...
def is_not_empty(value, ignore_whitespace=False): """Test values for being is not empty string or None. If the ignore whitespace flag is True any string that only contains whitespace characters is also considered empty. Parameters ---------- value: scalar Scalar value that is tested for...
def FormatClassToJava(input) : """ Transofmr a typical xml format class into java format @param input : the input class name """ return "L" + input.replace(".", "/") + ";"
def get_damage_resistances(monster_data) -> str: """Returns a string list of damage types to which the monster is resistant. """ try: damage_resistances = monster_data["damage_resistances"][0] except (KeyError, IndexError): damage_resistances = "" return damage_resistances
def primes(n): """Copied from https://stackoverflow.com/a/16996439/5393381 (author: Daniel Fischer)""" primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) n //= d d += 1 if n > 1: primfac.append(n) return primfac
def extract_hour(date_time): """Extract the hour in a format to use for display: :param date_time: the timestamp from EPA UV readings """ split_date_time = date_time.split() hour = split_date_time[1] suffix = split_date_time[2] if hour[0] == '0': hour = hour[1] return '\n'.join([...
def json_path(path, data): """Extract property by path""" fragments = path.split(".") src = data for p in fragments: src = src.get(p, {}) return src
def replace_underscore(value): """ convert string with underscore to space :param value: :return: """ return value.replace("_", " ")
def func_2(x: float, c: float, d: float) -> float: """ Test function 2. """ return x + c + d
def to_full_html_document(html_template_chunk: str) -> str: """ Convert a HTML chunk into a full, valid html document. """ result = "" result += "<!DOCTYPE html>\n" result += "<html>\n" result += "<body>\n" result += html_template_chunk + '\n' result += "</body>\n" result += "</h...
def build_aggregation(facet_name, facet_options, min_doc_count=0): """Specify an elasticsearch aggregation from schema facet configuration. """ exclude = [] if facet_name == 'type': field = 'embedded.@type' exclude = ['Item'] elif facet_name.startswith('audit'): field = facet...
def sum_contrast(value, target, reference): """Convenience function for creating sum-coded contrasts. :param value: value to convert into 1, 0, or -1 :param target: target (will be recoded to 1) :param reference: reference (will be recoded to -1) :return: recoded value """ if value == targe...
def parse_rank(rank): """ Ensure rank is 1-5 and invert to match priorities """ rank = int(rank) if rank >= 1 and rank <= 5: return int(6 - rank) else: raise RuntimeError(":x: Invalid rank `"+str(rank)+"`; rank should be 1-5")
def _in_use(path): """Checks if a Windows file is in use. When Windows is using an executable, it prevents other writers from modifying or deleting that executable. We can safely test for an in-use file by opening it in write mode and checking whether or not there was an error. Returns (bool): True if the...
def gcd(a, b): """Returns the greatest commod devisor of a and b""" if a < b: a, b = b, a while b > 0: a, b = b, a % b return a
def shp2geojson(layer): """Shapefile to Geojson conversion using mapshaper.""" cmd = 'mapshaper {layer}.shp'\ + ' -proj wgs84'\ + ' -o format=geojson precision=0.00000001'\ + ' {layer}.geojson' cmd = cmd.format(layer=layer) return cmd
def without_keys(d, keys): """Return dict without the given keys. __ https://stackoverflow.com/a/31434038/2402577 """ return {x: d[x] for x in d if x not in keys}
def num(s, filt=float): """Helper for numeric fields - we accept a string, convert it using filt, and will return an empty string if there is a ValueError converting """ if not s: return "" try: return filt(s) except ValueError: return ""
def value2safebyte(value): """Take boolean or integer value, convert to byte making sure it's not too large or reserved control char""" if isinstance(value, bool): if value: return b'1' return b'0' if not isinstance(value, int): raise RuntimeError('Input must be int or bo...
def _convert_line_to_tab_from_orifile(line): """ :param line: :return: >>> _convert_line_to_tab_from_orifile('''IMG_1468832894.185000000.jpg -75.622522 -40.654833 -172.350586 \ 657739.197431 6860690.284637 53.534337''') ['IMG_1468832894.185000000...
def cria_peca(s): """ Construtor peca. Recebe uma cadeia de caracteres correspondente ao identificador de um dos dois jogadores ('X' ou 'O') ou uma peca livre (' ') e devolve a peca correspondente. Caso algum dos seus argumentos nao seja valido, a funcao gera um erro com a mensagem 'cria_peca...
def _create_key_val_str(input_dict): """ Returns string of format {'key': val, 'key2': val2} Function is called recursively for nested dictionaries :param input_dict: dictionary to transform :return: (str) reformatted string """ def list_to_str(input_list): """ Convert all ...
def is_valid_user_request(newuser): """ helper to check required fields """ if "fullname" in newuser and "fullname" in newuser and "phone_number" in newuser and \ "email" in newuser and "password" in newuser: return True else: return False
def decomment_line(ln: str) -> str: """ cut off after % :param ln: :return: """ inquotes = False # do not remove inside double quotes for i, p in enumerate(list(ln)): if p == '"': if inquotes: inquotes = False else: inquo...
def do_secrets_conflict(a: dict, b: dict) -> bool: """Check whether secrets in two dicts returned by get_secrets() conflict. :return: True if secrets conflict, False otherwise. :rtype: bool """ for key in a: if key in b and a[key]["name"] != b[key]["name"]: return True ret...
def merge(arr): """ Time Complexity : O(nlogn) Auxiliary Space Complexity : O(n) """ arr.sort() updated_interval = [arr[0]] # Created new array to store all the merged interval current_index = 0 for intervals in arr[1:]: # For merging if intervals[0] <= updated...
def jaccard_similarity( set_a, set_b, element_to_weight=None, max_intersections=None): """Calculates Jaccard similarity, a measure of set overlap. Args: set_a: First set. set_b: Second set. element_to_weight: Optional, a dict of set elements to numeric weights. This ...
def calc_results_progress( number_of_users: int, number_of_users_required: int, cum_number_of_users: int, number_of_tasks: int, number_of_results: int, ) -> int: """ for each project the progress is calculated not all results are considered when calculating the progress if the requir...
def analog_linear2_ramp(ramp_data, start_time, end_time, value_final, time_subarray): """Use this when you want a discontinuous jump at the end of the linear ramp.""" value_initial = ramp_data["value"] value_final2 = ramp_data["value_final"] interp = (time_subarray - start_time)/(...
def _CalculateFrameTimes(events_per_frame, event_data_func): """Given a list of events per frame and a function to extract event time data, returns a list of frame times.""" times_per_frame = [] for event_list in events_per_frame: event_times = [event_data_func(event) for event in event_list] times_p...
def replace_format(string, **fmt): """Similar to `string.format(**fmt)` but ignores unknown `{key}`s.""" for k, v in fmt.items(): string = string.replace("{" + k + "}", v) return string
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category...
def in_units(qty, units): """ Convert quantity to specified `units` and return numerical value. If `qty` is `None`, then return `None`, regardless of `units`. .. note:: If `qty` is not `None`, then the following two expressions are equivalent: 1. ``chemtk.units.in_units(qt...
def generate_batches(batch_size, features, labels): """ Create batches of features and labels :param batch_size: The batch size :param features: List of features :param labels: List of labels :return: Batches of (Features, Labels) """ assert len(features) == len(labels) outout_batches = [] sample_size = len(...
def to_two_bytes(integer): """ Breaks an integer into two 7 bit bytes. """ if integer > 32767: raise ValueError("Can't handle values bigger than 32767 (max for 2 bits)") return bytearray([integer % 128, integer >> 7])
def print_number(number): """ print a ' every 3 number starting from the left (e.g 23999 -> 23'999)""" len_3 = round(len(str(number)) / 3.) j = 0 number = str(number) for i in range(1, len_3 + 1): k = i * 3 + j number = number[:-k] + '\'' + number[-k:] j += 1 # remove '...
def action_key(mod_name, func_name): """ Generate a key uniquely identify the action defined by the module and function. :param mod_name: the module's full package name :param func_name: the function name :return: the key for identifying the action. """ try: idx = mod_name.rindex('....