content
stringlengths
42
6.51k
def splitdigits(i, base=10): """ >>> splitdigits(0) [] >>> splitdigits(13) [1, 3] """ digits = [] while i: digits.append(i % base) i //= base digits.reverse() return digits
def preprocess_text_values(rows, fields): """ >>> rows = [ ... {"title": "Awesome title", "long_title": "Long text", "dating_period": 19}, ... {"title": "Title", "long_title": "Looong text", "dating_period": 17} ... ] >>> actual = preprocess_text_values(rows, ("title",)) >>> expected...
def is_subclass_at_all(cls, class_info): """Return whether ``cls`` is a subclass of ``class_info``. Even if ``cls`` is not a class, don't crash. Return False instead. """ try: return issubclass(cls, class_info) except TypeError: return False
def palindrome(value: str) -> bool: """ This function determines if a word or phrase is a palindrome :param value: A string :return: A boolean """ value = "".join(value.split()).lower() if len(value) <= 1: return True if value[0] != value[-1]: return False return pali...
def compare(gt, out): """ function that compares two lists of edges ex: ground truth list and list of discovered edges and returns precision and recall """ correct = list(set(gt) & set(out)) # correctly identified addit = list(set(out) - set(correct)) # additionally identified if len(out) == 0: precision = 0 ...
def vertices_from_bbox(box_min_x, box_min_y, box_min_z, box_max_x, box_max_y, box_max_z): """ Return a tuple with 1 - a list with 8 tuples representing the vertices of the box that the given bounding box min and max values represent 2 - the faces of that box """ v0 = (...
def check_password(password, guess): """Takes two string variables: the password and the guess. Returns true if they match, or false if they do not.""" return True if password == guess else False
def ensure_not_removed_orphaned(package_control_settings): """ Save the default user value for `remove_orphaned` on `_remove_orphaned`, so it can be restored later. """ print( "[2_bootstrap.py] ensure_not_removed_orphaned, finishing Package Control Uninstallation, setting remove_orphaned..."...
def pascal_triangle(num_rows): """ Calculate the pascal triangle for a given number of rows. """ def get_elem(arr, idx, default): if idx < 0 or idx >= len(arr): return default else: return arr[idx] def generate_columns(previous_row, num_columns): for ...
def V_invert_harmonic_1dof(x, par): """ Parameters ---------- x : TYPE independent variable value of the potential energy function. par : TYPE parameters of the potential energy function. Returns ------- V : TYPE potential energy of the 1 DOF ...
def is_ip(value): """ Check if a value is valid ip :param value: :return: """ parts = value.split(".") if len(parts) != 4: return False for item in parts: if not 0 <= int(item) <= 255: return False return True
def BlendColour(fg, bg, alpha): """ Blends the two colour component `fg` and `bg` into one colour component, adding an optional alpha channel. :param `fg`: the first colour component; :param `bg`: the second colour component; :param `alpha`: an optional transparency value. """ resu...
def dec_to_hex(decimal: int) -> str: """ Converts a decimal integer to a hexadecimal string :param decimal: An integer :return: A hexadecimal string """ remainders = [] while decimal != 0: remainders.append(decimal % 16) decimal //= 16 base16_str = "" for x in rever...
def underscore_to_camelcase(param: str) -> str: """ Converts a parameter written in underscore notation (i.e. `slack_id`) and converts it to camel case (i.e. `slackId`). This is required for the conversion from the standard Pythonic underscore notation to the GraphQL camel case. Args: param...
def serialize_graftpoints(graftpoints): """Convert a dictionary of grafts into string The graft dictionary is: <commit sha1>: [<parent sha1>*] Each line is formatted as: <commit sha1> <parent sha1> [<parent sha1>]* https://git.wiki.kernel.org/index.php/GraftPoint """ graft_li...
def reverse_truncatechars(string, start): """Inverse of truncate chars. Instead of the first x characters, excludes the first nth characters. """ return string[start:]
def scorer(predictions, gts, k=3): """ For model evaluation on InsuranceQA datset. Returns score@k. """ score=0 total=0 for gt, prediction in zip(gts, predictions): if bool(set(gt) & set(prediction[:k])): score+=1 total+=1 return score/total
def key_strip(key): """Cleanup whitespace found around a key @param key: A properties key @type key: str @return: Key without any uneeded whitespace @rtype: str """ newkey = key.rstrip() # If line now end in \ we put back the whitespace that was escaped if newkey[-1:] == "\\": ...
def replace_subset(lo, hi, arr, new_values, unique_resort=False): """ Replace a subset of a sorted arr with new_values. Can also ensure the resulting outcome is unique and sorted with the unique_resort option. :param lo: :param hi: :param arr: :param new_values: :param unique_resort: ...
def find_set_points(minmax_terms, var_name): """Return a list of sorted set points. Return an empty list there are variables but all coefficients are 0, or there are simply no variables. """ pts = set() for term in minmax_terms: left, right = term.left_right_nums() left_half, right_h...
def coordonnees (matrix): """Retourne les coordonnees d'affection optimal""" coordonnees = list() for y, y_elt in enumerate(matrix): for x, x_elt in enumerate(y_elt): if x_elt == 'E': coordonnees.append((y, x)) return coordonnees
def get_status_color(status): """Return (markup) color for test result status.""" colormap = {"passed": {"green": True, "bold": True}, "failed": {"red": True, "bold": True}, "blocked": {"blue": True, "bold": True}, "skipped": {"yellow": True, "bold": True}} r...
def unique_columns_list(nested_lists): """ Flatten the nested list (two levels) and leave unique elements. Parameters ---------- nested_lists : list A list which contains sublists. Returns ------- list A list with unique elements from sublists. """ return list(s...
def R11(As, RmS, FmGM): """ R11 Determining the minimum length of engagement meffmin (Sec 5.5.5) --- As : Tensile stress area of the bolt RmS : Tensile stress of the bolt FmGM : """ # Tensile strength FmS = RmS * As # #if FmS > FmGM : # print('FmS [{}...
def cal_iou(val1, val2): """ cal crop IOU :param val1: [x11,y11,x12,y12] :param val2: [x21,y21,x22,y22] :return type: float """ x11, y11, x12, y12 = val1 x21, y21, x22, y22 = val2 leftX = max(x11, x21) topY = max(y11, y21) rightX = min(x12, x22) bottomY = min(y12, y22)...
def absl_to_cpp(level): """Converts an absl log level to a cpp log level. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in Abseil C++. """ if not isinstance(level, int): raise TypeError('Ex...
def remove_blank_wrap(value, context): """ Remove blank and text wrap in the value. """ return "".join(value.split())
def colorfix(color): """fixes some errors associated with qPixmaps and PIL Image data.""" #14.01.03-16.39: added function to convert RGBA<->BGRA color2=(color[2],color[1],color[0],color[3]) return color2
def polygonal_number(n, k): """ Returns the kth n-gonal number P(n, k) given by the general formula: P(n, k) = [(n - 2)k^2 - (k - 4)n] / 2 """ return int(((n - 2) * k ** 2 - (n - 4) * k) / (2))
def gmof(x, sigma): """ Implementation of robust Geman-McClure function """ x_squared = x ** 2 sigma_squared = sigma ** 2 return (sigma_squared * x_squared) / (sigma_squared + x_squared)
def get_snap_statuses(r): """ Description: Helper function for pandas apply() function. Retrieves the associatedInterpretationSnapshots from the provisionalVariant column and parses out the statuses in a format expected in the vciStatus column. Args: r (pandas row): A row in a panda...
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ total, stop = 1, n - k while n > stop: total, n = total * n, n - 1 retur...
def check_for_factor(base, factor): """ This function should test if the factor is a factor of base. Factors are numbers you can multiply together to get another number. Return true if it is a factor or false if it is not. :param base: :param factor: :return: """ retur...
def metric_key(pool_name, metric_name): """Helper method to construct the admission controller metric keys""" return "admission-controller.%s.%s" % (metric_name, pool_name)
def _copy_list(seq): """Recursively copy a list of lists""" def copy_items(seq): for item in seq: if isinstance(item, list): yield list(copy_items(item)) else: yield item return list(copy_items(seq))
def parse_prefix(prefix): """ Take the prefix of an IRC message and split it up into its main parts as defined by :rfc:`2812#section-2.3.1`, section 2.3.1 which shows it consisting of a server name or nick name, the user, and the host. This function returns a 3-part tuple in the form of ``(nick, user,...
def step(step): """ checks that a *step* value is valid """ if step.lower() not in ("raw", "flat", "compile"): raise ValueError('step must be one of "raw" or "flat"') return step.lower()
def binom(n, k): """Computes the binomial coefficient of n and k. Taken from <https://en.wikipedia.org/wiki/Binomial_coefficient>.""" if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 k = min(k, n - k) # take advantage of symmetry c = 1 for i in range(k): c ...
def hex_to_rgb(value): """ Calculates rgb values from a hex color code. :param (string) value: Hex color string :rtype (tuple) (r_value, g_value, b_value): tuple of rgb values """ value = value.lstrip('#') hex_total_length = len(value) rgb_section_length = hex_total_length // 3 ret...
def Dic_Test_Empty_Dic(indic): """ check if indic is a (nested) empty dictionary. """ if indic.keys()!=[]: for key,keydata in indic.items(): if isinstance(keydata,dict): if keydata=={}: pass else: return Dic_Test...
def lt(value, arg): """Returns a boolean of whether the value is less than the argument.""" return value < int(arg)
def count(token: str, txt: str)-> int: """Count the token in the txt.""" return txt.count(token)
def check_types(expression, factory_attrs, job_attrs): """Validates the types of match_attrs in a match_expr. Args: code (str): Code to validate. Returns: str: None if code is valid. Error message if the code is invalid. """ # Mock job and glidein["attrs"] dictionaries default...
def _bool2str(bool_list): """ turns a list of booleans into a string :param bool_list: ex: '[False True False False True]' :return: '01001' """ return ''.join(['1' if x else '0' for x in bool_list])
def is_source_directory(src_count, files_count): """ Return True is this resource is a source directory with at least over 90% of source code files at full depth. """ return src_count / files_count >= 0.9
def iso_string_to_sql_utcdatetime_pythonformat_sqlite(x: str) -> str: """ Provides SQLite SQL to convert a column to a ``DATETIME`` in UTC, in a string format that matches a common Python format. The argument ``x`` is the SQL expression to be converted (such as a column name). Output like .. c...
def temp_get_users_with_permission_model( self, include_superusers=True, backend="django.contrib.auth.backends.ModelBackend", ): """Used to test that swapping the model method works""" # Search string: XYZ return ()
def format_datetime(value, datetime_format='medium'): """ Return a formatted DateTime value. :param value: input value to format :param datetime_format: the desired format :return: the formatted DateTime value """ if value: if datetime_format != 'medium': return str(value...
def is_prerelease(version_str): """ Checks if the given version_str represents a prerelease version. """ return any([c.isalpha() for c in version_str])
def verse(bottle): """Sing a verse""" bot1 = 'bottles' if bottle > 1 else 'bottle' bot2 = 'bottles' if bottle - 1 != 1 else 'bottle' next_bottle = bottle - 1 if bottle != 1 else 'No more' return '\n'.join([ f'{bottle} {bot1} of beer on the wall,', f'{bottle} {bot1} of beer,...
def filter_dicts_by_keys(iterable, keys, all_keys=False): """Returns a 'list' of 'dict' whose dictionaries contain at least one of the specified `keys`.""" def where(d): if all_keys: return all(k in d for k in keys) else: return any(k in d for k in keys) return [x...
def is_volume(name): """Return True if volume""" return name.startswith("v_")
def _popdefault(dict, key, default=None): """ Pops the given key from the dictionary and returns its value (or default). """ if key in dict: return dict.pop(key) return default
def _is_iterable(obj): """ Check if object is iterable """ try: _ = iter(obj) except Exception: # pylint: disable=broad-except return False return True
def charset_to_int(s, charset): """ Turn a string into a non-negative integer. """ if not isinstance(s, (str)): raise ValueError("s must be a string.") if (set(s) - set(charset)): raise ValueError("s has chars that aren't in the charset.") output = 0 for char in s: output...
def to_deg(value, loc): """convert decimal coordinates into degrees, munutes and seconds tuple Keyword arguments: value is float gps-value, loc is direction list ["S", "N"] or ["W", "E"] return: tuple like (25, 13, 48.343 ,'N') """ if value < 0: loc_value = loc[0] elif value > 0: ...
def get_enabled_tests(config): """ Build a set containing all tests defined in the config file. Each entry of the set is in the format {test-suite}/{test-module}::{test-function}, e.g. 'cfn-init/test_cfn_init.py::test_replace_compute_on_failure' """ enabled_test_suites = config.get("test-suites...
def _merge_relations(fwd_relations, rvs_relations): """ Tweak of DRF's _merge_relationships to be more readable """ relations = {} relations.update(fwd_relations) relations.update(rvs_relations) return relations
def get_custom_mode_name(system,custom_mode): """Returns meaningful name for system custom mode""" return "%d" % custom_mode
def row_squash(data, ruler=3): """ Small ruler will perform more better""" _rev = data[::-1] _rev_data = [] for i in range(0, len(_rev), int(ruler)): _rev_sub = _rev[i:i + int(ruler)] _rev_data.append(max(_rev_sub, key=_rev_sub.count)) return _rev_data[::-1]
def get_plain_text(text): """ clear \n and left space :param text: input text :type text str :return: str """ if not text or not isinstance(text, str): return "" return text.lstrip().replace("\n", "").replace("\r", "")
def create_ans2label(occurence): """Note that this will also create label2ans.pkl at the same time occurence: dict {answer -> whatever} name: prefix of the output file cache_root: str """ ans2label = {} label2ans = [] label = 0 for answer in occurence: label2ans.append(answe...
def append_info(info, new_info): """ :param info: :param new_info: :return: """ info.append(new_info) return info
def extend(*args): """shallow dictionary merge Args: a: dict to extend b: dict to apply to a Returns: new instance of the same type as _a_, with _a_ and _b_ merged. """ if not args: return {} first = args[0] rest = args[1:] out = type(first)(first) ...
def is_user_type_authorized(unauthorized_list, user_type): """Check user type authorization Method returns True if the user_type is in the unauthorized list """ if user_type in unauthorized_list: return True return False
def unmap(L,L2,mp): """ used in multiprove""" if mp == []: return L mx = max(mp) ## assert len(map) == len(L2),'len(mp) = %d, len(L2) = %d'%(len(map),len(L2)) assert mx < len(L),'max of map = %d, length of L = %d'%(mx,len(L)) for j in range(len(mp)): L[mp[j]] = L2[j] #expand resul...
def clamp_value(n, minimum, maximum): """ Clamp a value between a min and max :param n: :param minimum: :param maximum: :return: """ return max(minimum, min(n, maximum))
def is_leap(year): """Return True for leap years, False for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def is_binary_file(file_name): """ Tries to open file in text mode and read first 64 bytes. If it fails, we can be fairly certain, this is due to the file being binary encoded. Thanks Sehrii https://stackoverflow.com/a/51495076/949561 for the help. """ try: with open(file_name, 'tr') as ...
def offsetRect(rect, dx, dy): """Offset the rectangle by dx, dy.""" (xMin, yMin, xMax, yMax) = rect return xMin+dx, yMin+dy, xMax+dx, yMax+dy
def is_list_like(obj): """ This function checks if the given `obj` is a list-like (list, tuple, Series...) type or not. Parameters ---------- obj : object of any type which needs to be validated. Returns ------- Boolean: True or False depending on whether the input `obj` is...
def reverse_index(l: list, v): """ Find the index of the last occurrence of an element in a list. Parameters ---------- l: list The container of all elements v: object The element to be found Returns ------- int: The index of the last occurrence of `v` in `l...
def minimum_edit_distance(seq1,seq2): """Returns The Minimum Edit distance optimized for memory source:https://rosettacode.org/wiki/Levenshtein_distance """ if len(seq1) > len(seq2): seq1,seq2 = seq2,seq1 distances = range(len(seq1) + 1) for index2,char2 in enumerate(seq2): ...
def derivative(xy_data,npoints): """calculates the slope of xy data averaged of a number of points given by npoints xy_data = list of (x,y)-tuples """ derivative=[] for j in range (0,len(xy_data)-npoints): sumx=0; sumy=0 for i in range(j,j+npoints): sumx+=xy_data[i][0]; sumy+=xy...
def ip4_subnet_c(ip): """returns C subnet of ipv4 address e.g.: 1.2.3.4 -> 1.2.3.0""" return ".".join(ip.split(".")[:-1]) + ".0"
def value_to_bytes_big_endian(value: int, size: int): """ Pack integer value into bytes """ byte_numbers = reversed(range(size)) return bytes((value >> (x * 8)) & 0xff for x in byte_numbers)
def _key(key): """convert to a key.""" return [ord(x) for x in key]
def normalize_cern_person_id(value): """Normalize the CERN person ID. We always want a string or None if it's missing. """ if value is None: return None elif isinstance(value, int): return str(value) elif not value: return None else: return value
def is_equal_or_parent_of(page1, page2): """ Determines whether a given page is equal to or the parent of another page. This is especially handy when generating the navigation. The following example adds a CSS class ``current`` to the current main navigation entry:: {% for page in navigation %}...
def validate(v): """ """ try: v = int(v) except: v = 0 return v
def build_coevolution_matrix_filepath( input_filepath, output_dir="./", method=None, alphabet=None, parameter=None ): """ Build filepath from input filename, output dir, and list of suffixes input_filepath: filepath to be used for generating the output filepath. The path and the final suffi...
def copy(tupleo): """ clear(...) method of tupleo.tuple instance T.copy(tupleo) -> Tuple -- a shallow copy of tuple, tupleo """ if type(tupleo) != tuple: raise TypeError("{} is not tuple".format(tupleo)) convertlist = list(tupleo) return tuple(convertlist.copy())
def valid_git_ref (ref_name): """Return True iff the given ref name is a valid git ref name.""" # The following is a reimplementation of the git check-ref-format # command. The rules were derived from the git check-ref-format(1) # manual page. This code should be replaced by a call to # check_refn...
def md5sum(s): """MD5s the given string of data and returns the hexdigest. If you want the md5 of a file, call md5sum(open(fname).read())""" import hashlib return hashlib.md5(s).hexdigest().lower()
def bit_iterator(bit_length): """Get an iterator for the bits in left to right order""" return range(bit_length-1, -1, -1)
def splitRef(ref): """splits an autosar url string into an array""" if isinstance(ref,str): if ref[0]=='/': return ref[1:].split('/') else: return ref.split('/') return None
def pol_eval(p, x) -> float: """ evaluate polynomial from coefficients p : p[0] + p[1]*x + p[2]*x**2 + ... """ if not isinstance(p,(list,tuple)): p = [p] y = p[-1] for i in range(len(p)-2,-1,-1): y = p[i] + y*x return y
def underlyingFunction(thing): """Original function underlying a distribution wrapper.""" func = getattr(thing, '__wrapped__', thing) return getattr(func, '__func__', func)
def is_prime(n): """ from https://stackoverflow.com/questions/15285534/isprime-function-for-python-language """ if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if ...
def wrap_with(text, tag): """ Inserts tags (as format string) into string at line breaks""" paragraphs = text.split("\n") html_list = list(map(lambda x: tag.format(x), paragraphs)) return "\n".join(html_list)
def dice_roll(arg: str): """ Dice roll as number of rolls (eg 6) or as num and sides (2x6)""" num, sides = 1, 6 if arg.count("x") > 1: return None if "x" in arg: num, sides = arg.split("x") else: num = arg try: num = int(num) sides = int(sides) exce...
def _read_timestamp(file): """Get start and end time from timestamp csv file.""" try: with open(file, 'r') as f: rows = f.readlines() starttime, endtime = float(rows[0].split(",")[0]), float(rows[-1].split(",")[0]) starttime, endtime = starttime / (10**3), endtime / (10**...
def list_repeat(seq_list, n): """ input: [seq1, seq2], n=2 output: [seq1, seq1, seq2, seq2] """ res_list = [] for s in seq_list: res_list += [s.copy() for _ in range(n)] return res_list
def iou(bbox1, bbox2): """ Calculates the intersection-over-union of two bounding boxes. Args: bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. Returns: int: intersection-over-onion of bbox1, bbox2 "...
def quote(value): """Quote a value unambigously w.r.t. its data type. The result can be used during import into a relational database. :param value: The value to transform. :return: ``'null'`` if ``value`` is ``None``, ``'true'`` if it is ``True``, ``'false' if it is ``False``. For numeric v...
def _extract_augmentor_param(augmentor_yaml): """ Takes augmentor yaml dictionary and determines name and parameters Args: augmentor_yaml: Parameter dictionary containing augmentor data. """ if isinstance(augmentor_yaml, str): augmentor_name = augmentor_yaml augmentor_param = None...
def get_target_dimension_order(out_dims, direction_to_names): """ Takes in an iterable of directions ('x', 'y', 'z', or '*') and a dictionary mapping those directions to a list of names corresponding to those directions. Returns a list of names in the same order as in out_dims, preserving the order ...
def is_int(v): """ Check for valid integer >>> is_int(10) True >>> is_int("10") True >>> is_int("Ten") False >>> is_int(None) False """ try: v = int(v) except ValueError: return False except TypeError: return False return True
def _return_num_channels(rgb, gray): """ ``rgb`` and ``gray`` must both be boolean values. Returns number of channels (1 or 3) based on the above values. Consider the table below with keys rgb | gray | returned value (no. of channels) --------|---------...
def complete_matrix(X): """ input: X: sparse matrix output: Y: same matrix with zeros completed """ Y={} row=0 column=0 for k in X.keys(): row=max(row,k[0]) column=max(column,k[1]) for i in range(1,row+1): for j in range(1,column+1): if (i,j) in X....