content
stringlengths
42
6.51k
def extract_http_status_code_tag(trigger_tags, response): """ If the Lambda was triggered by API Gateway or ALB add the returned status code as a tag to the function execution span. """ is_http_trigger = trigger_tags and ( trigger_tags.get("function_trigger.event_source") == "api-gateway" ...
def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*',\ '*?????5', '*?????*', '*?????*', '*2*1***']) Fal...
def rlb(thing): """ Return thing with line breaks replaced by spaces """ return thing.replace("\r", " ").replace("\n", " ")
def _ensure_list(item): """ Ensures that the given item is a list. :param item: :return: """ if item is None: return [] if isinstance(item, list): return item if isinstance(item, tuple): return list(item) return [item]
def vowel_indices(word): """ We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters). :param word: A string input. :return: a list of indices of the vowels. """ return [i + 1 for i, j in enumerate(word) if j...
def _page_to_title(page): """Extract the title from a page. Args: page: a unicode string Returns: a unicode string """ # print("page=%s" % page) start_tag = u"<title>" end_tag = u"</title>" start_pos = page.find(start_tag) end_pos = page.find(end_tag) assert start_pos != -1 assert end_pos...
def sort_by_hw_count(user): """Sort students by the number of completed homeworks""" return sum([1 if hw['status'] == 'success' else 0 for hw in user['homeworks']])
def rightangletriangles(i): """genearate all the possible right angle triangles with integer edge for the given integer perimeter i list of tuple: [(longest, secondlong, shortest), ..] """ lmin=int(i/(1+2**0.5)) lmax=int(i/2) lt=[] for l in range(lmin, lmax): # ...
def is_sample(sample): """Return ``True`` if passed object is Sample and ``False`` otherwise.""" return type(sample).__name__ == "Sample"
def xattrSelect(x, idxSet): """ :param x: :param idxSet: :return: """ xOut = [] for row in x: xOut.append([row[i] for i in idxSet]) return xOut
def valid_passphrase_anagram(phrase: str) -> bool: """ Trick for anagrams : sorted words are the same """ words = phrase.split() word_set = set(tuple(sorted(word)) for word in words) return len(words) == len(word_set)
def xor_secret_i(K, kappa, i): """ Compute power consumption at bit i = kappa_i XOR K_i Parameters: K -- string kappa -- string i -- integer Return: p_i -- float """ # Transform string into list of booleans kappa = list(kappa) kappa = [bool(int(j)) for j in kappa] K = list(K) K = [bool(int(j)...
def my_hitpoints(state): """ Return current health (hitpoints) of the player. :param state: The current game state. :returns: int. """ return state['gladiators'][state['current_player']]['cur_hp']
def named_value(dictionary): """ Gets the name and value of a dict with a single key (for example SenzaInfo parameters or Senza Components) """ return next(iter(dictionary.items()))
def parse_platform_summary(raw_input_lines): """ @summary: Helper function for parsing the output of 'show system platform' @return: Returned parsed information in a dictionary """ res = {} for line in raw_input_lines: fields = line.split(":") if len(fields) != 2: con...
def filter_input_words(all_counts, allowed_chars, max_input_tokens): """Filters out words with unallowed chars and limits words to max_input_tokens. Args: all_counts: list of (string, int) tuples allowed_chars: list of single-character strings max_input_tokens: int, maximum number of tokens ac...
def do_files_comply(actual_in_files, actual_out_files): """Check if the 'in' files correspond to the 'out' files by names.""" expected = set(map(lambda x: x[:-3] + '.out', actual_in_files)) return not expected.difference(set(actual_out_files))
def indexSort(arr): """ Return new indexing for sorted array. """ return [i[0] for i in sorted(enumerate(arr), key=lambda x:x[1])]
def perc(num): """ Returns num as a percentage: Example: perc(0.05) returns "5%" """ return str(num * 100) + '%'
def calc_salary(s_from, s_to): """Calc salary. First modify salary to get 'from', 'to' :param s_from: int, salary from :param s_to: int, salary to :return: int or None, size of salary by 'from' and 'to' """ if (s_from is not None and s_to is not None): return (s_from + s_to) / 2 ...
def get_key_def(key, config, default=None, msg=None, delete=False, expected_type=None): """Returns a value given a dictionary key, or the default value if it cannot be found. :param key: key in dictionary (e.g. generated from .yaml) :param config: (dict) dictionary containing keys corresponding to parameter...
def deserialise_shape(shape): """ Get shape from serialised shape """ deserialised_shape = [] for sh in shape: deserialised_shape.append(tuple(sh)) return deserialised_shape
def mi09_Enuc(MFe, MNi, MSi, MCO): """Energy released via nuclear burning from Maeda & Iwamoto 2009 Input a composition, with masses of elements in solar masses: MFe: mass of stable Fe-peak elements like Cr, Ti, Fe, Co, Ni MNi: mass of 56Ni MSi: mass of intermediate-mass elements...
def is_abbr(word): """return True if word is abbr, False otherwise""" # more then 2 chars in word are uppercase num_of_uppers = sum(map(str.isupper, word)) num_of_lowers = sum(map(str.islower, word)) if num_of_uppers >= 2 and (num_of_uppers / len(word) >= 0.5): return True
def slip_encode_esc_chars(data_in): """Encode esc characters in a SLIP package. Replace 0xCO with 0xDBDC and 0xDB with 0xDBDD. :type str data_in: str to encode :return: str with encoded packet """ result = [] data = [] for i in data_in: data.append(ord(i)) ...
def get_neighbours(x, y, width, height): """ Calculates and returns the neighbours coordinates """ y1, y2, y3 = y - 1, y, y + 1 if y == 0: y1 = height - 1 elif y == height - 1: y3 = 0 x1, x2, x3 = x - 1, x, x + 1 if x == 0: x1 = width - 1 elif x == width - 1: ...
def _IsSpecified(args, name): """Returns true if an arg is defined and specified, false otherwise.""" return hasattr(args, name) and args.IsSpecified(name)
def linepoint(t, x0, y0, x1, y1): """ Returns coordinates for point at t on the line. Calculates the coordinates of x and y for a point at t on a straight line. The t parameter is a number between 0.0 and 1.0, x0 and y0 define the starting point of the line, x1 and y1 the ending poi...
def nth_sign(n): """ (-1)^n """ if n % 2 == 0: return 1 return -1
def swap_item(list: list, pull: object, push: object): """ Swap a specified item in a list for another. Parameters ---------- list : :class:`list` List to replace item within. pull Item to replace in the list. push Item to add into the list. Returns ------- ...
def is_clean(word): """ Check for profanity """ clean = True profane_words = [] if word in profane_words: clean = False return clean
def getEnemy(player): """ Returns the other player. getEnemy('X') returns 'O'. """ if player == 'X': return 'O' return 'X'
def subs(a, b): """Function that subtracts lists element by element. Parameters ---------- a b """ for i, val in enumerate(a): val = val - b[i] a[i] = val return a
def _get_extension_point_url_from_name(domain, category, pluggable_name): """Get the extension point URL based on a pluggable method name""" return '{}/{}/{}'.format(domain, category, pluggable_name).replace('//', '/')
def column_value_float(item, args): """Return the value stored in a column cast to a float. YAML usage: outputs: outcol: function: identity arguments: [col(KEYCOL)] value: column_value_float value_arguments: [col(VALUECO...
def forward_chain(rules, data, apply_only_one=True, verbose=False): """ Apply a list of IF-expressions (rules) through a set of data (assertions) in order. Return the modified data set that results from the rules. Set apply_only_one=True to get the behavior we describe in class. When it's False, a...
def class_memoization_fibonacci(i): """ time: O(n) space O(n) """ if i == 0: return 0 if i == 1: return 1 return class_memoization_fibonacci(i - 1) + class_memoization_fibonacci(i - 2)
def compare_lists(list1, list2): """Compare list contents, ignoring ordering. Hashability of elements not assumed, incurring O(N**2) See Also ======== L{MathSet} @type list1: list @type list2: list @return: True if a bijection exists between the lists. Note that this takes in...
def summing_numbers(target, nums): """Find target sum from two numbers in nums.""" for index, num1 in enumerate(nums): for num2 in nums[index + 1:]: if num1 + num2 == target: return num1, num2
def indent_string (s): """Put two spaces before each line in s""" lines = s.split ("\n") lines = [" " + i for i in lines] lines = [("" if i == " " else i) for i in lines] return "\n".join (lines)
def years_range(stress=False, padding=(0, 0)): """Returns a set of year values used for testing. """ return range(1925+padding[0], 2283-padding[1]) if stress else (1927, 2000, 2281)
def urljoin(refurl, objurl): """ >>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', '/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', 'beijing') ...
def without_leading_dir(path): """ Removes the the leading directory in FRONT of the given path. """ result = '\\'.join( path .replace('\\', '/') .split('/')[1:] ) if result.startswith('\\'): result = result[1:] return result
def mean_list(numbers): """ Mean value. Calculate the average for a list of numbers. Parameters ---------- numbers : list Attributes ---------- Notes ----- References ---------- """ return float(sum(numbers)) / max(len(numbers), 1)
def _calc_check_digit(number): """Calculate the check digit for the 11-digit number.""" weights = (6, 7, 8, 9, 4, 5, 6, 7, 8, 9) return str(sum(w * int(n) for w, n in zip(weights, number)) % 11)
def ifnone(*xs): """Return the first item in 'x' that is not None""" for x in xs: if x is not None: return x return None
def orientation(p,q,r): """Return positive if p-q-r are clockwise, neg if ccw, zero if colinear.""" return (q[1]-p[1])*(r[0]-p[0]) - (q[0]-p[0])*(r[1]-p[1])
def should_suspend(partial_result) -> bool: """Check the state of the result to determine if the orchestration should suspend.""" return bool(partial_result is not None and hasattr(partial_result, "is_completed") and not partial_result.is_completed)
def rpc_completion_callback(callback): """Verify callback is callable if not None :returns: boolean indicating nowait :rtype: bool :raises: TypeError """ if callback is None: # No callback means we will not expect a response # i.e. nowait=True return True if callab...
def uniq(string): """Removes duplicate words from a string (only the second duplicates). The sequence of the words will not be changed. """ words = string.split() return ' '.join(sorted(set(words), key=words.index))
def _LookForDropoutsInWindow(data_array, samp_freq, window_offset, silence_threshold, min_silence_len_secs): """Get silence periods inside the current window. This function returns a list of periods, for which the wave file contains silence. Only silence periods longer then MIN_SILEN...
def digits(x): """Convert an integer into a list of digits. Args: x: The number whose digits we want. Returns: A list of the digits, in order of ``x``. >>> digits(4586378) [4, 5, 8, 6, 3, 7, 8] """ # import pdb # pdb.set_trace() digs = [] while x != 0: div, m...
def pad_guid_bytes(raw_bytes: bytes) -> bytes: """Pads a sequence of raw bytes to make them the required size of a UUID. Note that if you're using an int as your source for instantiating a UUID, you should not use this function. Just use UUID(your_int_here). """ if not (0 < len(raw_bytes) <= 16): ...
def addBits(byte, numberOfBits, bitmap): """Used by ``emptyBlockBitmap`` to turn a byte or part of a byte into a bitstring. Turns MSB ``numberOfBits`` into a bitstring and appends it to ``bitmap``. NOTE: bits are ordered from LSB to MSB for adding to bitstring. The result string has the blocks or...
def map_smaller_file(func, filepath, suffix='.xlsx', truncated_size=2 ** 20): """ :param func: (filepath) => object :type func: Function :param filepath: :type filepath: str :param suffix: openpyxl, for instance, does a file extension check :type suffix: str :param truncated_size: :...
def indexed_images_relationship_match(data, indices, synset_matches): """ For each image in the data matched with with indices, see if there is a synset_match data - relationship json indices - indices of images that we are interested in (in the first use case these are humans / persons) ...
def containsAll(str, set): """Check whether 'str' contains ALL of the chars in 'set'""" return 0 not in [c in str for c in set]
def highest_bit(count): """Which is the nost significate bit in the binary number "count" that has been set? 0-based index""" highest_bit = -1 for i in range(0,32): if (count & (1<<i)) != 0: highest_bit = i return highest_bit
def get_unique_ents(ent_list): """ Process the entities to obtain a json object """ unique_ent_dict = {} for _ent in ent_list: if _ent[1] not in unique_ent_dict: unique_ent_dict[_ent[1]] = {} if _ent[0] not in unique_ent_dict[_ent[1]]: unique_ent_dict[_ent[1]][_ent[0]...
def nextpostfix(x): """Returns the next alpha postfix in the sequence.""" if x == '': return 'a' if ord(x[-1]) < ord('z'): x = x[0:-1] + chr(ord(x[-1])+1) else: if x[0] == 'z': x = 'a' + 'a' * len(x) else: x = chr(ord(x[0])+1) + x[1:] ...
def _path_append(parent, child): """Utility function for joining paths, ensuring that forward slashes are always used regardless of OS.""" parent = parent.rstrip('/') child = child.lstrip('/') return parent + '/' + child
def _flatten_results(result, default_value=None): """ Formats results to map to a single value or default value if empty. """ flattened = {} for k, v in result.items(): if len(v) > 1: raise ValueError( 'Expected one, but more returned for "{}": {}'.format(k, v)) i...
def get_human_name(name: str) -> str: """Get a human-readable name.""" return name.replace("-", " ")
def edgelist_to_adjacency(edgelist): """Converts an iterator of edges to an adjacency dict. Args: edgelist (iterable): An iterator over 2-tuples where each 2-tuple is an edge. Returns: dict: The adjacency dict. A dict of the form `{v: Nv, ...}` where `v` is a node in a ...
def _replace_brackets(s): """Replace brackets with parenthesis because it breaks the UI""" # It probably thinks the brackets are markdown or something. return s.replace("[", "(").replace("]", ")").strip()
def is_power_of_two(number: int) -> bool: """Check if a number is a power of 2""" return (number & (number - 1) == 0) and number != 0
def v2_high_urgency(_, publication): """Designates this alert as critical or high urgency This only works for pagerduty-v2 and pagerduty-incident Outputs. The original pagerduty integration uses the Events v1 API which does not support urgency. """ publication['@pagerduty-v2.severity'] = 'critical'...
def orient_blocks(subchain_blocks_raw, chain_data): """Create block num: coordinates dict. Orient them in correct direction. Add interblock regions, like block 1_2 between blocks 1 and 2. """ block_ranges = {} tStrand, tSize, qStrand, qSize = chain_data for i in range(len(subchain_bloc...
def get_aperture_value(tags): """Extracts aperture values from given tags if focal length also exists """ if tags and "EXIF FocalLength" in tags: if "EXIF FNumber" in tags: return eval(str(tags["EXIF FNumber"])) elif "EXIF ApertureValue" in tags: return eval(str(t...
def hms_to_seconds(time_string): """ Converts string 'hh:mm:ss.ssssss' as a float """ s = time_string.split(':') hours = int(s[0]) minutes = int(s[1]) secs = float(s[2]) return hours * 3600 + minutes * 60 + secs
def is_prime(n): """"pre-condition: n is a nonnegative integer post-condition: return True if n is prime and False otherwise.""" if n < 2: return False; if n % 2 == 0: return n == 2 # return False k = 3 while k*k <= n: if n % k == 0: ...
def _full_listing_name(chapter, listing, name, insert=False): """ Creates the name of a listing file from the components. The names are like "listing_C_N_<name>" where C is the chapter, N is the number and <name> is the listing name. For example, "listing_2_1_net_retention". "insert" listings are a...
def lambda_handler(event: dict, context: dict): """ Return the original data without any modification. This lambda can be modified for the custom transformation: https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html """ results = [] for record in event.get('records', []): ...
def template_method(position_arg1, position_arg2, keyword_arg1=None, keyword_arg2=1): """Template for writing docstring in python method Parameters --- position_arg1 : int description for position_arg1 position_arg2 : str or int description for position_arg2 keyword_arg...
def getTemperature(rawData): """ Note: You'll get data in reverse order from sensor: |low byte|high byte| 0x80|0E """ degrees = rawData & 0xFF #cut high byte off, get low byte000 degreesAfterDecimal = rawData >> 15 #shift msb to lsb place if (degrees & 0x80) != 0x80: #msb in low byte is 0 -> positiv...
def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all altseps into seps.""" return s.replace('\\', '/').lower()
def principal_form(disc): """Construct principal form for given discriminant. Follows Def. 5.4 from `Binary quadratic forms` by Lipa Long, 2019: https://github.com/Chia-Network/vdf-competition/blob/master/classgroups.pdf """ assert disc % 4 == 0 or disc % 4 == 1 k = disc % 2 f = (1,...
def collect_PR_from_line(line): """ Collect all unique protein (PR) numbers from between "#" in BRENDA. """ split_l = line.split("#") PRs = split_l[1] # first_sec = line.split(" ")[0] # check formatting is consistent # if first_sec[0] != '#' or first_sec[-1] != '#': # print('form...
def extract_from_dict(data, path): """ Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. """ value = data try: for key in path: value = value[key] return value except (KeyError, IndexError): return ''
def not_found(error): """Serve unknown route page.""" return 'This page does not exist', 404
def _isNumeric(n): """test if 'n' can be converted for use in numeric calculations""" try: b = float(n) return True except: pass return False
def average_error(state_edges_predicted, state_edges_actual): """ Given predicted state edges and actual state edges, returns the average error of the prediction. """ total=0 for key in state_edges_predicted.keys(): #print(key) total+=abs(state_edges_predicted[key]-state_edges_...
def command_line_parser(line): """ Parses lines of the following form: Command line: ['to_html.py'] :param line: sequence of lines :return: string containing the command_line, e.g., 'to_html.py' """ idx_start, idx_end = line.find("['"), line.find("']") if idx_start == -1 or idx_en...
def match_networks(target_params, networks): """Finds the WiFi networks that match a given set of parameters in a list of WiFi networks. To be considered a match, a network needs to have all the target parameters and the values of those parameters need to equal to those of the target parameters. ...
def uptime_to_short(sh_ver_uptime_line): """ uptime to short converts the uptime line form sh version to short format 1y2m3d :param sh_ver_uptime_line: line from show version containing the uptime :return: uptime short format """ fs_year = '' fs_week = '' fs_day = '' fs_hour = '' ...
def filter_duplicates(l): """ >>> filter_duplicates([{'a': 1}, {'b': 1}, {'a': 1}]) [{'a': 1}, {'b': 1}] """ def make_hashable(o): try: hash(o) return o except TypeError: return helper[type(o)](o) helper = { set: lambda o: tuple([make_...
def is_number(s: str) -> bool: """Is it a number? Args: s: String which may be a number Returns: bool """ try: float(s) return True except ValueError: return False
def triangulate(poly): """ This function return the triangulated given polygon mesh @type poly: hostApp object mesh @param poly: the hostApp obj to be decompose @rtype: hostApp object mesh @return: triangulated polygon mesh """ #put the host code here return poly
def is_node(node, name): """Return the node name""" if node is None: return False return node.__class__.__name__ == name
def are_ints(items): """ detect if all items are ints """ for i in items: try: int(i) if i is not None and len(i) > 0 else None except ValueError: return False return True
def unique_list(seq): """ Returns unique values from a sequence. Modified to remove empty context entries https://www.peterbe.com/plog/fastest-way-to-uniquify-a-list-in-python-3.6 """ return list(dict.fromkeys(s for s in seq if s))
def get_annotation(db_path, db_list): """ Checks if database is set as annotated. """ annotated = False for db in db_list: if db["path"] == db_path: annotated = db["annotated"] break return annotated
def map_functions(x, functions): """Mapping a List of Functions""" return [func(x) for func in functions]
def compute_avna(prediction, ground_truths): """Compute answer vs. no-answer accuracy.""" return float(bool(prediction) == bool(ground_truths))
def get_db_collection_names(db_collection_string): """ :param db_collection_string: A string like someDb.someCollection or just someCollection, which is interpreted as someCollection.someCollection. :return: An object with db and collection names. """ name_parts = db_collection_string.split(".") ...
def create_context(edit, text, length = 500, seperator = ['<b>', '</b>'], overlap = 90): """ Wrap context around an edit made by a user. Use this method to extract the preceding and following defined number of characters from the main text. This method uses utf8 encoding, because otherwise Arabic...
def sortDictByValue(dict): """ Sort a dictionary by its values Parameters dict: The dictionary to sort (dict) Returns items: The dictionary sorted by value (list) """ items = [(v, k) for k, v in dict.items()] items.sort() items.reverse() items = ...
def is_git_sha(text): """Returns True if this is probably a git sha""" # Handle both the full sha as well as the 7-character abbrviation if len(text) in (40, 7): try: int(text, 16) return True except ValueError: pass return False
def are_instances(lhs, rhs, cls) -> bool: """Return True if both lhs and rhs are instances of cls; False otherwise """ return isinstance(lhs, cls) and isinstance(rhs, cls)
def compare_channels(chanlist, chanlist_target): """Return a list of channels that are in both lists""" shared_channels = [] not_shared_channels = [] for chan in chanlist: if chan in chanlist_target: shared_channels.append(chan) else: not_shared_channels.append(...