content
stringlengths
42
6.51k
def get_xml(request): """Strips the request tag from a response and returns the xml""" open_tag_end = request.find('>') close_tag_start = request.rfind('</') return request[open_tag_end + 1:close_tag_start]
def rotate90(arr): """ left(r) to top top to right right(r) to bottom bottom to left >>> rotate90(EXAMPLE_ARR) [[7, 4, 1], [8, 5, 2], [9, 6, 3]] >>> rotate90(rotate90(rotate90(rotate90(EXAMPLE_ARR)))) == EXAMPLE_ARR True """ return [list(z) for z in zip(*arr[:...
def int_to_str_digit(n): """ Converts a positive integer, to a single string character. Where: 9 -> "9", 10 -> "A", 11 -> "B", 12 -> "C", ...etc Args: n(int): A positve integer number. Returns: The character representation of the input digit of value n (str). """ ...
def _getBestSize(value): """ Give a size in bytes, convert it into a nice, human-readable value with units. """ if value >= 1024.0**4: value = value / 1024.0**4 unit = 'TB' elif value >= 1024.0**3: value = value / 1024.0**3 unit = 'GB' elif value >= 1024...
def build_filename_paperinfo(_bibcode:str) -> str: """ Builds the name for the paperinfo output file """ return '{}_paperinfo.json'.format(_bibcode)
def min_index(l): """Returns the index of the min value""" m = float("inf") index = -1 for i in range(len(l)): if l[i] < m: index = i m = l[i] return index
def __checkToolArgs(args=None): """Handles None case for arguments as a helper function.""" if args is None: args = [None] return args
def remove_download_token_from_cookie(options, response): """ Removes a download token in cookie as an indicator that download is ready. Args: options (dict): args or form fields from Request object response: Response object Returns: The response object ...
def trajectory_importance_avg(states_importance): """ computes the importance of the trajectory, according to avg approach """ avg = sum(states_importance) / len(states_importance) return avg
def convert_byte(byte_to_convert): """ Converts byte to most biggest unit. """ byte_to_convert = float(byte_to_convert) TBYTE = 1024 * 1024 * 1024 * 1024 GBYTE = 1024 * 1024 * 1024 MBYTE = 1024 * 1024 KBYTE = 1024 if byte_to_convert / TBYTE >= 1: return str(round(byte_...
def reverse_bit_scan(bitboard): """ get most significant bit """ return bitboard.bit_length() - 1
def modExp(a, b, n): """ modExp(a, b, n) -> number modExp calculates a**b mod n """ c = 0 d = 1 for bi in bin(b)[2:]: c = 2 * c d = (d * d) % n if bi == '1': c += 1 d = (d * a) % n return d
def check_form(row): """ This function check the string that user entered is regulated. :param row: string, a string of words :return: boolean """ # check the length of row is regulated if len(row) < 6 or len(row) > 7: return False else: for i in range(len(row)): ch = row[i] # check the user enter spa...
def extremum (a, b, c) -> tuple: """ Returns the (x, y) coordinates of the extremum of the curve given by the polynomial, f(x | a, b, c). The extremum can refer to either a maximum or minimum value. When 'a' is negative, the max or top of the curve is returned. Otherwise, the min is returned. The value of the x-co...
def f(x): """ int -> int """ print(x) return x
def create_placeholders_from_signatures(signatures): """Creates placeholders from given signatures. Args: signatures: Dict of `TensorSignature` objects or single `TensorSignature`, or `None`. Returns: Dict of `tf.placeholder` objects or single `tf.placeholder`, or `None`. """ if signatures is ...
def progress(value, total, width, symbol='#', empty=' '): """Get a string representing the progress.""" frac = 1. * value / total pixels = round(frac * width) left_pixels = width - pixels return '[' + (symbol * pixels) + (empty * left_pixels) + ']'
def keys_sorted_by_value(d): """ Return the keys of dictionary d sorted by value. """ # By Daniel Schult, 2004/01/23 # http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306 items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() return [ backitems[i][1] for i...
def int_or_chr_key(s): """Return a sortable value as an integer if possible otherwise, convert the character to an integer""" try: return int(s) except Exception: return ord(s)
def MulPoint3(p, m): """Return matrix multiplication of p times m where m is a 4x3 matrix and p is a 3d point, extended with 1.""" (x, y, z) = p return (x * m[0] + y * m[3] + z * m[6] + m[9], x * m[1] + y * m[4] + z * m[7] + m[10], x * m[2] + y * m[5] + z * m[8] + m[11])
def get_ml_dag_id(parent_dag_id: str, **kwargs) -> int: """ Extracts ml_dag_id either from kwargs or from XCom Args: parent_dag_id: **kwargs: Returns: ml_dag_id """ if 'ml_dag_id' in kwargs: ml_dag_id = kwargs['ml_dag_id'] else: ml_dag_id = kwargs['task_instanc...
def is_valid_zero_one_param(param, required=True): """Checks if the parameter is a valid zero or one string. @param param: Value to be validated. @return True if the parameter has a valid zero or one value, or False otherwise. """ if param is None and not required: return True elif par...
def to_str(number): """ Convert a task state ID number to a string. :param int number: task state ID, eg. 1 :returns: state name like eg. "OPEN", or "(unknown)" if we don't know the name of this task state ID number. """ states = globals() for name, value in states.items(): ...
def cifar100_to_cifar20(target): """ CIFAR100 to CIFAR 20 dictionary. This function is from IIC github. """ class_dict = {0: 4, 1: 1, 2: 14, 3: 8, 4: 0, 5: 6, 6: 7, 7: 7, 8: 18, 9: 3, 10: 3, 11: 14, 12: 9, 13: 18...
def build_suffix_array(text): """ Build suffix array of the string text and return a list result of the same length as the text such that the value result[i] is the index (0-based) in text where the i-th lexicographically smallest suffix of text starts. """ result = [] # Implement this function yourse...
def _interpolate(start_rgb, end_rgb, percent_blend): """Interpolates an RGB value a specific percentage between two values Args: start_rgb (:obj:`list` of :obj:`int`): Beginning RGB color value end_rgb (:obj:`list` of :obj:`int`): Ending RGB color value percent_blend (float): % blend be...
def _resolve_yes_no(value): """ Fix for default values other than True or False for click_prompt_yes_no(). :param value: Return value of click.prompt(..., ..., type=click.BOOL) :returns: Returns True/False. """ return True if value in [True, 'True', 1, '1', 'yes', 'y'] else False
def get_obj_repr_unicode(obj): """Returns a string representation of an object converted to unicode. In the case of python 3, this just returns the repr() of the object, else it converts the repr() to unicode. """ obj_repr = repr(obj) return obj_repr
def calc_neighbour_positions(_cell_coord: tuple) -> list: """ Calculate neighbouring cell coordinates in all directions (cardinal + diagonal). Returns list of tuples. """ """Creates and returns coordinates of all cells around the current cell""" neighbour: list = [ (_cell_coord[0] - 1, _cell_co...
def level_order_traversal(node): """ @ref https://leetcode.com/problems/binary-tree-level-order-traversal/description/ @ref https://www.goodtecher.com/leetcode-102-binary-tree-level-order-traversal/ @details O(N) time since each node processed exactly once. O(N) space to keep output structure that ...
def hello_world(name='world'): """A hello world func""" return f"Hello {name}"
def class_to_path(cls): """Turn Class (Class or instance) into module path""" return '%s.%s' % (cls.__module__, cls.__name__)
def cut_rod2(p, n, r={}): """Cut rod. Same functionality as the original but implemented as a top-down with memoization. """ q = r.get(n, None) if q: return q else: if n == 0: return 0 else: q = 0 for i in range(n): ...
def string_diff(str1_orig, str2_orig, maxlen=11, backtrack=7): """ Compares strings, returns a part of str2 depending on how many chars into the string the first difference can be found. If the difference is after maxlen, a prefix of str is removed so that only the 'backtrack'-last letters of the co...
def build_command(args): """ Given a dictionary of arguments, build it back into a command line string. """ cmd = [] for opt in args: # Don't pass along store true args that are false if args[opt] in [False, None]: continue cmd.append("--%s" % opt.replace("_", "-"...
def _all_close(values, other_value, threshold): """Return true if all values are within threshold distance of other_value.""" for value in values: if abs(value - other_value) > threshold: return False return True
def one_of_k_encoding_unk(x, allowable_set): """ taken from https://github.com/thinng/GraphDTA function which one hot encodes x w.r.t. allowable_set with one bit reserved for elements not in allowable_set x: element from allowable_set allowable_set: list list of all known elements ...
def sample_to_time(sample, samplerate): """Returns times corresponding to samples in a series.""" return sample / float(samplerate)
def bipolar(signal): """ Inverse to unipolar(). Converts an unipolar signal to a bipolar signal. """ return signal * 2.0 - 1.0
def remove_duplicates(doi_table): """Remove all duplicate DOI entries. We exploit that each element in a set must be unique""" doi_set = set(doi_table) doi_table = list(doi_set) doi_table.sort() return doi_table
def json_replace(json_obj, **values): """ Search for elements of `{"{{REPLACE_PARAM}}": "some_key"}` and replace with the result of `values["some_key"]`. """ if type(json_obj) is list: return [json_replace(x, **values) for x in json_obj] elif type(json_obj) is dict: new = {} ...
def banner_command(argv): """Return sanitized command-line description. |argv| must be a list of command-line parameters, e.g. sys.argv. Return a string corresponding to the command, with platform-specific paths removed.""" # Remove path from first parameter argv = argv[:] argv[0] ...
def _strip_external_workspace_prefix(short_path): """If this target is sitting in an external workspace, return the workspace-relative path.""" if short_path.startswith("../") or short_path.startswith("external/"): return "/".join(short_path.split("/")[2:]) return short_path
def orbital_to_shell_mapping(ncore,nopen,npair): """\ Map the orbitals to shells. All the core orbitals are in the first shell. Then each orbital has its own shell. >>> orbital_to_shell_mapping(1,0,0) [0] >>> orbital_to_shell_mapping(2,0,0) [0, 0] >>> orbital_to_shell_mapping(2,1,0) ...
def test_inner(cond): """ >>> test_inner(True) {} >>> test_inner(False) Traceback (most recent call last): ... NameError: free variable 'a' referenced before assignment in enclosing scope """ if cond: a = {} def inner(): return a return inner()
def sub(x, y): """Substract two numbers""" return (x - y)
def search(query, dict): """ Search the person's birthday is in the dict or not. Arguments: query -- the name of person the user want to know. dict -- a dictionary needed to be print it's key. Returns: birthday -- the birthday of the query. """ return dict[query] if query...
def dump_dt(dt): """ Dump a naive datetime to UTC format """ if dt is None: return None return dt.isoformat('T') + 'Z'
def call_method(obj, method_name, *args): """Call method_name from obj with *args. Using in template: {% call_method obj 'get_something' '10' %} """ method = getattr(obj, method_name) return method(*args)
def _process_opt(opt): """ Helper function that extracts certain fields from the opt dict and assembles the processed dict """ return {'password': opt.get('password'), 'user': opt.get('user'), 'indexer': opt.get('indexer'), 'port': str(opt.get('port', '8080')), ...
def fixture_base_context(spring_api, cram_api) -> dict: """context to use in cli""" return { "spring_api": spring_api, "cram_api": cram_api, }
def getIdx(lst, element): """ getIdx(lst, element) Function to find more than one index with an wanted value in binary data. Main code is taken from https://stackoverflow.com/questions/... 6294179/how-to-find-all-occurrences-of-an-element-in-a-list Input: lst: List of binary data element: value to ...
def get_coordinates_here(response): """ Returns a tuple with the lat/long :param response: dict - The here response object :return: double, double """ try: lat = response["Response"]["View"][0]["Result"][0]["Location"][ "NavigationPosition" ][0]["Latitude"] lo...
def average(nums): """Find mean of a list of numbers.""" avg = sum(nums) / len(nums) return avg
def test_simple_closure(a, b): """Test some trivial closures.""" def f(): return a + 1 def g(): return b + 2 return f() * g()
def convertShape2String(shapeInt): """ Get the string corresponding to shape integer """ if shapeInt == -1: return "end" if shapeInt == 0: return "idle" if shapeInt == 1: return "cross" if shapeInt == 2: return "circle" return "error"
def filter_clusters(clusters, reference, minsize, mincontigs, checkpresence=True): """Creates a shallow copy of clusters, but without any clusters with a total size smaller than minsize, or fewer contigs than mincontigs. If checkpresence is True, raise error if a contig is not present in reference, else ...
def swap(value1, value2): """Return the value1 and value2 swapped. return tuple (value2, value1) """ return (value2, value1,)
def grid_range(sheet_id, min_row, min_col, max_row, max_col): """Returns GridRange json. min_row, min_col, max_row, max_col: int (None if unbound) :returns: GridRange json """ if min_row is None: start_row_index = None else: start_row_index = min_row - 1 if min_col is None...
def find_nth(string, substring, n): """Finds the index of the nth instance of the given substring from the given string""" location = string.index(substring) while n > 1: location = string.index(substring, location+len(substring)) n -= 1 return location
def custom_formatwarning(message, category, filename, lineno, line=""): """Ignore everything except the message.""" return "Warning: " + str(message) + "\n"
def get_image_uuid(volume_handler): """ fetch image uuid from volume handler """ image_id = volume_handler.split('-') if len(image_id) < 9: return None img_id = "-" return img_id.join(image_id[len(image_id)-5:])
def is_binary_in_path(path, binary): """ Checks if the given binary is available in the specified path. Returns: True or False (Boolean) """ import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) path = path.strip('"') exe_file = os.pat...
def validate_reponse_with_serializer(serialized_obj, response): """ Often times we wish to test a JSON response to make sure it matches expected serialization. This utility function takes in such a response and the serialization and returns true or false depending on if all fields match. """ ...
def generate_balanced_parentheses(n: int): """generate all balanced parentheses strings of length 2n copied this from leetcode :) """ ans = [] def backtrack(S = [], left = 0, right = 0): if len(S) == 2 * n: ans.append("".join(S)) return if left < n: ...
def extract_before(source: str, end: str) -> str: """Extract all of the characters before start. :param source: The input string from which to extract a substring. :param end: The substring that marks the place where extraction will end. :param return: A substring that is extracted from ``source``. ...
def ordered(obj): """ This function will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable) """ if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) if isinstance(obj, list): retu...
def parse_option(option: str) -> str: """Helper function to parse a provided option value. """ if "=" not in option: return f" :{option.strip()}:" key, value = option.split("=") return f" :{key.strip()}: {value.strip()}"
def filter_posts(line): """ Perform sentiment analysis and identify tweets that indicate violence :param line: list List from dataset """ keywords = ['riot', 'protest', 'violence', 'angry', 'sad', 'mourn', 'http'] for k in keywords: if k in line[0]: return True
def check_businesses(user_id, REVIEWS): """ returns a list of businesses a user has placed reviews for """ businesses = [] for city, reviews in REVIEWS.items(): for review in reviews: if review["user_id"] == user_id: businesses.append(review['business_id']) re...
def poly(*args): """ f(x) = a * x + b * x**2 + c * x**3 + ... *args = (x, a, b, ...) """ # Add a warning for something potentially incorrect if len(args) == 1: raise Exception("You have only entered a value for x, and no coefficients.") # Unpack arguments x = args[0] # The x...
def mult(v1,m): """multiplies two vector""" return v1[0]*m,v1[1]*m
def first_phrase(name): """ returns phrase, given lab member Parameters ---------- name : str lab member Returns ---------- utterance : string phrase simulating specific lab member """ if name == 'gina': return('I jus...
def follow_path(obj, path, create_missing=False): """Given a dict and a '/' separated path, follow that path and return the value at that location. Examples: obj={ a: { b: { c: { d: 'foo' } } } } path="/a/b" returns obj['a']['b'] Arguments: obj: the object to look in path: the path to foll...
def _get_tag_path(repository, tag=None): """Return the path for a tag, or list of tags if tag is empty. """ if tag: return '/acr/v1/{}/_tags/{}'.format(repository, tag) return '/acr/v1/{}/_tags'.format(repository)
def nameMe(partSfx, partName, endSuffix): """Set the name convention of all nodes eg L_Main_Ctrl""" if partSfx and partName and endSuffix: return "%s_%s_%s" % (partSfx, partName, endSuffix)
def bytes_to_uint32(b0, b1, b2, b3): """Convert two bytes to 16bit signed integer.""" value = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) return value
def isSafe(i, j, visited, graph): """ This function to check whether a given cell (row, col) can be included in DFS or not :param i: current row number :param j: current column number :param visited: 2-d grid of visited nodes :param graph: given 2-d grid :return: bool """ r...
def dict_to_tuple(courses_dict): """ Function that converts a dict to a list of tuple containing each key and its corresponding value :param courses_dict: Dictionary to be converted :return: List of tuples """ list_ = [] for course in courses_dict: list_.append((course, cours...
def repeat_list_as_string_2(my_list, number_of_repetitions): """ :param my_list: list :param number_of_repetitions: int :return: str """ return ''.join(number_of_repetitions * my_list)
def uid_query(uid: str) -> list: """ Construct RFC 4512-compatible LDAP query for a single NetID account Usage: .. highlight:: python .. code-block:: python ldap_query = ldap_query.ual_test_query('<netid>') > ['(uid=<netid>)'] :param uid: NetID handle/username :return: LD...
def ceil(x): """ Simulation to math.ceil No doctest needed """ if int(x) != x: return int(x) + 1 return int(x)
def track_length_string(length): """Convert track length in microseconds into human readable format :param length: track length in microseconds :returns: formatted string """ us = length % 1000 ms = int((length / 1000) % 1000) s = int(length / 1000000) minutes = int(s / 60) s = s - m...
def string_convert(value): """ Quotes variables embedded within templates :param - value to be quoted E.g: 6 -> '6' "mysql" -> "'mysql'" """ return "'{}'".format(str(value))
def same_origin(origin1, origin2): """ Return True if these two origins have at least one common ASN. """ if isinstance(origin1, int): if isinstance(origin2, int): return origin1 == origin2 return origin1 in origin2 if isinstance(origin2, int): return origin2 in o...
def pad_chunk_columns(chunk): """Given a set of items to be inserted, make sure they all have the same columns by padding columns with None if they are missing.""" columns = set() for record in chunk: columns.update(record.keys()) for record in chunk: for column in columns: ...
def split_block_lot(blocklot): """ Separates out block data from block and lot Args: blocklot (str): The original block and lot data from the file Returns: [block, lot] (str): A list with the block and lot stored separately as strings """ if len(blocklot) == 6: ...
def keyfilter(predicate, d, factory=dict): """ Filter items in dictionary by key >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> keyfilter(iseven, d) {2: 3, 4: 5} See Also: valfilter itemfilter keymap """ rv = factory() for k, v in d.i...
def percentage_to_mark(percentage): """Transform percentage values to mark label.""" thresholds = { 99: 'A+++', 95: 'A++', 90: 'A+', 80: 'B', 70: 'C', 60: 'D', 50: 'E', 40: 'F' } for threshold, mark in thresholds.items(): if percent...
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', '*?????*', '*?????*', ...
def _get_skip_step(iteration): """ How many steps should the model train before it saves all the weights. """ if iteration < 100: return 30 return 100
def get_page_marks(pageIndex, pageSize): """ :param pageIndex: :param pageSize: :return: """ lower_mark = (int(pageIndex) - 1) * int(pageSize) upper_mark = int(pageIndex) * int(pageSize) return {'lm': lower_mark, 'um': upper_mark}
def enquote(s): """Return string argument with surrounding quotes, for serialization into Python code.""" if s: if isinstance(s, str): return "'{}'".format(s) else: return s return None
def get_sequential_chunk(tests, modulo, modulo_index, is_sorted=False): """ >>> get_sequential_chunk(range(10), 4, 0) [0, 1, 2] >>> get_sequential_chunk(range(10), 4, 1) [3, 4, 5] >>> get_sequential_chunk(range(10), 4, 2) [6, 7] >>> get_sequential_chunk(range(10), 4, 3) [8, 9] >>...
def _manhattan_distance(x0, y0, x1, y1): """Get manhattan distance between points (x0, y0) and (x1, y1).""" return abs(x0 - x1) + abs(y0 - y1)
def seconds2human(seconds, keep_short=True, full_name=False): """Returns a human readable time range string for a number of seconds. >>> lib.base3.seconds2human(0.125) '0.12s' >>> lib.base3.seconds2human(1) '1s' >>> lib.base3.seconds2human(59) '59s' >>> lib.base3.seconds2human(60) '...
def _dataset_fields(geno): """ return the dataset metadata fields created for dataset definition geno """ return {'title': geno['title'], 'notes': geno.get('notes', '')}
def get_probability(x, x1, p1, x2, p2): """Calculate probability using a ramped function. The subsections and parameters below reflect a series of ramp functions we use to calculate various probabilities. p1 |----+ | \ | \ | \ p2 | +------- ...
def validate_file_transfer(filename, file_transfer_status): """Validate file transfer. Keyword arguments: filename -- name of file being copied file_transfer_status -- true (success) or false (failed) :param filename: str :param file_transfer_status: bool """ if not file_transfer_statu...
def validate_idxs(actual_idxs, req_idxs=[], invalid_idxs=[], idx_label="project", msg=""): """ Check that actual list of indexes contains all required indexes and none of the invalid indexes. If any required indexes are missing, or any invalid indexes are present, return an error messa...