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 len(l) > 0
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`` """ return [obj] if not isinstance(obj, list) else 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 degree + control_points_size + 1: return False # Check ascending order prev_knot = knot_vector[0] for knot in knot_vector: if prev_knot > knot: return False prev_knot = knot return True
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 users added # Determine if account should be locked approved = True return approved
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_lambda.append(argname) return "[%s](%s){ return %s->%s(%s); }" % ( ("&" if capture else ""), ", ".join(args_lambda_sig), instance_ptr, func["name"], ", ".join(args_lambda))
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 elif isinstance(file, int): return False split_url = file.split("://", 1) if len(split_url) == 2 and split_url[0].lower() != "file": return True return False
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_errors': [], 'dtd_errors': []}) """ if status[0] is True: return 'valid' if status[0] is False: return 'invalid' return 'undefined'
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("\\", "\\\\").replace("'", "\\'").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. :rtype: ``str`` """ assert isinstance(text,str), '%s is not a string' % text return text.capitalize()
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(pad) > 1: return orig orig_length = len(orig) if orig_length >= new_length: return orig return (pad * (new_length - orig_length)) + orig
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. """ return ( length // num_splits if length % num_splits == 0 else length // num_splits + 1 )
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., Miller, J. R., Noland, T. L., Mohammed, \ G. H., Sampson, P. H. 2001. Scaling-up and model inversion methods \ with narrowband optical indices for chlorophyll content estimation in \ closed forest canopies with hyperspectral data. IEEE Transactions on \ Geoscience and Remote Sensing 39, 1491-1507. doi:10.1109/36.934080. """ NHI = (b11 - b3)/(b11 + b3) return NHI
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 error if the check returns false. :return: True if obj is a valid raw representation of mathematical vectors, False otherwise """ if isinstance(obj, (list, tuple)) and 1 < len(obj) < 4: return True else: if throwerr: raise TypeError("A given object is not an accepted representation" " of a vector (must be a Python list or tuple)") return False
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(s)): if s[i] == ':': colon = i + 1 path, file = s[:colon-1], s[colon:] if path and not ':' in path: path = path + ':' return path, file
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-bottom:1px inset black;border-top:1px inset black;padding:8px;font-size: 20px;">' + str( text) + '</div>' return raw_html
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 "higher" else: return 'lower'
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 = len(str) upper = 0 lower = 0 nums = 0 spec = 0 for el in str: if el.isupper(): upper += 1 if el.islower(): lower += 1 if el.isdigit(): nums += 1 spec = len_str - (upper + lower + nums) return [upper, lower, nums, spec]
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': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} dict_of_rna_cpm_base = {'A': 'U', 'U': 'A', 'C': 'G', 'G': 'C'} try: if is_dna: cpm_char = dict_of_dna_cpm_base[base_char] else: cpm_char = dict_of_rna_cpm_base[base_char] except KeyError: cpm_char = '' return cpm_char
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 mapping mapp = {} for q in range(i, j + 1): x = A[q] if x in mapp: mapp[x] += 1 else: mapp[x] = 1 # Empty if not mapp: return 0 # Equal number of keys; return the max if max(mapp.values()) == min(mapp.values()): return max(mapp.values()) # No equal return 0 max_size = 0 start = 0 end = 0 for i in range(len(A)): # both working # for j in range(len(A)-1, 1, -1): for j in range(i, len(A) - 1): cnt = has_equal(A, i, j) if cnt > 0 and cnt > max_size: max_size = cnt start = i end = j print("Start index: {}, end index: {}, array: {}".format(start, end, A[start:end + 1])) return True
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 dates to use as a filter :return: list of filenames from which to generate time series """ filtered_files = [] for filename in source_files: for date in target_dates: if date in filename: filtered_files.append(filename) break return filtered_files
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 the beginning of the input # The first character doesn't need to be checked - start with the second chk = 1 while chk < bound: # While the check lies within the specified bounds # If the check character matches the reference character, a failed match # on the next character can start checking on the character after the # reference character (because it's necessarily already matched the # reference character) if inp[chk] == inp[ref]: chk += 1 # Increment the check and the reference ref += 1 # After incrementing (so that the next set is logged), log the # reference character as the maximum prefix for the check character table[chk] = ref # If the characters don't match and we're not referencing the first # character in the input elif ref: # Drop the reference back to the maximum prefix for said reference to # continue checking there ref = table[ref] # If there's no match and we're at the beginning of the input, just # increment the check character else: chk += 1 # # return table
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: message: A string containing an SMS message Returns: The list of normalized words from the message. """ # *** START CODE HERE *** return message.lower().split() # *** END CODE HERE ***
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 class='bar' href='foo'". """ t, i, j = tag.strip("</>"), 0, 0 while j >= 0: i = string.find("<%s%s" % (t, (" "+attributes.strip()).rstrip()), i) j = string.find("</%s>" % t, i+1) opened, closed = string[i:j].count("<%s" % t), 1 while opened > closed and j >= 0: k = string.find("</%s>" % t, j+1) opened += string[j:k].count("<%s" % t) closed += 1 j = k if i < 0: return string if j < 0: return string[:i] string = string[:i] + string[j+len(t)+3:] return string
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() for dic in listOfDict: if isinstance(dic, dict): if len(dic.keys()) == 1 and "@id" in dic.keys(): newList.append(dic["@id"]) elif isinstance(dic, list): convertIDtoValueListRecur(dic) return newList
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([]) for j in range(len(h)+1): if i == j: d[0][j] = j elif j == 0: d[i][0] = i # computation for i in range(1, len(r)+1): for j in range(1, len(h)+1): if r[i-1] == h[j-1]: d[i][j] = d[i-1][j-1] else: substitution = d[i-1][j-1] + 1 insertion = d[i][j-1] + 1 deletion = d[i-1][j] + 1 d[i][j] = min(substitution, insertion, deletion) return d[len(r)][len(h)] / float(len(r))
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.replace(i, '') s = s.strip() return 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 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0: raise ValueError("Input vectors cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise if not 1 < len(vector1) <= 3 or not 1 < len(vector2) <= 3: raise ValueError("The input vectors should contain 2 or 3 elements") # Convert 2-D to 3-D, if necessary if len(vector1) == 2: v1 = [float(v) for v in vector1] + [0.0] else: v1 = vector1 if len(vector2) == 2: v2 = [float(v) for v in vector2] + [0.0] else: v2 = vector2 # Compute cross product vector_out = [(v1[1] * v2[2]) - (v1[2] * v2[1]), (v1[2] * v2[0]) - (v1[0] * v2[2]), (v1[0] * v2[1]) - (v1[1] * v2[0])] # Return the cross product of the input vectors return vector_out
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 crabs: current_fuel_sum += abs(align_position - crab_position) if current_fuel_sum < min_fuel_sum: min_fuel_sum = current_fuel_sum return min_fuel_sum
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) return (value_max, ind_max)
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, xmax), pbc_1d(y, ymax), pbc_1d(z, zmax), ] points_pbc.append(point) return points_pbc
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, but along the x-direction. xdescent values are currently ignored. *hd_list* : list of (width, xdescent) of boxes to be aligned. *sep* : spacing between boxes *height* : Intended total length. None if not used. *align* : align mode. 'baseline', 'top', 'bottom', or 'center'. """ if height is None: height = max([h for h, d in hd_list]) if align == "baseline": height_descent = max([h-d for h, d in hd_list]) descent = max([d for h, d in hd_list]) height = height_descent + descent offsets = [0. for h, d in hd_list] elif align in ["left","top"]: descent=0. offsets = [d for h, d in hd_list] elif align in ["right","bottom"]: descent=0. offsets = [height-h+d for h, d in hd_list] elif align == "center": descent=0. offsets = [(height-h)*.5+d for h, d in hd_list] else: raise ValueError("Unknown Align mode : %s" % (align,)) return height, descent, offsets
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: mass_ship (float): The new mass of the ship at timestep i. """ TIME_STEP = .1 mass_ship = dry_mass + wet_mass - mass_flow * TIME_STEP * i return mass_ship
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':'D'} reverse_complement = "".join( complement.get(base, base) for base in reversed(primer) ) return(reverse_complement)
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) 'Natasha' """ key_dict = {sec_name.casefold(): sec_name for sec_name in the_dict.keys()} if the_key.casefold() in key_dict.keys(): return the_dict.get(key_dict[the_key.casefold()]) else: return default
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 mu == 1: # E + S -> ES if states[0] > 0 and states[1] > 0: states[0] -= 1 states[1] -= 1 states[2] += 1 elif mu == 2: # ES -> E + S if states[2] > 0: states[0] += 1 states[1] += 1 states[2] -= 1 elif mu == 3: # ES -> E + P if states[2] > 0: states[0] += 1 states[2] -= 1 states[3] += 1 else: raise ValueError('Reaction mu = %d does not exist.' % mu) return states
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 not match the one entered.' else: message = 'Valid' return message
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)) :param bulge: A couple (2-tuple) indicating the first and last position of the bulge. :return: True if there is an overlap between the stem nucleotides and the bulge nucleotides. False otherwise """ for stem_part in stem: for part in stem_part: for bulge_part in bulge: if abs(bulge_part - part) == 1: return True return False
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: year = 'Unknown' return name, year
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 of a Gaussian) in the range 0.1 -100 pc. :param source_fwhm_parcsec: the full width at half max of a Gaussian background source :return: an appropriate grid size for finite-size background magnification computation """ grid_radius_arcsec = grid_size_scale * source_fwhm_parcsec ** power return grid_radius_arcsec
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 ba = bytearray() for _ in range(nbytes): ba.append(n & 0xff) n >>= 8 if minlen > 0 and len(ba) < minlen: # zero pad? ba.extend([0] * (minlen-len(ba))) return ba
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 """ final = [] for element in newList: if element not in initialList: final.append(element) return final
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 branch, file
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", "").replace("G", "").replace("B", "").replace("0", "", 1) else: # If the counter is of the Fxxx format keep all the numbers (F29G034 -> 29034) cpy = x.replace("F", "").replace("G", "").replace("B", "") return cpy
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]) + f"_{int(end)+1}" else: string += "_1" return string
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 axis. y1 : float. The coordinate of the second point on the y axis. x : float. A value in the interval (x0, x1). Returns ------- float. Is the interpolated or extrapolated value. Examples -------- - interpolation 1: (30, 3, 40, 5, 37) -> 4.4 - interpolation 2: (30, 3, 40, 5, 35) -> 4.0 """ return y0 + (y1 - y0) * ((x - x0) / (x1 - x0))
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 performed if pred is true. fn2: The callable to be performed if pred is false. Returns: Tensors returned by the call to either `fn1` or `fn2`. Raises: TypeError: if `fn1` or `fn2` is not callable. """ if not callable(fn1): raise TypeError('fn1 must be callable.') if not callable(fn2): raise TypeError('fn2 must be callable.') if pred: return fn1() else: return fn2()
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 set to 0.85. This should be assessed depending on climate, crop reqs and level of hvac control High: Med: Low: """ if hvac_control == "high": # If advanced hvac control then temperature factor is 1 tf = 1 else: tf = 0.85 return tf
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 states.add(''.join([str(i) for i in lines])) lines[index_max] = 0 count += 1 while max_n > 0: if index == len(lines): index = 0 lines[index] += 1 max_n -= 1 index += 1 return count
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_stmts = list() for G in list_graphs: edges_list = [e[2]['stmt'] for e in G.edges(data=True)] list_stmts += edges_list return list_stmts
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 = " ".join(map(str, elems)) quippy_config = f"soap cutoff={cutoff} l_max={l_max} n_max={n_max} atom_sigma={sigma} n_Z={len(elems)} Z={{{species}}} n_species={len(elems)} species_Z={{{species}}}" return quippy_config
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 relatively prime to n"
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 sum. Normally the more tokens in query the lower pagepop influence should be. However the more tokens given the more ES seems to diverge IR score. Thus we bypass 'number of tokens' for the moment todo: hardcode coefficient values (currently in url params) and todo: make local pagepop coeff: `lp_coeff` proportional to number of hits :param ir_score: Information Relevance score by Elasticsearch :param gp_score: Global popularity score for that domain :param lp_score: Local popularity score for that domain :return: final score :rtype: ``float`` """ lp_coeff = float(urlparams.get('lp', 0)) gp_coeff = float(urlparams.get('gp', 0)) ir_coeff = 1 - gp_coeff - lp_coeff ret = gp_score * gp_coeff + lp_score * lp_coeff + ir_score * ir_coeff # drag down the average score when the two scores diverge too much # pp = gp_coeff * gp_score # ir = ir_coeff * ir_score # ret = pp * ir / (pp + ir) # failed: too much of a penalty return ret
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[ind]] = ind
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 ":loud_with_rain:" else: return ":fire:"