content
stringlengths
42
6.51k
def parse_payload_v1(event): """ Get HTTP request method/path/body for v1 payloads. """ body = event.get('body') method = event.get('httpMethod') try: package, *_ = event['pathParameters']['package'].split('/') except KeyError: package = None return (method, package, body...
def gen_random_str(length=32): """ Generate random string (letters+numbers) Args: length: string length (default: 32) """ import string import random symbols = string.ascii_letters + '0123456789' return ''.join(random.choice(symbols) for i in range(length))
def convert_mat_value(val): """Convert values specified in materials elements_vars.""" return { 'values': [float(x) for x in val['values']], 'min_value': float(val['min_value']) if val['min_value'] is not None else None, 'max_value': float(val['max_value']) if val['max_value'] is not Non...
def suffixer(n): """ Provides the suffix for printing out a podium spot based on the spot number. """ if n == 1: return 'st' elif n == 2: return 'nd' elif n == 3: return 'rd' else: return 'th'
def yx_to_xy(yx_grid): """Turns a y/x grid (row, column) into an x/y grid. Iterates through the yx grid keeping track of the current location, and maps that value to the corresponding position within the xy grid :param map: int[][], a typical ingested y/x grid :return: int[][], a RHR cartesian x,y g...
def valid_filename(s): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. Arguments: s {str} Ret...
def sizeof_fmt(num, suffix="B"): """Convert any number to human readable size. By Fred Cirera""" for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024.0: return "%3.1f %s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f %s%s" % (num, "Yi", suffix)
def max_(data): """Maximum of the values in the object""" maximum = data[0] for value in data: maximum = value if value > maximum else maximum return maximum
def spike_height(trending_score, x, x_old, time_boost=1.0): """ Compute the size of a trending spike. """ # Change in softened amount change_in_softened_amount = x**0.25 - x_old**0.25 # Softened change in amount delta = x - x_old softened_change_in_amount = abs(delta)**0.25 # Soft...
def add_gate_to_line(local_qasm_line, gate_symbol, qubit_index): """ Add in parallel the application of a gate on a qubit. Args: local_qasm_line: The existing line of QASM to add the gate in. gate_symbol: The symbol representing the gate. qubit_index: The index of the target qubit. ...
def parse_number_set(number_set): """ Parse a number set string to a set of integers. The string is a comma-separated range of "atoms", which may be * A single value (`1`) * A range of values (`1-5`) separated with either a dash or double dots. and these may also be negated with a leading exc...
def get_sequence(genome, chrom, start, end, is_forward_strand=True): """Return a sequence for the genomic region. Coordinates are 0-based, end-exclusive. """ # Prevent fetching negative coordinates. start = max(start, 0) if start >= end: return '' else: seq = genome[str(chr...
def url_path_join(*args): """Join path(s) in URL using slashes""" return '/'.join(s.strip('/') for s in args)
def witHelp(x): """ witHelp(x) -> (t, u) witHelp returns x as a tuple (t, u), where x = u * 2**t """ t = 0 while not (x & 1): x >>= 1 t += 1 return (t, x)
def numberSeparators(number, separator=' '): """ Adds a separator every 3 digits in the number. """ if not isinstance(number, str): number = str(number) # Remove decimal part str_number = number.split('.') if len(str_number[0]) <= 3: str_number[0] = str_number[0] e...
def calculate_declining_funds(starting_amount, interest_rate, stipend_amount): """ If I want to take out a big chunk every year, how many years will it last? :param starting_amount: The amount of money the bank has to start with. :type starting_amount: double :param interest_rate: The rate that inte...
def part_decode(part): """Decode a part of a JSON pointer. >>> part_decode("foo") 'foo' >>> part_decode("~0foo") '~foo' >>> part_decode("foo~0") 'foo~' >>> part_decode("~1foo") '/foo' >>> part_decode("foo~1") 'foo/' >>> part_decode("f~1o~0o") 'f/o~o' >>> part_dec...
def scale_norm(norm, min_distance, max_distance): """Convert network's sigmoid output into distance prediction""" return min_distance + max_distance * norm
def _container_name(name): """ For a given container or well name, return just the container name. Parameters ---------- name : str Returns ------- str """ return name.split("/", 1)[0]
def linspace(start, end, totalelem): """ Basically same as numpy.linspace. Cut [start, end] into an array with totalelem elements (including start and end) that are an even distance apart """ if totalelem == 1: return [start] gaps = totalelem - 1 dist = (end-start)/gaps retur...
def get_shape_from_component(component, component_name='vtx'): """ Given a component, returns the associated shape :param component: str :param component_name: str, component type ('vtx', 'e', 'f' or 'cv') :return: str """ component_shape = None if component.find('.{}['.format(componen...
def next_quarter(year, quarter, num=1): """return next quarter for Gregorian calendar""" if quarter not in range(1, 5): raise ValueError('invalid quarter') quarter -= 1 # for mod, div quarter += num year += quarter // 4 quarter %= 4 quarter += 1 # back return year, quarter
def fractional_epoch(row, *, default=None): """Given a data row, compute the fractional epoch taking batch into account. Example: Epoch 1 at batch 30 out of 100 batches per epoch would return epoch 1.3. """ if 'epoch' not in row: return default if 'batch' not in row: ...
def filter_pad(val, width, fillchar='0'): """Pads a number or string with fillchar to the specified width.""" return str(val).rjust(width, fillchar)
def itineraryisvalid(itinerary): """Verifies that an itinerary is able to be processed.""" itinerary = itinerary.lower() if len(itinerary) < 3: #We don't allow itineraries that don't have at least three destinations for now return False for count, i in enumerate(itinerary): if i no...
def divide_list(array, number): """Create sub-lists of the list defined by number. """ if len(array) % number != 0: raise Exception("len(alist) % number != 0") else: return [array[x:x+number] for x in range(0, len(array), number)]
def add_text_element(param_args): """Generates a string that represents a html text block. The input string should be wrapped in proper html tags param_args - a dictionary with the following arguments: param_args['text'] - a string returns - a string """ return param_...
def hasCapLettersOnly (tok): """Returns true if token has at least one capital letter, and no lower case letters. Can also contain digits, hypens, etc.""" hasCap = False for sub in tok: if (sub.isalpha()): if (sub.islower()): return False else...
def to_rgba_bytes(v: int) -> bytes: """ Converts an RGBA color int to raw bytes. """ return bytes(i & 0xFF for i in (v >> 24, v >> 16, v >> 8, v))
def get_unique_attribute_objects(graph, uniq_attrs): """Fetches objects from given scene graph with unique attributes. Args: graph: Scene graph constructed from the dialog generated so far uniq_attrs: List of unique attributes to get attributes Returns: obj_ids: List of object ids with the unique at...
def get_subkey(d, key_path): """Gets a sub-dict key, and return None if either the parent or child dict key does not exist :param d: dict to operate over :type d: dict of dicts :param key_path: dict keys path list representation :type key_path: list Example ------- >>> d = ...
def get_actual_pool(spoiler): """Retrieves the actual item pool based on items placed in the spoiler log. :param spoiler: Spoiler log output from generator :return: dict: key: Item name value: count in spoiler """ actual_pool = {} for location, item in spoiler['l...
def dict_sort(dictionary): """Takes in a dictionary with integer values and outputs a list of the keys sorted by their associated values in descending order.""" return list(sorted(dictionary, key=dictionary.__getitem__, reverse=True))
def inc_code_correct(inc_type_code, inc_type_desc): """ Parses and corrects OC CAD Incident Type Description. """ if inc_type_code == 'BOX_CO': inc_type_code = 'BOX_COM' elif inc_type_code == 'BOX_RE': inc_type_code = 'BOX_RES' elif inc_type_code == 'FULL_C': inc_type_cod...
def turn_left(block_matrix, debug=False): """block turn left.""" new_block = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] for i in range(4): for j in range(4): new_block[j][3-i] = block_matrix[i][j] if debug: print(new_block) return new_block
def file_base_features(path, record_type): """Return values for BASE_SCHEMA features.""" base_feature_dict = { "record_id": path, "record_type": record_type, # "utc_last_access": os.stat(path).st_atime, "utc_last_access": 1600000000.0, } return base_feature_dict
def _extract_mc_repeated_field(data, plural, singular): """Helper to extract repeated fields from xml consistently. Without this single element lists get returned as dicts """ f = data.get(plural, {}).get(singular, []) if type(f) == list: return f else: return [f]
def _ValidateRepoToDepPathConfig(repo_to_dep_path): """Checks that the repo_to_dep_path is properly formatted. Args: repo_to_dep_path (dict): A dictionary mapping repository url to its chromium repo path. For example: { "https://boringssl.googlesource.com/boringssl.git": ...
def get_indefinite_article(noun: str) -> str: """ >>> get_indefinite_article('Elephant') 'an' >>> get_indefinite_article('lion') 'a' >>> get_indefinite_article(' ant') 'an' """ normalised_noun = noun.lower().strip() if not normalised_noun: return 'a' if normalised_...
def separate_categories(invoice_lines: dict): """ This function separates categories and counts their prices. Decimal euros are converted into integer cents. :param invoice_lines: dictionary with invoice lines :return: dictionary with separated categories """ categories = {} for invoice i...
def flush(hand): """Return True if all the cards have the same suit.""" suits = [s for r, s in hand] return len(set(suits)) == 1
def tsv_example_row(label, title): """Return row with entity type column populated""" return [label] + [""] * (len(title) - 1)
def plural_suffix(count: int) -> str: """"s" when count is not one""" suffix = '' if count != 1: suffix = 's' return suffix
def itemfilter(fn, d): """returns {k: v for k, v in d.items() if fn(k, v)}""" return {k: v for k, v in d.items() if fn(k, v)}
def countPrimes(n): """ :type n: int :rtype: int """ if n <= 2: return 0 primes = [True] * (n) primes[0] = primes[1] = False for i in range(2, n): if primes[i]: for j in range(i*i, n, i): primes[j] = False return sum(primes)
def factorial(n): """A factorial of n (n!) is defined as the product of all positive integers less then or equal to n. According to the convention for an empty product, the value of factorial(0) (0!) is 1. >>> [factorial(i) for i in range(11)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800...
def is_email_link(href=None): """Utility function to determine whether the supplied href attribute is an email link.""" print("email_link()") return href and 'mailto:' in href
def convert_to_date( value=None, format="%Y-%m-%d %H:%M:%S"): """convert_to_date param: value - datetime object param: format - string format """ if value: return value.strftime(format) return ""
def return_file_read(_): """Return the lines expected to be found in the file_read test file. Args: _: Present to mimic the behavior of RawLog.get_section_* functions, but not used by the function Returns: A list of the lines in file_read.txt with trailing whitespace removed "...
def get_authors_text(csl_item, max_length=100): """ Return string of authors like: Ching, Himmelstein, Beaulieu-Jones, Kalinin, Do, Way, Ferrero, Agapow, Zietz, Hoffman, Xie, Rosen, et al "et al" is inserted when adding another name would cause authors_text to exceed max_length. """ authors...
def check_provisioning_state(provisioning_state: str): """Check if the provisioning state is succeeded""" required_provisioning_state = 'Succeeded' if required_provisioning_state.lower() == provisioning_state.lower(): return True return False
def velocity(range, avg_range, volume, avg_volume): """ The average of the average of the range and volume for a period. :param range: :param avg_range: :param volume: :param avg_volume: :return: """ rng_rate = range / avg_range vol_rate = volume / avg_volume total = sum((rng...
def width(canv): """ gets the height of the canvas :param canv: :return: integer height of the canvas """ return (canv and len(canv[0])) or 0
def get_nodetype(obj, objid): """ Returns key of the object with given ID. (eg., menu, page, etc. ) :param obj: Structure containing YAML object ( nested lists / dicts ). :param objid: YAML ID of given node. :return: Key of given ID. """ result = None if isinstance(obj, dict): ...
def go_to_url(url, return_what, uniqid): """ xxx """ #--------------------------------- # q = [url to redirect] # # return_what = 'form' = # '<form id="form_id_xxx"><input type="hidden" value="'+ str(q) +'" id="q"></form>' # # return_what = 'link' = # 'href="javascript:{}" onclick="d...
def format_order_by(orderby: list, alias='s', similarity_col='fts_col') -> str: """ Make the api parameter 'order-by' into pony code. **Works on single table query ONLY**. :param orderby: parameter from the api, list of field to be used by the order by :param alias: table alias :param similarit...
def remove(elements, element): """ This tag removes an element from a list. :param elements: The given list of elements :type elements: list :param element: The element to be removed :type element: object :return: The list without the element :rtype: list """ try: # Co...
def renumber(dictionary) : """Renumber the values of the dictionary from 0 to n :param dictionary: the partition :type dictionary: dictionary :rtype: dictionary :return: The modified partition and the number of classes """ count = 0 ret = dictionary.copy() new_values = dict([]) ...
def _fraction_elutions(fractions): """ Given a list of fraction names, group them after removing 'FractionXX' from the end. Return a dict of { elutionname: listofindices }. Example of fraction name: Orbitrap_HeLaCE_IEF_pH3_to_10_Fraction10 """ elution_names = {} for i,fname in enumerate(fra...
def get_peak_volumes(volumes): """Returns a list of the current peak volume at each second. Resets when volume below -72 or above 10.""" peaks = [] peak = -73 for volume in volumes: temp = peak if volume < -72: peak = -73 # Reset peak temp = '-Inf' el...
def quick_sort(num_list=[]): """Quick sorts a number list""" if type(num_list) != list: raise TypeError("The argument for quick_sort must be of type list.") if len(num_list) <= 1: return num_list choice = num_list[len(num_list) // 2] greater = [num for num in num_list if num > choi...
def generate_performance_payload(array, start_time, end_time, metrics): """Generate request payload for VMAX performance POST request :param array: symmetrixID :param start_time: start time for collection :param end_time: end time for collection :param metrics: metrics to be collected :returns: ...
def call_warpper(callback, request, args): """ change the calling policy according to the parameters of callback function *beautiful code ,oopssssssss """ varnames = callback.__code__.co_varnames argcount = callback.__code__.co_argcount if argcount != 0 and varnames[0] == "request": ...
def create_binding(subject, displayId, version, name, description, _type, role, sbol_type, order_by, percentMatch=-1, strandAlignment='N/A', CIGAR='N/A'): """ Creates bindings to be sent to SBH Arguments: subject {string} -- URI of part displayId {string} -- DisplayId...
def check_player_win(board, token) : """ board: list of strings representing tic-tac-toe board where a row is a string of 3 tokens token: string representing either x or o Check 8 possible winning combinations: 3 rows matching the token, 3 columns matching the token, or 2 diagnols mat...
def _path_to_name(path, prefix = None, suffix = None): """Converts a path string to a name suitable for use as a label name. Args: path: A path as a `string`. prefix: Optional. A string which will be prefixed to the namified path with an underscore separating the prefix. ...
def Flatten(value): """Flattens nested lists/tuples into an one-level list. If value is not a list/tuple, it is converted to an one-item list. For example, (1, 2, [3, 4, ('56', '7')]) is converted to [1, 2, 3, 4, '56', '7']; 1 is converted to [1]. """ if isinstance(value, (list, tuple)): result...
def boolean(value): """Parse the string "true" or "false" as a boolean (case insensitive)""" value = value.lower() if value == 'true': return True if value == 'false': return False raise ValueError("Invalid literal for boolean(): {}".format(value))
def has_read_perm(user, group, is_member, is_private): """ Return True if the user has permission to *read* Articles, False otherwise. """ if (group is None) or (is_member is None) or is_member(user, group): return True if (is_private is not None) and is_private(group): return False ...
def max_profit_naive(prices): """ :type prices: List[int] :rtype: int """ max_so_far = 0 for i in range(0, len(prices) - 1): for j in range(i + 1, len(prices)): max_so_far = max(max_so_far, prices[j] - prices[i]) return max_so_far
def levain_flour_weight(recipe, total_weight): """ Figure out the weight of flour in the levain from the total weight. """ total_liquid = sum(recipe["liquid"][i] for i in recipe["liquid"]) flour = total_weight / (1 + total_liquid / 100) return flour
def numerise_params(prop_dict): """ Returns drug properties with all qualitative values transformed into numeric values returns: numerically transformed property dictionaries rtype: dict """ clearance_dict = { 'low (< 5.6)': 1, 'medium (5.6-30.5)': 4, ...
def _index_exists(idx_conf, indexes): """ Check if an index for a collection was already created in the database. idx_conf - index config object from a collection schema indexes - result of request to arangodb's /_api/index?collection=coll_name """ for idx in indexes: if idx_conf['fields...
def sequence_class(immutable): """returns a callable class with a conditional expression.""" return tuple if immutable else list # the conditional expression is the same as below: # if immutable: # cls = tuple # else: # cls = list # return cls
def uppercaseFirstHash(data): """ This function takes the inputted data and formats all of the keys to be lowercase with the first letter capitalized. If the input is anything but a dictionary, it simply raises a TypeError. Args: :param data: The data to be reformatted Raises: ...
def rowToCombo(row, columns): """Converts a row to a list of (Attribute, Value) tuples. Args: row: the input row. columns: the columns of the input row. Returns: combo: the list of (Attribute, Value) tuples. """ res = [] for i, c in enumerate(columns): val = str...
def _create_weather_key(lat, lng): """ Creates a properly formatted key for storing in a JSON database. Args: lat (string or float) -- latitude component of coordinate lng (string or float) -- longitude component of coordinate Returns: string -- key value """ tmp = "%s,%s" % (lat, ...
def get_border_bounding_rect(h, w, p1, p2, r): """Get a valid bounding rect in the image with border of specific size. # Arguments h: image max height. w: image max width. p1: start point of rect. p2: end point of rect. r: border radius. # Returns rect coord ...
def get_dict_query_field(dict_field_name: str, sub_field: str): """Generate django query key for searching a nested json feild""" return dict_field_name + "__" + sub_field.replace(".", "__")
def InterpolateDepths(near_depth, far_depth, num_depths): """Returns num_depths from (far_depth, near_depth), interpolated in inv depth. Args: near_depth: The first depth. far_depth: The last depth. num_depths: The total number of depths to create, include near_depth and far_dept...
def flatten(xs): """Returns collection [xs] after recursively flattening into a list.""" if isinstance(xs, list) or isinstance(xs, set) or isinstance(xs, tuple): result = [] for x in xs: result += flatten(x) return result else: return [xs]
def reversepath(path): """ This function reverses a path. """ return path[::-1]
def isNumber(s): """ This function takes a string as an argument and tries to parse it to float. If it can, it returns true. Else, it returns false. This will filter elements in the .dat file so that only numbers are included in the returned arrays """ try: float(s) return True exce...
def _remove_dead_branch(transitions_list): """ Remove dead branchs inserting a selfloop in every node that has not outgoing links. Example ------- >>> trj = [1,2,3,1,2,3,2,2,4,3,5] >>> tr = pykov.transitions(trj, nsteps=1) >>> tr [(1, 2), (2, 3), (3, 1), (1, 2), (2, 3), (3, 2), (2, ...
def decode_pdf_string(bytestring): """ PDF Strings can sometimes be UTF-16. Detect and convert if necessary """ if(bytestring.startswith(b'\xfe\xff') or bytestring.startswith(b'\xff\xfe')): string = bytestring.decode("utf-16") else: string = bytestring.decode("ascii") return...
def _fmt_msg(msg): """Format the message for final display. Parameters ---------- msg : str The message to show to the user to provide additional context. returns ------- fmtd : str The formatted message to put into the error message. """ if not msg: return ...
def display_body(body_list): """ Sets the body for the message to be displayed with display()\n The body needs to be a list with each element of the list being a line. """ global body if type(body_list) == type(['hey', 'hey']): body = body_list return body elif type(body_list...
def split_layouts_by_arrow(s: str) -> tuple: """ Splits a layout string by first arrow (->). :param s: string to split :return: tuple containing source and target layouts """ arrow = s.find('->') if arrow != -1: source_layout = s[:arrow] target_layout = s[arrow + 2:] ...
def get_file_contents(filepath): """Returns the contents of a file as a string.""" data = "" try: with open(filepath, "r") as open_file: data = open_file.read() except Exception as e: print(e) finally: return data
def _pprint_version(value): """Pretty-print version tuple; takes a tuple of field numbers / values, and returns it as a string joined by dots with a 'v' prepended. """ return "v%s.x" % (".".join(map(str, value)),)
def is_pythagorean_triple(a: int, b: int, c: int) -> bool: """ This function checks the input a, b, c to see whether they satisfy the equation a^2 + b^2 = c^2 """ return True if (a**2 + b**2) == c**2 else False
def dissect_time(sec): """changes total seconds into hours, minutes, seconds""" seconds = sec % 60 minutes = (sec // 60) % 60 hours = (sec // 60) // 60 return hours, minutes, seconds
def parse_ID(seq): """Return the EC number inside the input string. Example ------- "ID\t1.1.1.1\n*****************\n" -> "1.1.1.1" """ seq = seq.split("\n")[0] return seq[2:].strip()
def json_path(path, data): """Extract property by path""" fragments = path.split(".") src = data for p in fragments: src = src[int(p)] if (isinstance(src, list) and p.isdigit()) \ else src[p] return src
def quote_sh_value(value): """quote a string value for use in sh config. """ if not value: return u'' value = u"%s" % (value,) return u'"%s"' % (value.replace('"', '\"'))
def base (t): """ find basic form of word """ return str("".join(sorted(t)))
def _find_method(obj, string): """Find methods in object that starts with `string`. """ out = [] for key in dir(obj): if key.startswith(string): out.append(getattr(obj, key)) return out
def indexByIdMap(cfg): """ Function that returns the dictionary that returns the index of a certain node given the ID. """ return {cfg['nodes'][i]['id']:i for i in range(len(cfg['nodes']))}
def generate_latex_error(error_msg): """ generate_latex_error(error_msg: str) -> str this generates a piece of latex code with an error message. """ s = """\\PackageError{vistrails}{ An error occurred when executing vistrails. \\MessageBreak %s }{vistrails}""" % error_msg return s
def decode_gcs_url(url): """Decode GCS URL. Args: url (str): GCS URL. Returns: tuple: (bucket_name, file_path) """ split_url = url.split('/') bucket_name = split_url[2] file_path = '/'.join(split_url[3:]) return (bucket_name, file_path)