content
stringlengths
42
6.51k
def construct_url(*components): """Concetenate strings to URL.""" separator = '/' url = separator.join(components) return url
def blob_name(i): """ Implements legacy schema for blobs naming: 0-th blob is called 'weights' 1-th blob is called 'biases' then, next blobs are called according to the new default schema with 'custom_' prefix: custom_2, custom_3 and so on. """ predefined_names = ['weights', 'biases'] if i < len(predefined_names): return predefined_names[i] else: return 'custom_{}'.format(i)
def func_exp(x, a, b, c): """Fit an exponential function.""" return a * x + b * x ** 2 + c
def count_words(text): """ Counts the number of words in a text :param text: The text you want to count the words in :return: The number of words in the text. """ text = text.split() return len(text)
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ res = "" n = 0 for i in s: if i not in res: res = res + i else: indexofi = res.find(i) res = res[indexofi+1::] + i k = len(res) if k > n: n = k print(res) return n
def _get_movie_from_list(movies, sapo_title, sapo_description): """Get movie from list of movies to add if exists""" for m in movies: if m.sapo_title == sapo_title and m.sapo_description == sapo_description: return m return None
def update(event, context): """ Place your code to handle Update events here To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events. """ physical_resource_id = event["PhysicalResourceId"] response_data = {} return physical_resource_id, response_data
def hex_to_rgb(hexcode): """ Convert Hex code to RGB tuple """ return (int(hexcode[-6:-4], 16), int(hexcode[-4:-2], 16), int(hexcode[-2:], 16))
def key_parse(keystring): """ parse the keystring/keycontent into type,key,comment :param keystring: the content of a key in string format """ # comment section could have a space too keysegments = keystring.split(" ", 2) keystype = keysegments[0] key = None comment = None if len(keysegments) > 1: key = keysegments[1] if len(keysegments) > 2: comment = keysegments[2] return (keystype, key, comment)
def _nint(str): """ Nearest integer, internal use. """ # return int(float(str)+0.5) x = float(str) if x >= 0: return int(x+0.5) else: return int(x-0.5)
def get_signed_headers(headers): """ Get signed headers. :param headers: input dictionary to be sorted. """ signed_headers = [] for header in headers: signed_headers.append(header.lower().strip()) return sorted(signed_headers)
def strConcat(strings : list) -> str: """Concatenate a list of string objects Parameters ---------- strings list of input strings to concatenate Returns ------- concatenated string """ return "".join(map(str, strings))
def pointer_pack(first, second): """Ex. pointer_pack(0xab, 0xcd) == 0xabcd""" return (first << 8) + second
def build_empty_list(size): """Build empty List. Args: size (int): Size. Returns: list: List of size with 'None' values. """ build = [] for _ in range(size): build.append(None) return build
def trim_txt(txt, limit=10000): """Trim a str if it is over n characters. Args: txt (:obj:`str`): String to trim. limit (:obj:`int`, optional): Number of characters to trim txt to. Defaults to: 10000. Returns: :obj:`str` """ trim_line = "\n... trimmed over {limit} characters".format(limit=limit) txt = txt[:limit] + trim_line if len(txt) > limit else txt return txt
def create_filename(file_name: str, extension: str) -> str: """ Replaces white spaces of the string with '-' and adds a '.' and the extension to the end. :param file_name: File name :param extension: File extension :return: str Transformed filename """ return file_name.replace(' ', '-') + '.' + extension
def linear_warmup_learning_rate(current_step, warmup_steps, base_lr, init_lr): """Construct the trainer of SpNas.""" lr_inc = (float(base_lr) - float(init_lr)) / float(warmup_steps) learning_rate = float(init_lr) + lr_inc * current_step return learning_rate
def delete_empty_values(d): """ removes empty values from a dictionary to prevent uneccessary metadata key transmission """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (delete_empty_values(v) for v in d) if v] return {k: v for k, v in ((k, delete_empty_values(v)) for k, v in d.items()) if v}
def k2j(k, E, nu, plane_stress=False): """ Convert fracture Parameters ---------- k: float E: float Young's modulus in GPa. nu: float Poisson's ratio plane_stress: bool True for plane stress (default) or False for plane strain condition. Returns ------- float """ if plane_stress: E = E / (1 - nu ** 2) return k ** 2 / E
def linear_search(alist, key): """ Return index of key in alist . Return -1 if key not present.""" for i in range(len(alist)): if alist[i] == key: return i return -1
def kth_ugly_number(k): """ Find kth ugly number :param k: given k :type k: int :return: kth ugly number :rtype: int """ # list of ugly numbers ugly_numbers = [0] * k # 1 is the first ugly number ugly_numbers[0] = 1 # indices of multiplier i_2 = i_3 = i_5 = 0 # value of pointer num_2, num_3, num_5 = 2, 3, 5 # start loop to find value from ugly[1] to ugly[n] for i in range(1, k): # choose the min value of all available multiples ugly_numbers[i] = min(num_2, num_3, num_5) # increment the value of index accordingly if ugly_numbers[i] == num_2: i_2 += 1 num_2 = ugly_numbers[i_2] * 2 if ugly_numbers[i] == num_3: i_3 += 1 num_3 = ugly_numbers[i_3] * 3 if ugly_numbers[i] == num_5: i_5 += 1 num_5 = ugly_numbers[i_5] * 5 # return ugly[n] value return ugly_numbers[-1]
def channel_frequency(channel, frequency): """ Takes a WiFi channel and frequency value and if one of them is None, derives it from the other. """ new_channel = channel new_frequency = frequency if (frequency is None and channel is not None): if 0 < channel < 14: # 2.4 GHz band new_frequency = (channel * 5) + 2407 elif channel == 14: new_frequency = 2484 elif 14 < channel < 186: # 5 GHz band, incl. UNII4 new_frequency = (channel * 5) + 5000 elif 185 < channel < 200: # 4.9 GHz band new_frequency = (channel * 5) + 4000 elif (frequency is not None and channel is None): if 2411 < frequency < 2473: # 2.4 GHz band new_channel = (frequency - 2407) // 5 elif frequency == 2484: new_channel = 14 elif 4914 < frequency < 4996: # 4.9 GHz band new_channel = (frequency - 4000) // 5 elif 5074 < frequency < 5926: # 5 GHz band, incl. UNII4 new_channel = (frequency - 5000) // 5 return (new_channel, new_frequency)
def nest(dict_in, delim="__"): """Nests the input dict by splitting keys (opposite of flatten above)""" # We will loop through all keys first, and keep track of any first-level keys # that will require a recursive nest call. 'renest' stores these keys output, renest = {}, [] for key in dict_in: if delim not in key: output[key] = dict_in[key] continue loc = key.split(delim, 1) if loc[0] not in output: output[loc[0]] = {} # Uniquely add the key to the subdictionary we want to renest renest.append(loc[0]) output[loc[0]][loc[1]] = dict_in[key] # Renest all higher-level dictionaries for renest_key in renest: output[renest_key] = nest(output[renest_key]) return output
def reform(data): """Turn a grid into raw pixels""" new_data = b"" for all_ in data: for cols in all_: new_data += bytes(cols) return new_data
def checkForRequiredField(form, *fields): """Check if all required fields are available""" for f in fields: if(len(form[f].strip()) == 0): return False return True
def all_subarray(flag=True): """When `flag` is True, mark this constraint as applying to all SUBARRAY forms, including full frame, as long as SUBARRAY is defined. Returns "A" or False. >>> all_subarray(True) 'A' >>> all_subarray(False) False """ return "A" if flag else False
def filter_niftis(candidates): """ Takes a list and returns all items that contain the extensions '.nii' or '.nii.gz'. """ candidates = list(filter(lambda x: 'nii.gz' == '.'.join(x.split('.')[1:]) or 'nii' == '.'.join(x.split('.')[1:]), candidates)) return candidates
def SetFieldValue(regValue, lsb, fsize, fieldValue): """ An internal utility function to assign a field value to a register value. Perform range check on fieldValue using fsize. :type regValue: ``int`` or ``long`` :param regValue: The value of the register to parse :type lsb: ``int`` :param lsb: The least significant bit of the field :type fsize: ``int`` :param fsize: The size of the field in bits :type fieldValue: ``int`` :param fieldValue: The new field value :rtype: ``int`` or ``long`` :return: The new register value """ if (-1 << fsize) & fieldValue: raise ValueError("field value '{}' exceeds range of {} bits".format(fieldValue, fsize)) msb = lsb + fsize mask = ~((pow(2, msb) - 1) & ~(pow(2, lsb) - 1)) return (regValue & mask) | (fieldValue << lsb)
def _get_alias(full_or_partial_id): """ Returns the alias from a full or partial id Parameters ---------- full_or_partial_id: str Returns ------- str """ # Note that this works for identifiers of all types currently described in the spec, i.e.: # 1. did:factom:f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b#management-2 # 2. did:factom:mainnet:f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b#management-2 # 2. #inbox # 3. management-1 # The function will return management-2, inbox and management-1, respectively return full_or_partial_id.split("#")[-1]
def is_hexstring(string): """ Determines if a string is a hexstring. :param Union[ByteString, str] string: A string. :return: Whether the string's length is even and all of its characters are in [0-9a-fA-f]. """ if isinstance(string, str): string = string.encode() return not len(string) % 2 and all( 0x30 <= c <= 0x39 or 0x61 <= c <= 0x66 for c in string.lower() )
def frame_attrs_from_set(frame_set): """ A `dict` of all the attributes of all frame classes in this `TransformGraph`. Broken out of the class so this can be called on a temporary frame set to validate new additions to the transform graph before actually adding them. """ result = {} for frame_cls in frame_set: result.update(frame_cls.frame_attributes) return result
def deep_merge(base, changes): """ Create a copy of ``base`` dict and recursively merges the ``changes`` dict. Returns merged dict. :type base: dict :param base: The base dictionary for the merge :type changes: dict :param changes: The dictionary to merge into the base one :return: The merged ``result`` dict """ def merge(result, changes): for k, v in changes.items(): if not isinstance(v, dict): result[k] = v else: if k not in result or not isinstance(result[k], dict): result[k] = v.copy() else: result[k] = result[k].copy() merge(result[k], changes[k]) result = base.copy() merge(result, changes) return result
def results_list_to_tsv(results): """ Format a list of SearchResults into a TSV (Tab Separated Values) string. :param results: a list of SearchResults :type results: list[sr_parser.SearchResult] :return: string in TSV format :rtype: str """ results_tab_separated = [str(res) for res in results] results_str = '\n'.join(results_tab_separated) return results_str
def como_mutable(matriz): """Obtener una copia mutable de `matriz`.""" return [list(fila) for fila in matriz]
def merge(arrayA, arrayB, k): """ As A has enough buffer to store all numbers of B, we need to use k to indicate the end of A. i is used to indicate the tail of A's unsorted numbers. j is used to indicate the tail of B's unsorted numbers. tail is the tail of the result. """ N = len(arrayA) i = k - 1 j = len(arrayB) - 1 tail = N - 1 while i >= 0 and j >= 0: if arrayA[i] > arrayB[j]: arrayA[tail] = arrayA[i] i -= 1 else: arrayA[tail] = arrayB[j] j -= 1 tail -= 1 if i < 0 and j < 0: return arrayA[-(len(arrayB) + k):] if i < 0 and j >= 0: arrayA[tail - j: tail + 1] = arrayB[:j+1] return arrayA[-(len(arrayB) + k):] if i >= 0 and j < 0: arrayA[tail - i: tail + 1] = arrayA[:i + 1] return arrayA[-(len(arrayB) + k):]
def bits2positions(bits): """Converts an integer in the range 0 <= bits < 2**61 to a list of integers in the range 0 through 60 inclusive indicating the positions of the nonzero bits. Args: bits: int. An integer in the range 0 <= bits < 2 ** 61 Returns: A list of integers in the range 0 though 60 inclusive. """ return list(i for i in range(61) if (2 ** i) & bits > 0)
def isSorted(lyst): """ Return whether the argument lyst is in non-decreasing order. """ for i in range(1, len(lyst)): if lyst[i] < lyst[i-1]: return False return True
def gcd(a, b): """Find greatest common divisor.""" while b > 0: a, b = b, a % b return a
def split_args_extra(args): """ Separate main args from auxiliary ones. """ try: i = args.index('--') return args[:i], args[i + 1:] except ValueError: return args, []
def worker_exploration(worker_index, num_workers): """ Computes an exploration value for a worker Args: worker_index (int): This worker's integer index. num_workers (int): Total number of workers. Returns: float: Constant epsilon value to use. """ exponent = (1.0 + worker_index / float(num_workers - 1) * 7) return 0.4 ** exponent
def _pad_norm_assert_noshape(outputs): """Assert Masked BN/GN w/o spatial shape returns None shape.""" outputs, spatial_shape = outputs assert spatial_shape is None return outputs, []
def _interpolate_target(bin_edges, y_vals, idx, target): """Helper to identify when a function y that has been discretized hits value target. idx is the first index where y is greater than the target """ if idx == 0: y_1 = 0. else: y_1 = y_vals[idx - 1] y_2 = y_vals[idx] edge_1 = bin_edges[idx] edge_2 = bin_edges[idx + 1] frac = (target - y_1) / (y_2 - y_1) x = edge_1 + frac * (edge_2 - edge_1) return x
def simple_logged_task(a, b, c): # pylint: disable=invalid-name """ This task gets logged """ return a + b + c
def is_same_class_or_subclass(target, main_class): """ checks if target is the same class or a subclass of main_class :param target: :param main_class: :return: """ return isinstance(target, main_class) or issubclass(target.__class__, main_class)
def prune_species(components): """Remove any duplicates and set stoichiometries""" unique_names = set(species.name for species in components) unique_species = [] for name in unique_names: identical_species = [s for s in components if s.name == name] # Add this species only once species = identical_species[0] # The order in this species is the number of times it appears # as either a reactant or product species.stoichiometry = len(identical_species) unique_species.append(species) # Sort the components alphabetically by name return sorted(unique_species, key=lambda s: s.name)
def debian_package_install(packages, clean_package_cache=True): """Jinja utility method for building debian-based package install command. apt-get is not capable of installing .deb files from a URL and the template logic to construct a series of steps to install regular packages from apt repos as well as .deb files that need to be downloaded, manually installed, and cleaned up is complicated. This method will construct the proper string required to install all packages in a way that's a bit easier to follow. :param packages: a list of strings that are either packages to install from an apt repo, or URLs to .deb files :type packages: list :returns: string suitable to provide to RUN command in a Dockerfile that will install the given packages :rtype: string """ cmds = [] # divide the list into two groups, one for regular packages and one for # URL packages reg_packages, url_packages = [], [] for package in packages: if package.startswith('http'): url_packages.append(package) else: reg_packages.append(package) # handle the apt-get install if reg_packages: cmds.append('apt-get update') cmds.append('apt-get -y install --no-install-recommends {}'.format( ' '.join(reg_packages) )) if clean_package_cache: cmds.append('apt-get clean') cmds.append('rm -rf /var/lib/apt/lists/*') # handle URL packages for url in url_packages: # the path portion should be the file name name = url[url.rfind('/') + 1:] cmds.extend([ 'curl --location {} -o {}'.format(url, name), 'dpkg -i {}'.format(name), 'rm -rf {}'.format(name), ]) # return the list of commands return ' && '.join(cmds)
def _nh(name): """ @return: Returns a named hex regex """ return '(?P<%s>[0-9a-f]+)' % name
def unique(seq): """use this instead of list(set()) to preserve order of the original list. Thanks to Stackoverflow: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order""" seen = set() seen_add = seen.add return [ x for x in seq if not (x in seen or seen_add(x)) ]
def set(byte: int, index: int) -> int: """Set bit at index to 1.""" assert 0 <= byte <= 255 assert 0 <= index <= 7 return byte | (1 << index)
def check_unexpected(lines, recipes): """Check for unexpected output lines from dry run""" unexpected = [] for line in lines.splitlines(): if 'Running task' in line: for recipe in recipes: if recipe in line: break else: line = line.split('Running', 1)[-1] if 'do_rm_work' not in line: unexpected.append(line.rstrip()) elif 'Running setscene' in line: unexpected.append(line.rstrip()) return unexpected
def _plugin_import(plug): """ Tests to see if a module is available """ import sys if sys.version_info >= (3, 4): from importlib import util plug_spec = util.find_spec(plug) else: import pkgutil plug_spec = pkgutil.find_loader(plug) if plug_spec is None: return False else: return True
def search(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums : return -1 left = 0 right = len(nums) - 1 while left <= right : mid = (left + right) >> 1 if nums[mid] == target : return mid if nums[0] <= nums[mid] : if nums[0] <= target < nums[mid] : right = mid - 1 else : left = mid + 1 else : if nums[mid] < target <= nums[len(nums) - 1] : left = mid + 1 else : right = mid -1 return -1
def find_all_indexes(text, pattern): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # instead of starting at 0, I can start where i found patter and start at the index + 1 index = 0 window = len(pattern) indexes = [] if pattern == '': # for empty pattern creates list of indecies of the text return list(range(len(text))) else: # greater or equals to catch the patter if it's last index while index <= len(text) - 1: if pattern == text[index:window + index]: indexes.append(index) index += 1 return indexes
def has_all_tags(span, tags): """ Tests if `tags`'s are all in a certain trace span """ return tags.items() <= span.get("tags").items()
def set_format(data): """Set the data in the requested format. (1) Devide into 8 bits. (2) Convert to the format 'XXXX XXXX'. """ n = len(data) data_list = [] for i in range(0, n, 8): data_temp = ''.join(data[i:i+4]) + ' ' data_temp = data_temp + ''.join(data[i+4:i+8]) data_list.append(data_temp) return data_list
def IsQACup(cup): """ Given inner cup checks if it is QA or a clinical one Parameters ---------- cup: string Inner cup series returns: boolean True if QA, False otherwise """ return cup == "Q"
def get_rolled_fn(logfile, rotations): """Helper to get filename of |logfile| after |rotations| log rotations.""" return '%s.%d' % (logfile, rotations)
def roundto(val,decimal:int=8,force:bool=False): """ Better round function which works with complex numbers and lists val:Any; value to round decimal:int>=0; decimal places to round to force:bool; force value rounding as complex number rounding """ if isinstance(val,complex) or force: return complex(round(val.real,decimal),round(val.imag,decimal)) elif isinstance(val,(int,float)): return round(val,decimal) elif isinstance(val,list): return [roundto(value,decimal) for value in val] elif type(val).__name__ == 'null': return val else: try: if val.__name__ == "Matrix": return round(val,decimal) else: raise Exception except: raise TypeError(f"Can't round {val}.")
def check_ship_direction(head, tile): """ Return whether ship is placed horizontally ("H") or vertically ("V") """ h_c, h_r = head[0], head[1] t_c, t_r = tile[0], tile[1] if h_r == t_r: return "H" elif h_c == t_c: return "V" else: raise ValueError( "You can only place your ship horizontally or vertically.")
def MakeDeclarationString(params): """Given a list of (name, type, vectorSize) parameters, make a C-style parameter declaration string. Ex return: 'GLuint index, GLfloat x, GLfloat y, GLfloat z'. """ n = len(params) if n == 0: return 'void' else: result = '' i = 1 for (name, type, vecSize) in params: result = result + type + ' ' + name if i < n: result = result + ', ' i += 1 #endfor return result #endif
def weeks_elapsed(day1: int, day2: int) -> int: """ def weeks_elapsed(day1, day2): (int, int) -> int day1 and day2 are days in the same year. Return the number of full weeks that have elapsed between the two days. >>> weeks_elapsed(3, 20) 2 >>> weeks_elapsed(20, 3) 2 >>> weeks_elapsed(8, 5) >>> weeks_elapsed(40, 61) """ max_day = max(day1, day2) min_day = min(day1, day2) days_in_between = max_day - min_day return days_in_between // 7
def _underline(text): """Format a string by overstriking.""" return ''.join('_' + '\b' + ch for ch in text)
def unicoded(s:str)->str: """ Recursively finds the first occurance of \\u and either corrects or keeps it. Decision is based on amount of backslashes: if the printed version has even, then they are all escape-character sequences. On very long lines, recursion limits occur. Reverting to loop-based solution. """ def counter(i:int)->bool: """If, right before s[i] (which will be a start index for \\u) there're an odd number of \\, ie. u is not escaped, will return False, indicating that we should move on. """ count = True for ch in s[i-1::-1]: if(ch=='\\'): count = not count else: break return count # We can't use `replace` because as unlikely as it may be, # there's no guarantee that we didn't write an unicode in original # file. Therefore escape-counting is always needed. t_loc = 0 loc = s.find('\\u') corrected = '' while(loc>0): corrected += s[t_loc:loc] if(counter(loc)): t_loc = loc + 6 corrected += eval("'{}'".format(s[loc:t_loc])) else: t_loc = loc + 2 corrected += s[loc:t_loc] loc = s.find('\\u', t_loc) corrected += s[t_loc:] return corrected
def benchmark_select_skl_metric(metric: str) -> str: """ Convert `MuyGPyS` metric names to `scikit-learn` equivalents. Args: metric: The `MuyGPyS` name of the metric. Returns: The equivalent `scikit-learn` name. Raises: ValueError: Any value other than `"l2"` or `"F2"` will produce an error. """ if metric == "l2": return "l2" elif metric == "F2": return "sqeuclidean" else: raise ValueError(f"Metric {metric} is not supported!")
def fetch_image_url(item, key="images"): """Fetch image url.""" try: return item.get(key, [])[0].get("url") except IndexError: return None
def try_helper(f, arg, exc=AttributeError, default=''): """Helper for easy nullable access""" try: return f(arg) except exc: return default
def dimensionalize_pressure(p, config_dict): """ Function to dimensionalize pressure Function 'dimensionalize_pressure' retrurns the pressures values dimensionalize accorind to data from the SU2 configuration file Args: p (list): Pressure values config_dict (dict): SU2 cfg file dictionary to dimensionalize non-dimensional output Returns: p (list): New pressure values """ ref_dim = config_dict.get('REF_DIMENSIONALIZATION', 'DIMENSIONAL') p_inf = float(config_dict.get('FREESTREAM_PRESSURE', 101325.0)) gamma = float(config_dict.get('GAMMA_VALUE', 1.4)) ma = float(config_dict.get('MACH_NUMBER', 0.78)) if ref_dim == 'DIMENSIONAL': return p - p_inf elif ref_dim == 'FREESTREAM_PRESS_EQ_ONE': return (p - 1) * p_inf elif ref_dim == 'FREESTREAM_VEL_EQ_MACH': return (p * gamma - 1) * p_inf elif ref_dim == 'FREESTREAM_VEL_EQ_ONE': return (p * gamma * ma**2 - 1) * p_inf
def greet2(name:str): """Stack example function.""" print("How are you, " + name + "?") return None
def _num_extreme_words(words, extreme_words, average=True): """ Count the number of common words Inputs: words (list of string): to be checked extreme_words (set of string or dict[string] -> float): common words set Returns: tuple or list of int: # of extreme words in each extreme polars """ if not isinstance(extreme_words, (dict, set)): raise Exception('[ERROR] common/rare word list should be set!') elif isinstance(extreme_words, list): extreme_words = set(extreme_words) if not len(extreme_words) > 0: raise Exception('[ERROR] no words found!!') res = 0 for word in words: if word in extreme_words: res += 1 if average: res /= len(extreme_words) return res
def unshuffle(l, order): """ unshuffles list given shuffled index """ l_out = [0] * len(l) for i, j in enumerate(order): l_out[j] = l[i] return l_out
def iso7816_4_unpad(padded): """Removes ISO 7816-4 padding""" msg_end = padded.rfind(b'\x80') if msg_end == -1 or any(x for x in padded[msg_end+1:]): raise ValueError(f'Invalid padding') return padded[:msg_end]
def parse_db_result(result): """Returns a Rate object from the data from the database""" return {'from':result[1], 'to':result[2], 'date':result[0], 'rate':result[3]}
def tau_h(R0, vsc): """Arnett 1982 expansion timescale, in days R0: initial radius in cm vsc: scaling velocity in cm/s """ return (R0/vsc) / 86400.0
def revoke_role(role, target): """Helper method to construct SQL: revoke privilege.""" return f"REVOKE {role} from {target};"
def bearer_auth(req, authn): """ Pick out the access token, either in HTTP_Authorization header or in request body. :param req: :param authn: :return: """ try: return req["access_token"] except KeyError: assert authn.startswith("Bearer ") return authn[7:]
def linspace(minimum, maximum, count): """a lazy reimplementation of linspace because I often need linspace but I'm too lazy to import a module that would provide it. NB this version includes both end-points, which might make the step not what you expect. """ if maximum <= minimum: raise ValueError("minimum must be less than maximum") if count <= 1: raise ValueError("count must be at least 2") step = (maximum - minimum) / (count - 1) # step should be a float return [ minimum + step * x for x in range(count)]
def _min_max(x, xmin, xmax): """ Defines a function which enforces a minimum and maximum value. Input: x, the value to check. Input: xmin, the minumum value. Input: xmax, the maximum value. Output: Either x, xmin or xmax, depending. """ # Check if x is less than the minimum. If so, return the minimum. if x < xmin: return xmin # Check if x is greater than the maximum. If so, return the maximum. elif x > xmax: return xmax # Otherwise, just return x. And weep for the future. else: return x
def convert_box(box): """[x, y, w, h] to x1, y1, x2, y2.""" x, y, w, h = box return [x, y, x + w, y + h]
def find_snippet(text, start, end, skip=(0, 0)): """Find snippet in text :param text: Text to search in :type text: str :param start: Where to start grabbing text :type start: str :param end: Where to stop grabbing text and return :type end: str :param skip: Number of character to trim in front and behind gragbbed text :type skip: tuple :return: Snippet found in the text :rtype: str """ start_index = text.find(start) if start_index == -1: return start_index end = text.find(end, start_index) return text[start_index + len(start) + skip[0]:end - skip[1]]
def launch_piece_letter_to_number(letters): """Convert 24 upper case letter 3-letter code to integer, omitting I (eye) and O (oh) from the alphabet. The TLE standard is 24 upper case letter 3-letter code, omitting I (eye) and O (oh) from the alphabet, with no representation for zero. The 1st piece of a launch is denoted by 'A', and subsequent pieces 'B', 'C', 'D'... 'Z'. The 25th (24*1 + 1) piece would be denoted by 'AA', and subsequent pieces 'AB', 'AC'... 'AZ', 'BA', BB', 'BC',... 'ZZ'. The 601st (24*24 + 24 + 1) piece would be denoted by 'AAA', and subsequent pieces, 'AAB', 'AAC'... AZZ', 'BAA', 'BAB'... 'ZZZ' This allows for a maximum of 24^3 + 24^2 + 24 pieces, or 14424 pieces for a single launch (ZZZ) Receives """ letters = letters.strip() # Omit I (eye) and O (oh) dictionary = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8, 'J':9,'K':10,'L':11,'M':12,'N':13,'P':14,'Q':15,'R':16,'S':17, 'T':18,'U':19,'V':20,'W':21,'X':22,'Y':23,'Z':24} base = len(dictionary) strlen = len(letters) if (9 <= strlen <= 11): # Handle the case where we got passed the full international_designation letters = letters[8:].strip() strlen = len(letters) if strlen == 1: number = dictionary[letters] elif strlen == 2: first_number = dictionary[letters[0]] second_number = dictionary[letters[1]] number = (first_number * base) + second_number elif strlen == 3: first_number = dictionary[letters[0]] second_number = dictionary[letters[1]] third_number = dictionary[letters[2]] number = (first_number * base * base) + (second_number * base) + third_number else: # No valid data received return False return number
def set(d, *item): """Set a value in the nested dict `d`. Any subdictionaries created in this process are of the same type as `d`. Note that this implies the requirement that `d`s type have a zero-argument constructor. """ *intermediate_keys, last_key, value = item create_intermediate_dicts = False cls = type(d) for k in intermediate_keys: if create_intermediate_dicts: d[k] = d = cls() continue try: d = d[k] except KeyError: d[k] = d = cls() create_intermediate_dicts = True d[last_key] = value return value
def prepend_list(base_word: str, prepend: list, separator: str='') -> list: """Inserts list:prepend at beginning of str:base_word with default str:separator='', returns a list """ return [f'{pre}{separator}{base_word}' for pre in prepend]
def switch_testing(fuel_switches, service_switches, capacity_switches): """Test if swithes defined for same enduse Arguments --------- fuel_switches : list Switches service_switches : list Switches capacity_switches : list Switches """ all_switches_incl_sectors = {} enduses_service_switch = set([]) for switch in service_switches: enduses_service_switch.add(switch.enduse) # Collect all enduses and affected sectors if switch.enduse not in all_switches_incl_sectors: all_switches_incl_sectors[switch.enduse] = set([]) if not switch.sector: all_switches_incl_sectors[switch.enduse] = None else: all_switches_incl_sectors[switch.enduse].add(switch.sector) else: if not switch.sector: pass else: all_switches_incl_sectors[switch.enduse].add(switch.sector) enduses_capacity_switch = set([]) for switch in capacity_switches: enduses_capacity_switch.add(switch.enduse) # Collect all enduses and affected sectors if switch.enduse not in all_switches_incl_sectors: all_switches_incl_sectors[switch.enduse] = set([]) if not switch.sector: all_switches_incl_sectors[switch.enduse] = None else: all_switches_incl_sectors[switch.enduse].add(switch.sector) else: if not switch.sector: pass else: all_switches_incl_sectors[switch.enduse].add(switch.sector) enduses_service_switch = list(enduses_service_switch) enduses_capacity_switch = list(enduses_capacity_switch) for enduse in all_switches_incl_sectors: if all_switches_incl_sectors[enduse] != None: all_switches_incl_sectors[enduse] = list(all_switches_incl_sectors[enduse]) return all_switches_incl_sectors
def min_max(num1, num2) -> tuple: """ Gets the min and max of the provided values :param num1: first number :param num2: second number :return: -> (min, max) """ return (min(num1, num2), max(num1, num2))
def prob6(limit=100): """ The sum of the squares of the first ten natural numbers is, 1**2 + 2**2 + ... + 10**2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)**2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ a = 0 b = 0 for i in range(1, limit + 1): a += i ** 2 b += i return b ** 2 - a
def manhattan_distance(a, b): """ Return the Manhattan distance between points A and B (both tuples). """ return abs(a[0] - b[0]) + abs(a[1] - b[1])
def _reverse_table(table): """Return value: key for dictionary.""" return {value: key for (key, value) in table.items()}
def check_rows(board): """ list -> bool This function checks if every row has different numbers and returns True is yes, and False if not. >>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****", \ " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"]) True >>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 4****", \ " 9 5 ", " 6 83 *", "1 1 **", " 8 2***", " 2 ****"]) False """ for row in board: numbers = [] for elem in row: if elem == '*' or elem == ' ': continue else: if elem in numbers: return False numbers.append(elem) return True
def zeemanLande(S, N, J): """ Return the Zeeman splitting factor in Hz/microG """ if (J == 0): gJ = 0.0 else: gJ = (J*(J+1)+S*(S+1)-N*(N+1)) / (J*(J+1)) return gJ
def index(fks, id): """Looks for the id on fks, fks is an array of arrays, each array has on [1] the id of the class in a dia diagram. When not present returns None, else it returns the position of the class with id on fks""" for i, j in fks.items(): if fks[i][1] == id: return i return None
def linear_mass(t, ttrunc, m): """Integrate (1-m*(a-ttrunc)) da from a=ttrunc to a=t """ tt = t - ttrunc return ((tt + ttrunc * m * tt) - m/2. * (t**2 - ttrunc**2))
def join_chunks(chunks): """empty all chunks out of their sub-lists to be split apart again by split_chunks(). this is because chunks now looks like this [[t,t,t],[t,t],[f,f,f,][t]]""" return [item for sublist in chunks for item in sublist]
def optimize_highlight(lst): """Optimize a highlight list (s1, n1), ... by combining parts that have the same color. """ if len(lst) == 0: return lst else: prev = lst[0] new_lst = [] for s, n in lst[1:]: if s.strip() == "" or prev[1] == n: # Combine with previous: prev = (prev[0] + s, prev[1]) else: new_lst.append(prev) prev = (s, n) new_lst.append(prev) return new_lst
def getThreshhold(g: int, n: int, alpha: float = 0.06, d=0.1, zeta=1) -> float: """ `returns` minimum vector movement threshold Paremeters ---------- `g`: current generation/iteration `n`: total number of iterations `alpha`: fraction of the main space diagonal `d`: initial value of threshold `zeta`: controls the decay rate of the threshold """ if (alpha < 0 or alpha > 1): raise ValueError('Invalid alpha') return alpha * d * ((n - g)/n) ** zeta
def create_table(order:int) -> str: """ create a table to store polynomial root information """ query = "CREATE TABLE IF NOT EXISTS polynomials (id text primary key, " params = ["root{} int, iroot{} int".format(root, root) for root in range(order)] return query + ', '.join(params) + ");"
def build_suffix_tree(text): """ Build a suffix tree of the string text and return a list with all of the labels of its edges (the corresponding substrings of the text) in any order. """ result = [] # Implement this function yourself return result
def add_versions(nodes, versions): """ In Dutch rechtspraak.nl data, an version can have an annotation. :param nodes: list of node objects :param versions: list of versions :return: list of nodes """ count_version = {} count_annotation = {} for item in versions: id0 = item['id'] val = item['hasVersion'] count_version[id0] = count_version.get(id0, 0) + 1 if val.lower().find('met annotatie') >= 0: count_annotation[id0] = count_annotation.get(id0, 0) + 1 for node in nodes: node['count_version'] = count_version.get(node['id'], 0) node['count_annotation'] = count_annotation.get(node['id'], 0) return nodes
def is_affine_st(A, tol=1e-10): """ True if Affine transform has scale and translation components only. """ (_, wx, _, wy, _, _, *_) = A return abs(wx) < tol and abs(wy) < tol
def RLcoeffs(index_k, index_j, alpha): """Calculates coefficients for the RL differintegral operator. see Baleanu, D., Diethelm, K., Scalas, E., and Trujillo, J.J. (2012). Fractional Calculus: Models and Numerical Methods. World Scientific. """ if index_j == 0: return ((index_k-1)**(1-alpha)-(index_k+alpha-1)*index_k**-alpha) elif index_j == index_k: return 1 else: return ((index_k-index_j+1)**(1-alpha)+(index_k-index_j-1)**(1-alpha)-2*(index_k-index_j)**(1-alpha))
def update_connections(existing, new): """ This will update the connections dictonary """ for new_key in new.keys(): if new_key not in existing.keys(): existing[new_key] = new[new_key] else: existing[new_key] += new[new_key] return existing