content
stringlengths
42
6.51k
def create_crumb(title, url=None): """ Helper function """ crumb = """<span class="breadcrumb-arrow">""" \ """&gt;""" \ """</span>""" if url: crumb = "%s<a href='%s'>%s</a>" % (crumb, url, title) else: crumb = "%s&nbsp;&nbsp;%s" % (crumb, title) retur...
def fixed_implies_implicant(fixed,implicant): """Returns True if and only if the (possibly partial) state "fixed" implies the implicant. Parameters ---------- fixed : partial state dictionary State (or partial state) representing fixed variable states. implicant : partial state dictiona...
def recursion_power(number: int, exp: int, result: int = 1) -> int: """ Perpangkatan dengan metode rekursif rumus matematika: number^exp >>> recursion_power(2, 5) 32 >>> recursion_power(100, 0) 1 >>> recursion_power(0, 100) 0 >>> recursion_power(1, 100) 1 """ if exp <...
def vlan_range_to_list(vlans): """Converts single VLAN or range of VLANs into a list Example: Input (vlans): 2-4,8,10,12-14 OR 3, OR 2,5,10 Returns: [2,3,4,8,10,12,13,14] OR [3] or [2,5,10] Args: vlans (str): User input parameter of a VLAN or range of VLANs Returns: l...
def bool_to_str(value): """Return 'true' for True, 'false' for False, original value otherwise.""" if value is True: return "true" if value is False: return "false" return value
def image_space_to_region(x, y, x1, y1, x2, y2): """ Relative coords to Region (screen) space """ w = (x2 - x1) h = (y2 - y1) sc = w return x1 + (x + 0.5) * sc, (y1 + y2) * 0.5 + y * sc
def addNodeFront(node, head, tail) : """ Given a node and the head pointer of a linked list, adds the node before the linked list head and returns the head of the list """ if head is None : head = node tail = node return (head, tail) head.prev = node node.next = head head = n...
def get_max_profit1(stock_prices): """ - Time: O(n^2) - Space: O(1) * n is len(stock_prices) """ length = len(stock_prices) assert length > 1, 'Getting a profit requires at least 2 prices' profit = stock_prices[1] - stock_prices[0] length = len(stock_prices) for i in range(leng...
def third_part(txt): """Third logical part for password.""" m, d, y = txt.split('/') return f'{y.zfill(4)}{m.zfill(2)}{d.zfill(2)}'
def cubicinout(x): """Return the value at x of the 'cubic in out' easing function between 0 and 1.""" if x < 0.5: return 4 * x**3 else: return 1/2 * ((2*x - 2)**3 + 2)
def flatten(json_response): """ flattens the json response received from graphQL, and returns the list of topics :param json_response: response of the format mentioned in graph_query :return: list of topics """ topics = [] if json_response.get("data", None) is not None: # print(json_...
def build_query_id_to_partition(query_ids, sizes): """Partition a given list of query IDs. :param query_ids: an input array of query IDs. :param sizes: partion sizes :return: a dictionary that maps each query ID to its respective partition ID """ assert sum(sizes) == len(query_ids) ...
def removekey(d, key): """remove selected key from dict and return new dict""" r = dict(d) del r[key] return r
def majority(*args): """ Evaluate majority function on arbitrary number of inputs. :param args: tuple of Boolean inputs :return: [bool] value of majority function """ return sum(args) > len(args)/2
def nth_fibonacci_bruteforce(n: int) -> int: """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for i in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1
def substrings(a, b, n): """Return substrings of length n in both a and b""" def substring_parse(string, n): length = len(string) substrings = set() for i in range(length - n + 1): substrings.add(string[i:i+n]) return substrings # parsing a into substrings a...
def findCameraInArchive(camArchives, cameraID): """Find the entries in the camera archive directories for the given camera Args: camArchives (list): Result of getHpwrenCameraArchives() above cameraID (str): ID of camera to fetch images from Returns: List of archive dirs that matchi...
def url_origin(url: str) -> str: """ Return the protocol & domain-name (without path) """ parts = url.split('/') return '/'.join(parts[0:3])
def parse_host_and_port(raw): """Returns a tuple comprising hostname and port number from raw text""" host_and_port = raw.split(':') if len(host_and_port) == 2: return host_and_port else: return raw, None
def getcommontype(action): """Get common type from action.""" return action if action == 'stock' else 'product'
def _get_resource_tag( resource_type, tag, runtime, chip, resource_id=None, ): """ Get resource tag by resource type. IMPORTANT: resource_id is optional to enable calling this method before the training resource has been created resource_tag will be incomplete (missing r...
def digits_in_base(number, base): """ Convert a number to a list of the digits it would have if written in base @base. For example: - (16, 2) -> [1, 6] as 1*10 + 6 = 16 - (44, 4) -> [2, 3, 0] as 2*4*4 + 3*4 + 0 = 44 """ if number == 0: return [ 0 ] digits = [] while nu...
def climate_validation(climate): """ Decide if the climate input is valid. Parameters: (str): A user's input to the climate input. Return: (str): A single valid string, such as "cold", "cool" or " Moderate" and so on. """ while climate != "1" and climate != "2" and ...
def binary(num, length=8): """ Format an integer to binary without the leading '0b' """ return format(num, '0{}b'.format(length))
def key_value_parser(path,keys,separator=' '): """ Key value parser for URL paths Uses a dictionary of keyname: callback to setup allowed parameters The callback will be executed to transform given value Examples: >>> list(sorted(key_value_parser('/invalidkey1/randomvalue/key1/0/key3/...
def cut_file_type(file_name): """ :param file_name: :return: """ file_name_parts = file_name.split(".") return file_name.replace("." + file_name_parts[len(file_name_parts)-1], "")
def numrev(n): """Reversing a Number.""" if type(n) == int: a = n rev = 0 while a > 0: rev = rev * 10 rev = rev + a % 10 a = a // 10 return rev else: raise Exception('Only positive integers allowed.')
def add_required_cargo_fields(toml_3p): """Add required fields for a Cargo.toml to be parsed by `cargo tree`.""" toml_3p["package"] = { "name": "chromium", "version": "1.0.0", } return toml_3p
def _s2cmi(m, nidx): """ Sparse to contiguous mapping inserter. >>> m1={3:0, 4:1, 7:2} >>> _s2cmi(m1, 5); m1 1 {3: 0, 4: 1, 5: 2, 7: 3} >>> _s2cmi(m1, 0); m1 0 {0: 0, 3: 1, 4: 2, 5: 3, 7: 4} >>> _s2cmi(m1, 8); m1 4 {0: 0, 3: 1, 4: 2, 5: 3, 7: 4, 8: 5} """ nv = -1...
def smooth_nulls(matrix): """This function takes a matrix as an input. For any values that meet a condition, it averages the value at the same index in both the preceding and the following rows and assigns the result as its value""" for i, year in enumerate(matrix): for j, day in enumerate(year...
def bbox_vflip(bbox, rows, cols): """Flip a bounding box vertically around the x-axis.""" x_min, y_min, x_max, y_max = bbox return [x_min, 1 - y_max, x_max, 1 - y_min]
def apses_to_ae(apo, per, radius = None): """ Convert apoapsis and periapsis altitudes (expressed in altitudes or absolute values, e.g. 300x800km) to semi-major axis (a) and eccentricity (e). If radius is specified, the apo and per are altitudes, if not specified, apo and per are absolute values """...
def uneditableInput( placeholder="", span=2, inlineHelpText=False, blockHelpText=False): """ *Generate a uneditableInput - TBS style* **Key Arguments:** - ``placeholder`` -- the placeholder text - ``span`` -- column span - ``inlineHelpText`` -- inline...
def normalize_bid(iccu_bid): """ u'IT\\ICCU\\AGR\\0000002' => 'AGR0000002' """ return "".join(iccu_bid.split("\\")[-2:])
def get_partition_key(partition_type, partition_num=None): """Generates a unique key for a partition using its attributes""" key = 'partition' if partition_type in ['cv', 'test']: return '_'.join([key, partition_type]) elif partition_type == 'train': assert partition_num is not None ...
def identifier_keys(items): """Convert dictionary keys to identifiers replace spaces with underscores lowercase the string remove initial digits For convenience of use with NameSpace (above) >>> assert identifier_keys({'A fred': 1})['a_fred'] == 1 """ def identify(x): ...
def _shift_num_right_by(num: int, digits: int) -> int: """Shift a number to the right by discarding some digits We actually use string conversion here since division can provide wrong results due to precision errors for very big numbers. e.g.: 6150000000000000000000000000000000000000000000000 // 1e27 ...
def get_cell_description(cell_input): """Gets cell description Cell description is the first line of a cell, in one of this formats: * single line docstring * single line comment * function definition * %magick """ try: first_line = cell_input.split("\n")[0] if first_l...
def diffs(l): """ 'Simple' (i.e. not pairs) differences of a list l. """ d = [l[i]-l[i-1] for i in range(1,len(l))] d = list(dict.fromkeys(d)) d = sorted(d) return d
def sumBase(n: int, k: int) : """ Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. TC : O(N) SC : O(1) n : int (integer base 10...
def hsv2rgb(h, s, v): """http://en.wikipedia.org/wiki/HSL_and_HSV h (hue) in [0, 360[ s (saturation) in [0, 1] v (value) in [0, 1] return rgb in range [0, 1] """ if v == 0: return 0, 0, 0 if s == 0: return v, v, v i, f = divmod(h / 60., 1) p = v * (1 - s) q...
def _maybe_to_dense(obj): """ try to convert to dense """ if hasattr(obj, 'to_dense'): return obj.to_dense() return obj
def is_negation(bigram_first_word): """Gets the fist word of a bigram and checks if this words is a negation or contraction word""" NEGATION_WORDS = ['no','not'] NEGATION_CONTRACTIONS = ["isn't","aren't","wasn't","weren't","haven't", "hasn't","hadn't","won't","wouldn't","don't", "doesn't","didn't","...
def common_suffix(*seqs): """Return the subsequence that is a common ending of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_suffix >>> common_suffix(list(range(3))) [0, 1, 2] >>> common_suffix(list(range(3)), list(range(4))) [] >>> common_suffix([1, 2, 3], [9, 2, ...
def check_flag(params, string, delete): """ Check if a parameter (string) was beeen declared in the line of commands (params) and return the associated value. If delete is true the related string will be deleted If string is not present, return None Input: params = list of parameters from ori...
def codecs_error_ascii_to_hex(exception): """On unicode decode error (bytes -> unicode error), tries to replace invalid unknown bytes by their hex notation.""" if isinstance(exception, UnicodeDecodeError): obj = exception.object start = exception.start end = exception.end in...
def get_label_features(features, parents=None): """ Recursively get a list of all features that are ClassLabels :param features: :param parents: :return: pairs of tuples as above and the list of class names """ if parents is None: parents = [] label_features = [] for name, fe...
def rect2poly(ll, ur): """ Convert rectangle defined by lower left/upper right to a closed polygon representation. """ x0, y0 = ll x1, y1 = ur return [ [x0, y0], [x0, y1], [x1, y1], [x1, y0], [x0, y0] ]
def check_if_duplicates(aList_in): """[Check if given list contains any duplicates] Returns: [type]: [description] """ iFlag_unique = 1 for elem in aList_in: if aList_in.count(elem) > 1: iFlag_unique = 0 break else: pass return iF...
def intersection_over_union(boxA, boxB): """ IOU (Intersection over Union) = Area of overlap / Area of union @param boxA=[x0, y0, x1, y1] (x1 > x0 && y1 > y0) two pointer are diagonal """ boxA = [int(x) for x in boxA] boxB = [int(x) for x in boxB] xA = max(boxA[0], boxB[0]) yA = max(bo...
def generateNumberTriangleLines(numberTriangle): """ Generate the lines that when printed will give the number triangle appearance. Params: numberTriangle - 2D list representing elements of a number triangle Returns: numberTriangleLines - List of strings to print the number triangle in ...
def SplitAttr(attr): """Takes a fully-scoped attributed and returns a tuple of the (scope, attr). If there is no scope it returns (None, attr). """ s = '' a = '' if attr: if attr.find('/') >= 0: tokens = attr.split('/') else: tokens = attr.rsplit('.', 1) if len(tokens) == 1: a = attr else: ...
def snake_to_pascal(value: str) -> str: """method_name -> MethodName""" return ''.join(map(lambda x: x[0].upper() + x[1:], value.replace('.', '_').split('_')))
def a2b(a): """test -> 01110100011001010111001101110100""" return ''.join([format(ord(c), '08b') for c in a])
def calc_jaccard_index(multiset_a, multiset_b): """Calculate jaccard's coefficient for two multisets mutliset_a and multiset_b. Jaccard index of two set is equal to: (no. of elements in intersection of two multisets) _____________________________________________ (no. of elements in ...
def case_insensitive_dict_get(d, key, default=None): """ Searches a dict for the first key matching case insensitively. If there is an exact match by case for the key, that match is given preference. Args: d: dict to search key: key name to retrieve case-insensitively Returns: valu...
def stringify_rgb(rgb): """Used to convert rgb to string for saving in db""" rgb_value = f"{rgb[0]}, {rgb[1]}, {rgb[2]}, {rgb[3]}" return rgb_value
def isPowerOfFour(num): """ :type num: int :rtype: bool """ return num > 0 and (num&(num-1)) == 0 and (num & 0x55555555) != 0
def ipv4_range_type(string): """ Validates an IPv4 address or address range. """ import re ip_format = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' if not re.match("^{}$".format(ip_format), string): if not re.match("^{}-{}$".format(ip_format, ip_format), string): raise ValueError return...
def __progress_class(replicating_locks, total_locks): """ Returns the progress class (10%, 20%, ...) of currently replicating locks. :param replicating_locks: Currently replicating locks. :param total_locks: Total locks. """ try: return int(float(total_locks - replicating_loc...
def _lrp_meanPcrEff(tarGroup, vecTarget, pcrEff, vecSkipSample, vecNoPlateau, vecShortLogLin): """A function which calculates the mean efficiency of the selected target group excluding bad ones. Args: tarGroup: The target number vecTarget: The vector with the targets numbers pcrEff: The...
def get_round_digits(pair): """Get the number of digits for the round function.""" numberofdigits = 4 if pair: base = pair.split("_")[0] if base in ("BTC", "BNB", "ETH"): numberofdigits = 8 return numberofdigits
def metric_fn(labels, predictions): """ Defines extra evaluation metrics to canned and custom estimators. By default, this returns an empty dictionary Args: labels: A Tensor of the same shape as predictions predictions: A Tensor of arbitrary shape Returns: dictionary of string:m...
def islist(string): """ Checks if a string can be converted into a list. Parameters ---------- value : str Returns ------- bool: True/False if the string can/can not be converted into a list. """ return (list(string)[0] == "[") and (list(string)[-1] == "]")
def is_active_bot(user_info): """ Returns true if the provided user info describes an active bot (i.e. not deleted) """ if not user_info['ok']: return False user = user_info['user'] return user.get('is_bot', False) and not user['deleted']
def encode3(s): """ convert string => bytes for compatibility python 2/3 """ if type(s)==str: return s.encode('UTF-8') return s
def json_analysis(data): """ This fuction creates json navigator, where user can choose what object or data he/she wants to see, by using recursion """ if isinstance(data, dict): print("This object is dictionary") print(data.keys()) users_input = str(input("Please choose wha...
def reorder(datalist, indexlist): """reorder(datalist, indexlist) Returns a new list that is ordered according to the indexes in the indexlist. e.g. reorder(["a", "b", "c"], [2, 0, 1]) -> ["c", "a", "b"] """ return [datalist[idx] for idx in indexlist]
def capitalize(s): """Return a new string like s, but with the first letter capitalized.""" return (s[0].upper() + s[1:]) if s else s
def mean(iterable): """ mean(iter: iterable) mean of a list with numbers args: iterable: list => eg: 0, [1,2,3,4,5] return: number => eg: 3 """ ss, i = 0, 0 for e in iterable: i += 1 ss += e return ss / i
def merge_sort(array): """Merge sort data structure function.""" if len(array) > 1: if len(array) % 2 == 0: half = int(len(array) / 2) else: half = int(len(array) / 2 + .5) left_half = array[:half] right_half = array[half:] merge_sort(left_half) ...
def snake_split(s): """ Split a string into words list using snake_case rules. """ s = s.strip().replace(" ", "") return s.split("_")
def get_free_item_obj(free_items, sku): """Fetch free item obj :param free_items: List :param sku: String :rtype: Dictionary """ for item in free_items: if item["item"] == sku: return item
def win_check(board, mark): """Check if player with respective marker wins""" if board[1] == mark: if (board[2] == mark and board[3] == mark or board[4] == mark and board[7] == mark or board[5] == mark and board[9] == mark): return True if board[5] ...
def iround(x): """Round floating point number and cast to int.""" return int(round(x))
def is_abba(abba_str): """Returns true if 4 character string consists of a pair of two different characters followed by the reverse of that pair""" if len(abba_str) != 4: raise Exception return abba_str[0] == abba_str[3] and abba_str[1] == abba_str[2] and abba_str[0] != abba_str[1]
def bresenham_line(x0, y0, x1, y1): """ Return all pixels between (x0, y0) and (x1, y1) as a list. :param x0: Self explanatory. :param y0: Self explanatory. :param x1: Self explanatory. :param y1: Self explanatory. :return: List of pixel coordinate tuples. """ steep = abs(y1 - y0) ...
def is_connected_seed(seed:int): """Returns True if the given seed would generate a connected graph, False otherwise.""" # We reserve those seed divisible by 3 to the NOT solvable instances return (seed % 3) != 0
def build_dict(transitions, labels, to_filter=[]): """Build a python dictionary from the data in the GAP record produced by kbmag to describe a finite-state automaton. Parameters ----------- transitions : list list of tuples of length `n`, where `n` is the number of possible labels...
def get_group_detail(groups): """ Iterate over group details from the response and retrieve details of groups. :param groups: list of group details from response :return: list of detailed element of groups :rtype: list """ return [{ 'ID': group.get('id', ''), 'Name': group.g...
def orderPath (nodesDict, start, stop, path): """ Internal function used by shortestWay to put into order nodes from the routing table. Return the shortest path from start to stop """ if start == stop: return path + [start] return orderPath (nodesDict, start, nodesDict[stop][0], pat...
def _from_fan_speed(fan_speed: int) -> int: """Convert the Tradfri API fan speed to a percentage value.""" nearest_10: int = round(fan_speed / 10) * 10 # Round to nearest multiple of 10 return round(nearest_10 / 50 * 100)
def cut_name(matrix: list) -> list: """ Clear matrix :param matrix: matrix to clear :return: cleared matrix """ new_matrix = [] for line in matrix: new_matrix.append(line[1:]) return new_matrix
def ix(museum_ix, mvsas_ix, day_ix, p_len, d_len): """Return the index of the variable list represented by the composite indexes""" return day_ix + (d_len)*(mvsas_ix + (p_len)*(museum_ix))
def bool_from_env_string(string: str) -> bool: """Convert a string recieved from an environment variable into a bool. 'true', 'TRUE', 'TrUe', 1, '1' = True Everything else is False. :param string: The string to convert to a bool. """ if str(string).lower() == 'false' or str(string) == ...
def removenone(d): """ Return d with null values removed from all k,v pairs in d and sub objects (list and dict only). When invoked by external (non-recursive) callers, `d` should be a dict object, or else behavior is undefined. """ if isinstance(d, dict): # Recursively call removenone on v...
def listInts(input_list): """ This function takes a list of ints and/or floats and converts all values to type int :param list input_list: list of ints and/or floats :return list int_list: list of only ints """ for i in range(len(input_list)): try: input_list[i] = int(in...
def factorial_n(num): """ (int) -> float Computes num! Returns the factorial of <num> """ # Check for valid input if isinstance(num, int) and num >= 0: # Base Case - terminates recursion if num == 0: return 1 # Breakdown else: ...
def dms_to_degrees(v): """Convert degree/minute/second to decimal degrees.""" d = float(v[0][0]) / float(v[0][1]) m = float(v[1][0]) / float(v[1][1]) s = float(v[2][0]) / float(v[2][1]) return d + (m / 60.0) + (s / 3600.0)
def calc_polynomial(x, a, b, c): """ y = ax^2 + bx + c :param x: :param a: :param b: :param c: :return: """ return a * x ** 2 + b * x + c
def transitive_closure(roots, successors) -> set: """ Transitive closure is a simple unordered graph exploration. """ black = set() grey = set(roots) while grey: k = grey.pop() if k not in black: black.add(k) them = successors(k) if them is not None: grey.update(them) return black
def lower(s): """lower(s) -> string Return a copy of the string s converted to lowercase. """ return s.lower()
def J_p2(Ep, norm=1.0, alpha=2.0): """ Defines the particle distribution of the protons as a power law Parameters ---------- - Ep = E_proton (GeV) - alpha = slope - norm = the normalization (at 1 GeV) in units of cm^-3 GeV-1 Outputs -------- - The particle distribution time...
def destructure(answers: dict, *keys: str) -> list: """[summary] Args: answers (dict) Returns: list: an ordered list of values corresponding to the provided keys """ return [answers[key] if key in answers else None for key in keys]
def fun_lr(lr, total_iters, warmup_total_iters, warmup_lr_start, iters): """Cosine learning rate with warm up.""" factor = pow((1 - 1.0 * iters / total_iters), 0.9) if warmup_total_iters > 0 and iters < warmup_total_iters: factor = 1.0 * iters / warmup_total_iters return lr*factor
def createnozzlelist(nozzles, activen, spacing, firstnozzle=1): """ create an evenly spaced list with ones and zeros """ list = [0] * nozzles for x in range(activen): list[x * (spacing + 1) + firstnozzle] = 1 return list
def simple_conditionals(conditional_A, conditional_B, conditional_C, conditional_D): """ Simplified, more readable test function """ return (conditional_A) and (conditional_B) and (conditional_C) and (conditional_D)
def package_get_details(manifest, package, v_str): """Return the manifest details for a given version of a package. This is just a dictionary access - however, we abstract it away behind this filter. """ try: return manifest['packages'][package][v_str] except KeyError: re...
def get_len(obj): """ A utility function for getting the length of an object. Args: obj: An object, optionally iterable. Returns: The length of that object if it is a list or tuple, otherwise 1. """ if not isinstance(obj, (list, tuple)): return 1 else: retur...
def is_block_number(provided): """ Check if the value is a proper Ethereum block number. :param provided: The value to check. :return: True iff the value is of correct type. """ return type(provided) == int