content
stringlengths
42
6.51k
def gcd(a,b=None): """ Return greatest common divisor using Euclid's Algorithm. a - can be either an integer or a list of integers b - if 'a' is an integer, 'b' should also be one. if 'a' is a list, 'b' should be None """ if (b == None): if (a == []): return 1 g =...
def group_blocks_into_fills(blocks, max_size, min_size=(0, 0, 0)): """ A 'good enough' function that groups similar blocks into fills where possible. `blocks` is an array of (x, y, z, name) tuples where `name` can be any type that defines a block (eg. if all the blocks are the same then `name` could ju...
def how_much_to_go(current_level): """ Calculates the number of points the user needs to obtain to advance levels based on their current level Args: current_level::int The users current level Returns: to_go_points::int The number of points the user needs to ...
def isbn_gendigit (numStr): """ (string)-->(string + 1-digit) Generates the 10th digit in a given 9-digit isbn string. Multiplies the values of individual digits within the given 9-digit string to determine the 10th digit. Prints the original string with its additional 10th digit. Prints X for the 1...
def _splitquery(url): """splitquery('/path?query') --> '/path', 'query'.""" path, delim, query = url.rpartition('?') if delim: return path, query return url, None
def check_for_horseshoe(farm, n_var, m_var, horseshoe) -> int: """Brute-froces the farm to find possible horseshoe places""" found = 0 row = 0 col = 0 horseshoe_length = len(horseshoe) while row < n_var: # check if we can separate a 3x3 square: if ( row + horse...
def _cmp_zorder(lhs, rhs) -> bool: """Used to check if two values are in correct z-curve order. Based on https://github.com/google/neuroglancer/issues/272#issuecomment-752212014 Args: lhs: Left hand side to compare rhs: Right hand side to compare Returns: bool: True if in corre...
def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(2...
def _int_to_bytes(n): """Takes an integer and returns a byte-representation""" return n.to_bytes((n.bit_length() + 7) // 8, 'little') or b'\0' # http://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes
def convert_mb_to_b(size): """ Convert value from MB to B for the given size variable. If the size is a float, the function will convert it to int. :param size: size in MB (float or int). :return: size in B (int). :raises: ValueError for conversion error. """ try: size = int(si...
def parse_components(components, trans_to_range): """Get genes data. Each gene has the following data: 1) It's ID 2) Included transcripts 3) Genic range. """ genes_data = [] for num, component in enumerate(components, 1): gene_id = f"reg_{num}" # get transcripts and thei...
def check_validity(passport): """Check if a passport is valid.""" return len(passport) == 8 or len(passport) == 7 and "cid" not in passport
def generate_filename(in_path, out_dir, bitrate, encoder): """ Create a new filename based on the original video file and test bitrate. Parameters ---------- in_path : str Full path of input video. out_dir : str Directory of output video. bitrate : int Video bitrate ...
def partition(A, p, r): """ Quicksort supporting algorithm. """ q = p for u in range(p, r): if A[u] <= A[r]: A[q],A[u] = A[u],A[q] q += 1 A[q],A[r] = A[r],A[q] return q
def virial_mass(FWHM, vel_disp): """ Calculates the Vyrial Theorem based Dynamical mass FWHM is the deconvolved size of the source in pc vel_disp is the velocity dispersion in km/s http://adsabs.harvard.edu/abs/2018arXiv180402083L Leroy et al 2018 """ M = 892. * FWHM * (vel_disp**2.) ...
def get_type(data): """ @param data: rosdoc manifest data @return 'stack' of 'package' """ return data.get('package_type', 'package')
def post(post_id): """ get post page url :param post_id: int :return: string """ return "http://www.vanpeople.com/c/" + str(post_id) + ".html"
def count_number_fishers_alive(dict_fishers,gamerunning): """ This function , count the number of fishers alive in the island, if is 1 the number of players alive and the game is running, he catch the number, and form a message of the winner, otherwise ,return just return the number of players @param dict_fis...
def xy_data(dataset, variable): """X-Y line/circle data related to a dataset""" # import time # time.sleep(5) # Simulate expensive I/O or slow server if dataset == "takm4p4": return { "x": [0, 1e5, 2e5], "y": [0, 1e5, 2e5] } else: return { ...
def create_distance_data(distances: list): """ :param distances: list of Distance objects :return: array of distance values, array of id values """ ids = [] values = [] for dist in distances: ids.append(dist._id) values.append(dist.value) return values, ids
def mark_code_blocks(txt, keyword='>>>', split='\n', tag="```", lang='python'): """ Enclose code blocks in formatting tags. Default settings are consistent with markdown-styled code blocks for Python code. Args: txt: String to search for code blocks. keyword(optional, string): String tha...
def countSuccess( successList, failList ): """Intended to be used with 'renewsliver', 'deletesliver', and 'shutdown' which return a two item tuple as their second argument. The first item is a list of urns/urls for which it successfully performed the operation. The second item is a list of the urn...
def prime(n, primes): """Return True if a given n is a prime number, else False.""" if n > 5 and n % 10 == 5: return False for p in primes: if n % p == 0: return False return True
def intersect(tup1, tup2): """ Return the common interval between tup1 and tup2. """ return (max(tup1[0], tup2[0]), min(tup1[1], tup2[0]))
def parseSysfsValue(key, value): """ Parse the sysfs value string Parameters: value -- SysFS value to parse Some SysFS files aren't a single line/string, so we need to parse it to get the desired value """ if key == 'id': # Strip the 0x prefix return value[2:] if key ==...
def _fix_missing_period(line): """ Adds a period to a line that is missing a period. """ dm_single_close_quote = u'\u2019' dm_double_close_quote = u'\u201d' END_TOKENS = [ '.', '!', '?', '...', "'", "`", '"', dm_single_close_quote, ...
def intersect_lists(l1, l2): """Returns the intersection of two lists. The result will not contain duplicate elements and list order is not preserved.""" return list(set(l1).intersection(set(l2)))
def extract_chat_id(body): """ Obtains the chat ID from the event body Parameters ---------- body: dic Body of webhook event Returns ------- int Chat ID of user """ if "edited_message" in body.keys(): chat_id = body["edited_message"]["chat"]["id"] ...
def selection_sort(array): """ Selection sort algorithm. :param array: the array to be sorted. :return: sorted array >>> import random >>> array = random.sample(range(-50, 50), 100) >>> selection_sort(array) == sorted(array) True """ for i in range(0, len(array) - 1): min...
def output_pins(pins): """ :param pins: dictionary of all pins, input and output :return: dictionary of pins configured as output """ outputs = {} for key in pins.keys(): if pins[key]['pin_direction'] == 'output': outputs[key] = pins[key] return outputs
def start_from(year, starting_year): """[Returns the years from the first publication of the book] Args: year ([str]): [Year of the book] starting_year ([str]): [Year of pulication of the first book of the serie] Returns: [int]: [Years since the publication of the first book of the...
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ try: if number < 0 : return 'complex numbers not supported' elif number >= 0...
def product(A,B): """Takes two sets A and B, and returns their cartesian product as a set of 2-tuples.""" product = set() for x in A: for y in B: product.add((x,y)) """Now it is time to return the result""" return product
def strategy(history, alivePlayers, whoami, memory): """ history contains all previous rounds (key : id of player (shooter), value : id of player (target)) alivePlayers is a list of all player ids whoami is your own id (to not kill yourself by mistake) memory is None by default ...
def list_to_text(what_to_show_): """converts list to text to use in plottitle Args: what_to_show_ (list with strings): list with the fields Returns: string: text to use in plottitle """ what_to_show_ = what_to_show_ if type(what_to_show_) == list else [what_to_show_] w = "" ...
def parse_version(version): """Parse version string and return version date integer.""" try: if "-" in version: return int(version.split("-", 1)[0]) except TypeError: return version
def normalize_course_id(course_id): """Make course_id directory naming name worthy convert: from: course-v1:course+name to: course_name """ return course_id.split(":")[1].replace("+", "_")
def is_key_valid(key): """ Return True if a key is valid """ if len(key) < 8: print() print('The master key should be at least 8 characters. Please try again!') print() return False return True
def Nv_for_nuclide(nuclide): """Calculate oscillator quantum number of valence shell for given nuclide. Arguments: nuclide (tuple): (Z,N) for nuclide Returns: Nv (int): oscilllator quantum number for valence shell """ # each major shell eta=2*n+l (for a spin-1/2 fermion) contains ...
def class_fullname(obj): """Returns the full class name of an object""" return obj.__module__ + "." + obj.__class__.__name__
def decay_value(base_value, decay_rate, decay_steps, step): """ decay base_value by decay_rate every decay_steps :param base_value: :param decay_rate: :param decay_steps: :param step: :return: decayed value """ return base_value*decay_rate**(step/decay_steps)
def count_binary_ones(number): """ Returns the number of 1s in the binary representation of number (>=0) For e.g 5 returns 2 (101 has 2 1's), 21 returns 3 ("10101") """ # Use only builtins to get this done. No control statements plz return bin(number)[2:].count("1")
def convert_message(content, id): """ Strip off the useless sf message header crap """ if content[:14] == 'Logged In: YES': return '\n'.join(content.splitlines()[3:]).strip() return content
def sum_value(values, period=None): """Returns the final sum. :param values: list of values to iterate. :param period: (optional) # of values to include in computation. * None - includes all values in computation. :rtype: the final sum. Examples: >>> values = [34, 30, 29, 34, 38, 25, 3...
def get_comma_separated_values(values): """Return the values as a comma-separated string""" # Make sure values is a list or tuple if not isinstance(values, list) and not isinstance(values, tuple): values = [values] return ','.join(values)
def invert_dict(d): """unvert dict""" inverse = dict() for key in d: # Go through the list that is saved in the dict: for item in d[key]: # Check if in the inverted dict the key exists if item not in inverse: # If not create a new list ...
def get_ue_sla(ue_throughput, ue_required_bandwidth): """ Function to calculate UE's SLA """ return int(ue_throughput >= ue_required_bandwidth)
def is_ascii(s): """Checks if text is in ascii. Thanks to this thread on StackOverflow: http://stackoverflow.com/a/196392/881330 """ return all(ord(c) < 256 for c in s)
def adjust_learning_rate(learning_rate, epoch, step=20): """Sets the learning rate to the initial LR decayed by 10 every 10 epochs""" lr = learning_rate * (1 ** (epoch // step)) return lr
def totalcost(endclasses): """ Tabulates the total expected cost of given endlcasses from a run. Parameters ---------- endclasses : dict Dictionary of end-state classifications with 'expected cost' attributes Returns ------- totalcost : Float The total expected cost of ...
def highest_occurrence(array): """ Time: O(n) Space: O(n) :param array: strings, int or floats, can be mixed :return: array containing element(s) with the highest occurrences without type coercion. Returns an empty array if given array is empty. """ # hash table with a count of each ...
def get_version_mapping_directories(server_type): """ This function will return all the version mapping directories :param server_type: :return: """ if server_type == 'gpdb': return ( {'name': "gpdb_5.0_plus", 'number': 80323}, {'name': "5_plus", 'number': 80323},...
def isGifv(link): """ Returns True if link ends with video suffix """ return link.lower().endswith('.gifv')
def multis_2_mono(table): """ Converts each multiline string in a table to single line. Parameters ---------- table : list of list of str A list of rows containing strings Returns ------- table : list of lists of str """ for row in range(len(table)): for column ...
def parse_header(elements) -> dict: """ Parse headers from nodes TSV Parameters ---------- elements: list The header record Returns ------- dict: A dictionary of node header names to index """ header_dict = {} for col in elements: header_dict[col] = el...
def _GetNestedKeyFromManifest(manifest, *keys): """Get the value of a key path from a dict. Args: manifest: the dict representation of a manifest *keys: an ordered list of items in the nested key Returns: The value of the nested key in the manifest. None, if the nested key does not exist. """ ...
def _wayback_timestamp(**kwargs): """Return a formatted timestamp.""" return "".join( str(kwargs[key]).zfill(2) for key in ["year", "month", "day", "hour", "minute"] )
def solver_problem2(input_list): """walk through the route and return aim""" horizon = 0 depth = 0 aim = 0 for direction, distance in input_list: if direction == "forward": horizon += distance depth = depth + aim * distance elif direction == "down": ...
def get_attachment_name(attachment_name): """ Retrieve attachment name or error string if none is provided :param attachment_name: attachment name to retrieve :return: string """ if attachment_name is None or attachment_name == "": return "demisto_untitled_attachment" return attachme...
def cardLuhnChecksumIsValid(card_number): """ checks to make sure that a number passes a luhn mod-10 credit card checksum """ card_number = ''.join(card_number.split()) # remove all whitespace sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits): ...
def _get_masks(tokens, max_seq_length): """Mask for padding""" if len(tokens) > max_seq_length: raise IndexError("Token length more than max seq length!") return [1]*len(tokens) + [0] * (max_seq_length - len(tokens))
def strip_domain_address(ip_address): """ Strip domain from ip address """ mask_index = ip_address.find('/') if mask_index > 0: return ip_address[:mask_index].split('%')[0] + ip_address[mask_index:] else: return ip_address.split('%')[0]
def count_all(obj): """ Return the number of elements in obj or sublists of obj if obj is a list. Otherwise, if obj is a non-list return 1. @param object|list obj: object to count @rtype: int >>> count_all(17) 1 >>> count_all([17, 17, 5]) 3 >>> count_all([17, [17, 5], 3]) 4...
def list_of_lists(string): """list_of_list Parse a string of the form "1,2,3 4,3,2 ..." :param string: """ if string: return [float(x) for x in string.strip().split(",")] else: return string
def get_gender(gender: str) -> str: """ :param gender: :return: """ gen = 'male' if gender == "0": gen = 'male' elif gender == "1": gen = 'female' elif gender == "2": gen = "d" else: raise IndexError("Unknown gender-index: " + gender) return gen
def get_sequence_header_length(seq_header_len): """Returns length of SEQUENCE header.""" if seq_header_len > 255: return 4 if seq_header_len > 127: return 3 return 2
def lower_case(s): """Transforms an input string into its lower case version. Args: s (str): Input string. Returns: Lower case of 's'. """ return s.lower()
def escape_codepoints(codepoint): """Skip the codepoints that cannot be encoded directly in JSON. """ if codepoint == 34: codepoint += 1 # skip " elif codepoint == 92: codepoint += 1 # Skip backslash return codepoint
def isint(num): """Test whether a number is *functionally* an integer""" try: int(num) == float(num) except ValueError: return False return True
def shallow_copy_as_ordinary_list(iterable): """Return a simple list that is a shallow copy of the given iterable. NOTE: This is needed because "copy.copy(x)" returns an SqlAlchemy InstrumentedList when the given 'x' is such. Then, operations on the instrumented copy (e.g., remove) cause SqlA-side-eff...
def div(html:str)->str: """wrap an html snippet in a <div></div>""" return f'<div>{html}</div>'
def get_locus_blocks(glstring): """ Take a GL String, and return a list of locus blocks """ # return re.split(r'[\^]', glstring) return glstring.split('^')
def calculate_symmetric_kl_divergence(p, q, calculate_kl_divergence): """ This function calculates the symmetric KL-divergence between distributions p and q. In particular, it defines the symmetric KL-divergence to be: .. math:: D_{sym}(p||q) := \frac{D(p||q) + D(p||p)}{2} Args: ...
def marked(obj): """Whether an object has been marked by spack_yaml.""" return (hasattr(obj, '_start_mark') and obj._start_mark or hasattr(obj, '_end_mark') and obj._end_mark)
def type_match(haystack, needle): """Check whether the needle list is fully contained within the haystack list, starting from the front.""" if len(needle) > len(haystack): return False for idx in range(0, len(needle)): if haystack[idx] != needle[idx]: return False return ...
def invert_yang_modules_dict(in_dict: dict, debug_level: int = 0): """ Invert the dictionary of key:RFC/Draft file name, value:list of extracted YANG models into a dictionary of key:YANG model, value:RFC/Draft file name Arguments: :param in_dict (dict) input...
def get_nested_item(d, list_of_keys): """Returns the item from a nested dictionary. Each key in list_of_keys is accessed in order. Args: d: dictionary list_of_keys: list of keys Returns: item in d[list_of_keys[0]][list_of_keys[1]]... """ dct = d for i, k in enumerate(list_o...
def CRL_focalpoint(energy,lens_configuration): """ CRL_focalpoint(energy,lens_configuration): lens_confguration is a dictionary of the form [lens_radius1:numer lenses, lens_radius2: number_lenses, ...] returns the focal length """ focal_distance=0.0 return focal_distance
def column_names_window(columns: list, window: int) -> list: """ Parameters ---------- columns: list List of column names window: int Window size Return ------ Column names with the format: w_{step}_{feature_name} """ new_columns = [] for w in rang...
def titlecase(input_str): """Transforms a string to titlecase.""" return "".join([x.title() for x in input_str.split('_')])
def _get_effective_padding_node_input(stride, padding, effective_padding_output): """Computes effective padding at the input of a given layer. Args: stride: Stride of given layer (integer). padding: Padding of given layer (integer). effective_padding_output: Effective padding at output of given layer ...
def get_range(min_val, max_val): """ Returns a range of values """ return range(min_val, max_val)
def any_in(a_set, b_set): """ Boolean variable that is ``True`` if elements in a given set `a_set` intersect with elements in another set `b_set`. Otherwise, the boolean is ``False``. Parameters ___________ a_set : list First set of elements. b_set : list Second set of eleme...
def check_compatibility(test_stem, reference_stems, compatibility_matrix): """ Checks if a given test stem is compatible with stems in another set of reference stems When folding RNA by adding stems, this function can used be to check if the added stem crosses or overlaps the stems already present ...
def get_dihedrals(bonds): """ Iterate through bonds to get dihedrals. Bonds should contain no duplicates. """ dihedrals = [] for i1, middle_bond in enumerate(bonds): atom1, atom2 = middle_bond atom1_bonds, atom2_bonds = [], [] for i2, other_bond in enumerate(bonds): ...
def city_functions(city, country, population=''): """Generate a neatly formatted city.""" if population: return (city.title() + ', ' + country.title() + ' - population ' + str(population) + '.') return city.title() + ', ' + country.title() + '.'
def first_index(lst, predicate): """Return the index of the first element that matches a predicate. :param lst: list to find the matching element in. :param predicate: predicate object. :returns: the index of the first matching element or None if no element matches the predicate. """ ...
def memoized(cache, f, arg): """Memoizes a call to `f` with `arg` in the dict `cache`. Modifies the cache dict in place.""" res = cache.get(arg) if arg in cache: return cache[arg] else: res = f(arg) cache[arg] = res return res
def temp_validation(value): """ :param value: temperature value given by the system :return: Boolean """ min_value = 0 max_value = 45 return True if (value > min_value) and (value < max_value) else False
def dim_returns(k, inverse_scale_factor): """ A simple utility calculation method. Given k items in posession return the benefit of a K + 1th item given some inverse scale factor. The formula used is utility = 100% if no items are in posession or utility = 1 / inverse_scale_factor * (k + 1) ...
def addtime(output, unit, t): """add a formatted unit of time to an accumulating string""" if t: output += ("%s%d %s%s" % ((", " if output else ""), t, unit, ("s" if t > 1 else ""))) return output
def get_cad_srt(cad, component, placeholder): """ Parse component dictionary of component EDA2CADTransform objects. Get CAD Scale, Rotation, Translation about part's local coordinate system. """ if cad is not None: scale = [component.get("scale")['X'], compon...
def firstUniqChar(s): """ :type s: str :rtype: int """ h = {} for i, c in enumerate(s): if c in h: h[c] = -1 else: h[c] = i for c in s: if h[c] != -1: return h[c] return -1
def set_level(request, level): """ Set the minimum level of messages to be recorded, and return ``True`` if the level was recorded successfully. If set to ``None``, use the default level (see the get_level() function). """ if not hasattr(request, 'dmm_backend'): return False request...
def check_convergence(p_in, p_out, tols, abs_flags): """ All four input arguments are lists or tuples of the same length. Compares values in 'p_in' against those in 'p_out', and returns False if the difference is greater than the corresponding value in 'tols'. If the value in 'abs_flags' is True, t...
def bin_to_str(bin_str_arr): """ Convert binary number in string to string :param bin_str_arr: str, whose length must be a multiple of 8 :return: str """ res = '' for i in range(0, len(bin_str_arr), 8): res += chr(int(bin_str_arr[i:i+8], 2)) return res
def score_gamma(x, k, theta): """ Compute score function of one-dimensional Gamma distribution. inputs: x: real number at which the score function is evaluated k: positive number (shape parameter of Gamma distribution) theta: positive number (scale parameter of Gamma distribution) ...
def bin_data(array_like, bin_size): """ This is an old alias, please use bin_sum_data or bin_mean_data """ return([sum(array_like[i:i+bin_size]) for i in range(0, len(array_like), bin_size)])
def path_to_str(pathP: list) -> str: """Use to get a string representing a path from a list""" if len(pathP) < 1: return "" if len(pathP) < 2: return pathP[0] res = f"{pathP[0]} -> " for i in range(1, len(pathP) - 1): res += f"{pathP[i]} -> " return res + f"{pathP[-1]}"
def base36_to_int(s): """ Convertd a base 36 string to an integer """ return int(s, 36)