content
stringlengths
42
6.51k
def AlamAv_from_ElamV(ElamV, Rv): """ Find A(lambda)/A(V) from E(lambda - V) / E(B - V). """ return (ElamV + Rv) / Rv
def _jinja2_filter_datetime(data): """ Extract an excert of a post """ words = data.split(" ") return " ".join(words[:100])
def not_empty_list(l): """Check if given value is a non-empty list. :param l: value :return: True on non-empty list, False otherwise :rtype: bool :Example: >>> not_empty_list([1, 2, 3]) True >>> not_empty_list(None) False """ return isinstance(l, list) and l...
def coerce_list(obj) -> list: """ Takes an object of any type and returns a list. If ``obj`` is a list it will be passed back with modification. Otherwise, a single-item list containing ``obj`` will be returned. :param obj: an object of any type :return: a list equal to or containing ``obj`` "...
def 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_vector) is not degr...
def escape(text): """escape html control characters Everything which might include input text should be escaped before output as html for security""" return text.replace('&', '&amp;').replace('<', '&lt;').replace( '>', '&gt;').replace('"', '&quot;').replace("'", '&apos;')
def _get_s3_presigned_url(response_dict): """ Helper method to create an S3 presigned url from the response dictionary. """ url = response_dict['url'] return url['scheme']+'://'+url['host']+url['path']+'?'+url['query']
def to_list(x): """This normalizes a list/tensor into a list. If a tensor is passed, we return a list of size 1 containing the tensor. """ if isinstance(x, list): return x return [x]
def check_approved(userName, userArn): """Summary Args: userName (TYPE): Description userArn (TYPE): Description Returns: TYPE: Description """ # Default approved = False # Connect change record DDB # Check if approved for adding users # Check how many us...
def any_plus(choices): """ Appends Any as an option to the choices for a form""" choices = list(choices) choices.insert(0, ("any", "- Any -")) return choices
def compose_source_labels_path_for(path): """Return source labels file path for given file.""" return '%s.syntaxLabels.src' % path
def wrap_lambda(func, instance_ptr, capture=True): """ Wrap func to instance (singleton) with C++ lambda """ args_lambda = [] args_lambda_sig = [] for i, param in enumerate(func["parameters"]): argname = "p" + str(i) args_lambda_sig.append("%s %s" % (param["type"], argname)) args...
def is_storage(file, storage=None): """ Check if file is a local file or a storage file. Args: file (str or int): file path, URL or file descriptor. storage (str): Storage name. Returns: bool: return True if file is not local. """ if storage: return True eli...
def status_sps(status): """ This method will return valid, invalid or undefined for a given result of models.PackageMember.sps_validation_status(). status: Tuple(None, {}) status: Tuple(True, {'is_valid': True, 'sps_errors': [], 'dtd_errors': []}) status: Tuple(False, {'is_valid': True, 'sps_er...
def quote(s: str) -> str: """ Quotes a string and escapes special characters inside the string. It also removes $ from the string since those are not allowed in NGINX strings (unless referencing a variable). :param s: The string to quote :return: The quoted string """ return "'" + s.replace...
def capitalize(text): """ Creates a copy of ``text`` with only its first character capitalized. For 8-bit strings, this function is locale-dependent. :param text: The string to capitalize :type text: ``str`` :return: A copy of ``text`` with only its first character capitalized. ...
def pad_left(orig, pad, new_length): """ Pad a string on the left side. Returns a padded version of the original string. Caveat: The max length of the pad string is 1 character. If the passed in pad is more than 1 character, the original string is returned. """ if len(p...
def total (initial, *positionals, **keywords): """ Simply sums up all the passed numbers. """ count = initial for n in positionals: count += n for n in keywords: count += keywords[n] return count
def all_numbers(maybe_string_with_numbers): """In this challenge you need to return true if all of the characters in 'maybe_string_with_numbers' are numbers if all of the characters in the string are not numbers please return false """ return str.isdigit(maybe_string_with_numbers)
def get_default_chunksize(length, num_splits): """Creates the most equal chunksize possible based on length and number of splits. Args: length: The integer length to split (number of rows/columns). num_splits: The integer number of splits. Returns: An integer chunksize. """ ...
def nhi(b3, b11): """ Normalized Humidity Index (Lacaux et al., 2007). .. math:: NHI = (b11 - b3)/(b11 + b3) :param b3: Green. :type b3: numpy.ndarray or float :param b11: SWIR 1. :type b11: numpy.ndarray or float :returns NHI: Index value .. Tip:: Zarco-Tejada, P. J., Mi...
def validate_vector(obj, throwerr=False): """ Given an object obj, check if it is a valid raw representation of a real mathematical vector. An accepted object would: 1. be a Python list or Python tuple 2. be 2 or 3 items in length :param obj: Test subject :param throwerr: Raise an e...
def split(s): """Split a pathname into two parts: the directory leading up to the final bit, and the basename (the filename, without colons, in that directory). The result (s, t) is such that join(s, t) yields the original argument.""" if ':' not in s: return '', s colon = 0 for i in range(len(...
def box(text, gen_text=None): """Create an HTML box of text""" if gen_text: raw_html = '<div style="padding:8px;font-size:20px;margin-top:20px;margin-bottom:14px;">' + str( text) + '<span style="color: red">' + str(gen_text) + '</div>' else: raw_html = '<div style="border-botto...
def high_low(input, inverse=False): """ return 'higher' or 'lower' based on the amount. Used for metric comparison boxes """ if input > 0 and inverse == False: return 'higher' if input > 0 and inverse == True: return "lower" if input < 0 and inverse == True: return "highe...
def simp_str(str): """Return a integer list to count: upper-, lowercase, numbers, and spec. ch. input = string output = list of integers, to count ex: if input is "*'&ABCDabcde12345"), output: [4,5,5,3]. the order is: uppercase letters, lowercase, numbers and special characters. """ len_str...
def calculate_rtu_inter_char(baudrate): """calculates the interchar delay from the baudrate""" if baudrate <= 19200: return 11.0 / baudrate else: return 0.0005
def convert_complementary_base_char(base_char: str, is_dna: bool) -> str: """ A function that converts base char into complementary base char returns '' when inputed base doesn't have conplementary base :param base_char: :param is_dna: :return cpm_char: """ dict_of_dna_cpm_base = {'A': '...
def equal_letters_numbers_brute_force(A): """ Here, I'm trying to outputs the sub-array that its numbers and letters *content* are equal: Count(A, subarray) = Count(B, subarray) in [A,B,A,A,A,B,B,B,A,B,A,A,B,B,A,A,A,A,A,A] :param A: :return: """ def has_equal(A, i, j): # Create mapp...
def filter_source_files(source_files, target_dates): """ Filters dataset files by date. This optimizes time series generation by only using files that belong to the dates for which new dataset files were fetched for. :param source_files: list of filenames to filter :param target_dates: list of date...
def deleteIntroTabs(s): """ @param s: String where we want to delete tabs ("\t") and enters ("\r") @return: The same string "s" without those special characters """ s = s.replace("\n","") #s = s.replace(" ","") s = s.replace("\t","") return s
def stripReservedNameChars(nam): """ Return identifier with reserved characters removed """ reservedChars = """<>& %?:;+"'""" return "".join([c for c in nam if c not in reservedChars])
def kmp_prefix(inp, bound=None): """Return the KMP prefix table for a provided string.""" # If no bound was provided, default to length of the input minus 1 if not bound: bound = len(inp) - 1 table = [0] * (bound+1) # Initialize a table of length bound + 1 ref = 0 # Start referencing at th...
def aggregate_subclasses(labels): """ Aggregates the labels, takes labels of subclasses and aggregates them in the original classes """ label_tmp = [] for i in range(len(labels)): label_tmp.append(labels[i].split("_")[0]) return label_tmp
def arcgiscache_path(tile_coord): """ >>> arcgiscache_path((1234567, 87654321, 9)) 'L09/R05397fb1/C0012d687' """ return 'L%02d/R%08x/C%08x' % (tile_coord[2], tile_coord[1], tile_coord[0])
def get_words(message): """Get the normalized list of words from a message string. This function should split a message into words, normalize them, and return the resulting list. For splitting, you should split on spaces. For normalization, you should convert everything to lowercase. Args: ...
def str2byte(_str): """ str to bytes :param _str: :return: """ return bytes(_str, encoding='utf8')
def strip_element(string, tag, attributes=""): """ Removes all elements with the given tagname and attributes from the string. Open and close tags are kept in balance. No HTML parser is used: strip_element(s, "a", "href='foo' class='bar'") matches "<a href='foo' class='bar'" but not "<a clas...
def is_positive(number): """ The is_positive function should return "True" if the number received is positive, otherwise it returns "None". """ if number > 0: return True return None
def get_subnode(node, key): """Returns the requested value from a dictionary, while ignoring null values""" if node != None and key in node: return node[key] return None
def convertIDtoValueListRecur(listOfDict): """Recursive function of the convertIDtoValue Args: listOfDict (list): The list of dict in the original dict Returns: list: The list of directory with property with single "@id" kay to have the value of it instead """ newList = list() ...
def angle_from_point( x, img_width=640, fov_angle=44 ): """ Calculate the angle from a point """ return( -( ( img_width / 2 ) - x ) * fov_angle )
def min_digits(x): """ Return the minimum integer that has at least ``x`` digits: >>> min_digits(0) 0 >>> min_digits(4) 1000 """ if x <= 0: return 0 return 10 ** (x - 1)
def wer(ref: str, hyp: str) -> float: """Implemented after https://martin-thoma.com/word-error-rate-calculation/, but without numpy""" r, h = ref.split(), hyp.split() # initialisation d = [[0 for inner in range(len(h)+1)] for outer in range(len(r)+1)] for i in range(len(r)+1): d.append([]) ...
def normalizeVersion(s): """ remove possible prefix from given string and convert to uppercase """ prefixes = ['VERSION', 'VER.', 'VER', 'V.', 'V', 'REVISION', 'REV.', 'REV', 'R.', 'R'] if not s: return str() s = str(s).upper() for i in prefixes: if s[:len(i)] == i: s = s...
def contain(x1, y1, w1, h1, x2, y2, w2, h2): """ check if the first rectangle fully contains the second one """ return x1 <= x2 and y1 <= y2 and x2 + w2 <= x1 + w1 and y2 + h2 <= y1 + h1
def vector_cross(vector1, vector2): """ Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple """ try: if vector1...
def number_of_divisors(n): """ Number of divisors of n. >>> number_of_divisors(28) 6 """ cnt = 1 if n > 1: cnt += 1 half = n//2 for i in range(2, half+1): if n % i == 0: cnt += 1 return cnt
def time_format(sec): """ Args: param1(): """ hours = sec // 3600 rem = sec - hours * 3600 mins = rem // 60 secs = rem - mins * 60 return hours, mins, round(secs,2)
def centre(images): """Mapping from {0, 1, ..., 255} to {-1, -1 + 1/127.5, ..., 1}.""" return images / 127.5 - 1
def call_if_callable(v, *args, **kwargs): """ if v is callable, call it with args and kwargs. If not, return v itself """ return v(*args, **kwargs) if callable(v) else v
def find_cheapest_fuel(crabs): """ Find cheapest fuel consumption combination :param crabs: list of crabs :return: cheapest sum of fuel consumption """ min_fuel_sum = sum(crabs) for align_position in range(min(crabs), max(crabs) + 1): current_fuel_sum = 0 for crab_position in...
def int_func(word: str) -> str: """ Returns a word with the first letter capitalized. >>> int_func('text') 'Text' """ return word[0].upper() + word[1:]
def xstr(this_string): """Return an empty string if the type is NoneType This avoids error when we're looking for a string throughout the script :param s: an object to be checked if it is NoneType """ if this_string is None: return '' return str(this_string)
def _GetValueAndIndexForMax(data_array): """Helper function to get both max and argmax of a given array. Args: data_array: (list) array with the values. Returns: (tuple) containing max(data_array) and argmax(data_array). """ value_max = max(data_array) ind_max = data_array.index(value_max) retu...
def str2html(src: str) -> str: """Switch normal string to a html type""" if not src: return "" str_list = src.split("\n") while str_list[-1] == "\n" or str_list[-1] == "": str_list.pop() for i in range(len(str_list) - 1): str_list[i] += "<br>" return "".join(str_list)
def is_classic_netcdf(file_buffer): """ Returns True if the contents of the byte array matches the magic number in netCDF files :param str file_buffer: Byte-array of the first 4 bytes of a file """ # CDF. if file_buffer == b"\x43\x44\x46\x01": return True return False
def apply_pbc(points, box_size): """Apply periodic boundary conditions to keep points in the box.""" def pbc_1d(v, vmax): while v < 0.: v += vmax return v % vmax points_pbc = [] xmax, ymax, zmax = box_size for x, y, z in points: point = [ pbc_1d(x,...
def linfct(x,a,tau): """ linear function input: x: coordinates a: offset tau: slope """ return a + x*tau
def _get_aligned_offsets(hd_list, height, align="baseline"): """ Given a list of (height, descent) of each boxes, align the boxes with *align* and calculate the y-offsets of each boxes. total width and the offset positions of each items according to *mode*. xdescent is analogous to the usual descent...
def Mass_of_spaceship(wet_mass, mass_flow, dry_mass, i): """Calculates the mass of the rocket at time t Args: wet_mass (float): The mass of the ship and fuel at time t=0. mass_flow (float): Amount of fuel expelled per timestep i (int): Iterator used for Euler's Method Returns: ...
def getRevComp(primer): """\ Function determines the reverse complement of a string. The complement dictionary contains all possibilities of bases/wildcards and their complement. """ complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R':'Y','Y':'R', 'S':'S', 'W':'W', 'K':'M','B':'T','V':'B', 'D':'H','H'...
def ci_lookup(the_key, the_dict, default=None): """Case-insensitive lookup Note that this will not work if keys are not unique in lower case - it will match the last of the matching keys >>> the_dict1 = {'Me': 'Andrew', 'You': 'Boris', 'Her': 'Natasha'} >>> ci_lookup('heR', the_dict1) ...
def reactions(mu, states): """Executes Michaelis-Menten chemical reactions. :Arguments: mu : int Index of the equation states : NumPy array Current states of the system (E, S, ES, P) :Returns: NumPy array : Updated state vector (E, S, ES, P) """ if m...
def arr_in_list(gast_list): """ returns true if there is a gast node of type arr in list of gast nodes else returns false """ for node in gast_list: if node["type"] == "arr": return True return False
def validate_confirm_password(value, password): """ Returns 'Valid' if confirmation password provided by user is valid, otherwise an appropriate error message is returned """ if not value: message = 'Please confirm password.' elif value != password: message = 'This password does ...
def uniq(seq): """Return list of unique values while preserving order. Values must be hashable. """ seen, result = {}, [] for item in seq: if item in seen: continue seen[item] = None result.append(item) return result
def any_difference_of_one(stem, bulge): """ See if there's any difference of one between the two ends of the stem [(a,b),(c,d)] and a bulge (e,f) :param stem: A couple of couples (2 x 2-tuple) indicating the start and end nucleotides of the stem in the form ((s1, e1), (s2, e2)) :pa...
def convert_time_12(time): """ Given a number, convert to 12 H unless its the hour 12-2 """ if not time == "12": time = str(int(time)-12) return time
def parse_book_name(line): """ Extracts book name and year from title :param line: string containing book title :return: name: book name year: book year """ parts = line.split(':') name = parts[0].strip() if(parts.__len__() > 1): year = parts[1].strip() else: ...
def auto_raytracing_grid_size(source_fwhm_parcsec, grid_size_scale=0.005, power=1.): """ This function returns the size of a ray tracing grid in units of arcsec appropriate for magnification computations with finite-size background sources. This fit is calibrated for source sizes (interpreted as the FWHM o...
def int_to_bytes(n, minlen=0): # helper function """ int/long to bytes (little-endian byte order). Note: built-in int.to_bytes() method could be used in Python 3. """ nbits = n.bit_length() + (1 if n < 0 else 0) # plus one for any sign bit nbytes = (nbits+7) // 8 # number of whole bytes b...
def sel_reverse(arr, l): """Return a list with items reversed in steps.""" if l == 0: return arr arr = [arr[i:i + l][::-1] for i in range(0, len(arr), l)] return sum(arr, [])
def unit(v): """Return a unit vector""" return v/abs(v)
def str_convert(arg): """ Convert a VBA expression to an str, handling VBA NULL. """ if (arg == "NULL"): return '' return str(arg)
def rename(row, renaming): """Rename keys in a dictionary. For each (k,v) in renaming.items(): rename row[k] to row[v]. """ if not renaming: return row for k,v in renaming.items(): row[v] = row[k] del row[k]
def getDiffElements(initialList: list, newList: list) -> list: """Returns the elements that differ in the two given lists Args: initialList (list): The first list newList (list): The second list Returns: list: The list of element differing between the two given lists """ fi...
def get_simple_split(branchfile): """Splits the branchfile argument and assuming branch is the first path component in branchfile, will return branch and file else None.""" index = branchfile.find('/') if index == -1: return None, None branch, file = branchfile.split('/', 1) return b...
def convert_target_counters(x): """ This function converts the FxxxGxxx xml format to the final format. E.g: F29G034 -> 29034, F08G069 -> 8069. """ if x[1] == str(0): # If the counter in question is of the F0xx format -> remove 0 and keep the rest of the numbers cpy = x.replace("F", "")....
def next_string(string): """Create a string followed by an underscore and a consecutive number""" # if the string is already numbered the last digit is separeted from the rest of the string by an "_" split = string.split("_") end = split[-1] if end.isdigit(): string = "_".join(split[:-1]) ...
def none(x): """Return True if all elements in `x` are False""" return all([not i for i in x])
def interpolation(x0, y0, x1, y1, x): """ Performs interpolation. Parameters ---------- x0 : float. The coordinate of the first point on the x axis. y0 : float. The coordinate of the first point on the y axis. x1 : float. The coordinate of the second point on the x a...
def static_cond(pred, fn1, fn2): """Return either fn1() or fn2() based on the boolean value of `pred`. Same signature as `control_flow_ops.cond()` but requires pred to be a bool. Args: pred: A value determining whether to return the result of `fn1` or `fn2`. fn1: The callable to be perform...
def _calc_prob_from_ldr(prob): """This is the most reliable proxy for insects.""" return prob['z'] * prob['temp_loose'] * prob['ldr']
def calc_temperature_factor(hvac_control): """ Temperature Factor Equation Notes: -------- The reduction in yield caused by over heating or freezing of the grow area, especially if the farm is uncontrolled by hvac or other systems If no hvac control, preliminary value...
def union_list(cmp_lists): """ Get the two or multiple lists' union. Support one empty list. :param cmp_lists: A list of will do union calculate lists. It must have two list at least. :return: result: The result of the lists union. """ result = list(set().union(*cmp_lists)) return result
def first_half(dayinput): """ first half solver: """ lines = dayinput.split(' ') lines = [int(i) for i in lines] states = set() count = 0 while ''.join([str(i) for i in lines]) not in states: max_n = max(lines) index_max = lines.index(max_n) index = index_max + 1 ...
def create_list_stmts(list_graphs): """ Create a unique list of statements (strings) from a list of graphs in which statements are attributes of edges :param list_graphs: list of context-graphs (nodes = ids, edges = statements) :return: list_stmts: a unique list of statements (strings) """ list_...
def make_quippy_config(config): """Generate the quippy descriptor argument string.""" # doing this here to make the f-string slightly less horrible cutoff = config["cutoff"] l_max = config["l_max"] n_max = config["n_max"] sigma = config["sigma"] elems = config["elems"] species = " ".jo...
def check_syntax(code): """Return True if syntax is okay.""" try: return compile(code, '<string>', 'exec', dont_inherit=True) except (SyntaxError, TypeError, ValueError): return False
def ord_modulo (a, n): """ Compute the order of a modulo n. Computes the order of rational int a modulo rational int n. """ prod = a % n for count in range (1, n): if prod == 1: return count else: prod = (a * prod) % n return "Not rel...
def line(x, a, b): """Linear model - used in fitting.""" return a*x + b
def heuristic_score(ir_score, gp_score, lp_score, urlparams): """ A formula to combine IR score given by Elasticsearch and PagePop scores given by page popularity algorithm. Arithmetics is black art, it can only improve via manually testing queries, and user feedback. Currently its a simple weighted...
def is_reference(candidate): """ Checks if provided value is Deployment Manager reference string. """ return candidate.strip().startswith('$(ref.')
def to_list(ls): """ Converts ``ls`` to list if it is a tuple, or wraps ``ls`` into a list if it is not a list already """ if isinstance(ls, (list, tuple)): return list(ls) else: return [ls]
def format_metric(metric: float) -> str: """ Returns a readable string from the given Dice or loss function value, rounded to 3 digits. """ return "{:0.3f}".format(metric)
def greet(greeting, name): """ greet :param greeting: :param name: :return: """ return '{}, {}!'.format(greeting, name)
def filter_everyone(text): """Removes mentionable instances of @everyone and @here.""" return text.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere')
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ cache = {} if len(nums) <= 1: return [] for ind in range(len(nums)): if (target - nums[ind]) in cache: return [cache[target - nums[ind]], ind] cache[nums[i...
def job_health_check(value: int): """ Check health by value according to: https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/HealthReport.java and output the corresponding icon """ if value >= 80: return ":sunny:" elif 79 <= value <= 39: return "...