content
stringlengths
42
6.51k
def get_window_context(idx, tree, size): """Return a list of words within a 2*size window around the idx position.""" return [node.token for node in tree[max(0, idx-size) : idx] + tree[idx+1 : idx+size+1]]
def identity(t): """ Returns its single argument. :returns: Its argument. """ return t;
def parse_zone_id(full_zone_id): """Parses the returned hosted zone id and returns only the ID itself.""" return full_zone_id.split("/")[2]
def single_number_2(nums): """ Find single number in given array :param nums: given array :type nums: list[int] :return: single number :rtype: int """ ones, twos = 0, 0 for n in nums: # The expression "one & arr[i]" gives the bits that are # there in both 'ones' and ...
def _normalize_filenames(filenames): """Returns a list of strings from a string or a list of strings. :rtype: List[str] """ if filenames is None or filenames == "": return [] if isinstance(filenames, list): return filenames if isinstance(filenames, (str,)): # It's a sing...
def calculate_return_rate(net_values): """ Args: net_values: net values of fund as a list Returns: return_rate """ return_rate = [] for i in range(1, len(net_values) - 1): return_rate.append((net_values[i] - net_values[i - 1]) / net_values[i - 1]) return return_rate
def _generate_source_tree(sources, sizes): """Generates a dict equivalent to the source tree. Each element is either a file (so its value is its size) or a folder (so its value is a dictionary of all the files or folders found inside it). |sources| is a list of files to build the source tree out of, and |sizes...
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 # lines 1-5 creates a function'fib' to calculate the Fibonacci no of n while n >= 0: i, j = j, i + j n = n - 1 return i
def ensurePositiveCount(count=None): """Ensures the given count is an integer with value greater than or equal tozero.""" if count is None or (isinstance(count, int) is False) or count <= 1: p_count = int(1) else: p_count = int(count) return p_count
def generateTwapParams(security, urgency): """generate params for twap algo""" params = {} params['urgency'] = {security: urgency} # bid + 0.25 * bid_ask_spread params['price_range_factor'] = 0.1 params['cycle'] = 1000 params['lifetime'] = 60000 # 10 minutes ...
def mcNuggetPackage(x,y,z): """returns the largest number that does not divide by multiples of the three numbers that are input. Input integers > 1 ordered from smallest to largest.""" nonDividable = (0,1) testNumber = 1 while nonDividable[-1] - nonDividable[-2] <= y-x or nonDividable[-1] - nonDivid...
def is_adjacency_two_colorable(adjacency): """Try to color a data of adjacency with two colors only withtout any element adjacent to each other having the same colour. Parameters ---------- adjacency : dict Dictionary of adjacency between elements, each elements points to the list of adjacent e...
def pluck(data, *keys): """ Returns `keys` values from a dict. Good for multi assigning variables straight from a dict. """ return [data.get(k) for k in keys]
def quote_wrap(s): """Does not need to escape because `s` is assured not to have `"` """ return '"' + s + '"'
def create_intervals(data_len, interval_no): """ split the interval [0, data_len] into a list of equal intervals :param data_len: length of the data :param interval_no: number of intervals to be split into :return: list of intervals (start, end) """ step = data_len // interval_no interva...
def items_equivalent(list1, list2, comparator): """Returns whether two lists are equivalent (i.e., same items contained in both lists, irrespective of the items' order) with respect to a comparator function.""" def contained(item): for _item in list2: if comparator(item, _item): ...
def push_key_prefix(prefix, d): """ Returns a dict with the same values as d, but where each key adds the prefix, followed by a dot. """ return {prefix + "." + k: v for k, v in d.items()}
def list_articles(article_compilation): """List articles for anonymous users to view.""" return { 'article_compilation': article_compilation, }
def _map_non_formatted_money_to_version_with_currency(cost, resource, token): """ Map a non formatted money str (e.g., 0.001) to a version with currency (e.g., $0.001). :param cost: float with the value that we want to transform :param resource: resource containing all the values and keys :param to...
def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2), inner(word3))
def count_shares_owned(transactions): """ Sum the totals of buy/sell orders to get a current list of stocks owned. """ stocks = {} for t in transactions: symbol = t.stock.symbol stocks.setdefault(symbol, 0) stocks[symbol] += t.quantity if stocks[symbol] == 0: ...
def discretize_probability(val): """ return 1 if given value is greater than 0.5, otherwise return 0 """ return 1. if val >= 0.5 else 0.
def checksum(number, bits=4): """ Calculate the checksum of a number. The checksum of length N is formed by splitting the number into bitstrings of N bits and performing a bitwise exclusive or on them. :param number: Number to generate the check :type number: int :return: Checksum of the ...
def factorielle(n): """ This function calculates the factorial of the integer n, i-e the product of every integer beetwen 1 and n. """ if n == 0 or n == 1: return 1 else: return n*factorielle(n-1)
def listify(o): """Ensure an object is a list by wrapping if necessary""" if isinstance(o, list): return o return [o]
def __vertexUnpack3(vertex): """ Extend vertex to 3 dimension. :param vertex: :return: """ if len(vertex) == 2: vertex = vertex + (0,) return vertex
def flatten_me(lst): """Flatten a list of lists or return an already flat list.""" n_lst = [] for i in lst: try: for j in i: n_lst.append(j) except: n_lst.append(i) return n_lst
def chunk_list(list_to_chunk: list, chunk_size: int) -> list: """Chunks given list into chunks of a given size.""" return [ list_to_chunk[i : i + chunk_size] for i in range(0, len(list_to_chunk), chunk_size) ]
def merge_ordered_list(in_list1: list, in_list2: list) \ -> list: """ Merge two ordered list :param in_list1: the first source list :param in_list2: the second source list :return: the merged list """ _list1 = in_list1.copy() _list2 = in_list2.copy() _output_list = [] ...
def get_range(value, startidx=0): """ Filter - returns a list containing range made from given value Usage (in template): <ul>{% for i in 3|get_range %} <li>{{ i }}. Do something</li> {% endfor %}</ul> Results with the HTML: <ul> <li>0. Do something</li>...
def limit_scope_length(start_end_pos, valid_length, max_phrase_words): """filter out positions over scope & phase_length > 5""" filter_positions = [] for positions in start_end_pos: _filter_position = [pos for pos in positions \ if pos[1] < valid_length and (pos[1]-pos[0]...
def bitstr_to_int(a): """ Convert binary string to int """ return int(a, 2)
def row2dict(row): """Takes sqlite3.Row objects and converts them to dictionaries. This is important for JSON serialization because otherwise Python has no idea how to turn a sqlite3.Row into JSON.""" x = {} for col in row.keys(): x[col] = row[col] return x
def enter_exit(): """with: Use and release a resource.""" class _Resource: def __enter__(self): return "enter concert" def __exit__(self, error_class, error, traceback): pass with _Resource() as resource: return resource
def get_P(tasks): """ Get the HB product for the given periodic task set. Parameters ---------- tasks : list of pSyCH.task.Periodic Set of periodic tasks, for which the HB product needs to be computed. Returns ------- float HB product for the task set. """ P = ...
def position(initial: int, steps: int) -> int: """ >>> position(9, 10) 45 >>> position(9, 9) 45 >>> position(2, 4) 2 >>> position(2, 6) -3 >>> position(-4, 2) -9 """ return (initial + (initial - steps + 1)) * steps // 2
def multiplication_table(row, col): """ Function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. Each value on the table should be equal to the value of multiplying the number in its first row times the number i...
def check_format(letters): """This function is to check if user input is in correct format""" if len(letters) != 7: return False else: for i in range(0, 7, 2): if not letters[i].isalpha(): return False for i in range(1, 6, 2): if not letters[i] == ' ': return False
def is_viv_ord_impname(impname): """ return if import name matches vivisect's ordinal naming scheme `'ord%d' % ord` """ if not impname.startswith("ord"): return False try: int(impname[len("ord") :]) except ValueError: return False else: return True
def pairs_from_list(lights): """Generate a list of pairs to enable from-each-end lighting.""" length = len(lights) half = int(length / 2) offset = 0 centre = None if length % 2 == 1: centre = lights[half] offset = 1 left = lights[:half] rh_start = half + offset rig...
def text_from_notes(notes, note_type): """Returns a content string for a specific note from an array of notes. Args: notes (list): note list note_type (str): note type """ description_strings = [] for note in [n for n in notes if n["type"] == note_type]: description_strings ...
def repr_iterable(iterable, token='\n'): """Return a token separated string of joined iterables without index""" return '\n'.join('{}'.format(elem) for index, elem in enumerate(iterable))
def int_or_float(val): """Used for filtering sklearn arguments that should be treated as float if between 0 and 1 and as int otherwise """ if val < 1: return float(val) else: return int(val)
def json_utf8_encode(obj: object) -> object: """Binary encode all strings in an object. :arg obj: Object. :returns: Object with binary encoded strings. """ if isinstance(obj, str): return obj.encode('utf-8') if isinstance(obj, list) or isinstance(obj, tuple): return [json_utf8_...
def is_capital_letter(par: str) -> bool: """check if a paragraph is all in capital letters""" return all(word.isupper() for word in par if word not in [" ", "\n"])
def query_table1(session_id, item_in_session): """ This function returns the SQL neccessary to get the artists, songs, and lengths of the songs with the specified session id passed as an argumemt and specified item in session passed as an argumemt. """ query = """select artist_name, song_name, ...
def bpmsimple(beatlist): """ computes bpm based on low-passed and high-passed beat times :param beatarray: array of low-passed beats :param hbeatarray: array of high-passed beats :return: approximate bpm """ length = len(beatlist) if length >= 2: total = 0 for dif in beat...
def make_full_mask(wave_length): """ Make a mask that can mask full wave data. :param wave_length: length of raw wave. :return: a list containing only one mask tuple(begin, end). """ mask = [(0, wave_length)] return mask
def l1_bit_rate(l2br, pps, ifg, preamble): """ Return the l1 bit rate :param l2br: l2 bit rate int bits per second :param pps: packets per second :param ifg: the inter frame gap :param preamble: preamble size of the packet header in bytes :return: l1 bit rate as float """ return l2br...
def max_sequence(listeners, price): """ Compute the maximum earnings for a sequence of length 'length'. An instance of the maximum subarray problem. :param listeners: list of listeners for each break slot :param price: price per break :return: maximum profit """ best = 0 cur_...
def make_error(status_code, error_message=None, aio=False): """Returns an error as a dict to be consumed by the SymphonyApiMocker like: error = make_error() m.register_uri('GET', SOME_URL, **error) """ if error_message is None: # Replace with the generic Symphony error message ...
def tile_key(tile): """Key which sorts tiles into blocks""" v = 2 ** 16 * int(tile[0] / 8) + int(tile[1] / 8) return v
def freq_to_channel(freq): """ freq -- frequqncy in Hz return -- channel number """ if 2412000000 <= freq <= 2472000000: return 1 + int((freq - 2412000000) / (5 * 1000000)) if freq == 2484000000: return 14 if 5035000000 <= freq <= 5825000000: return 7 + int((freq - 50...
def _compare_glue_job_params(user_params, current_params): """ Compare Glue job params. If there is a difference, return True immediately else return False :param user_params: the Glue job parameters passed by the user :param current_params: the Glue job parameters currently configured :return: Tru...
def m1m2_to_nu(m1,m2): """Symmetric mass ratio from m1, m2""" return m1*m2/(m1+m2)**2
def is_even(x): """ True if x is even, false otherwise. Args: x (float): Number to test. Returns: bool: True if even. """ return x % 2 == 0
def __copy_options(user_options, default_options): """If user provided option so we use it, if not, default option value should be used""" for k in default_options.keys(): if k not in user_options.keys(): user_options[k] = default_options[k] return user_options
def _pluralize_granularity(granularity): """Pluralize the given granularity""" if 'century' == granularity: return "centuries" return granularity + "s"
def _build_url(*args): """ Build a URL from a given list of arguments. """ items = [] for idx, arg in enumerate(args): arg = "%s" % arg if arg.startswith("/"): arg = arg[1:] if arg.endswith("/") and not idx + 1 == len(args): arg = arg[:-1] items.append...
def jaccard_similarity(first, second): """ Given two sets, returns the jaccard similarity between them :param first: a set :param second: a set :return: the similarity as a double """ return len(first & second) / len(first | second)
def base36encode(number, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): """Converts an integer to a base36 string.""" if not isinstance(number, int): raise TypeError('number must be an integer') base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <...
def get_curve_value(x_value, c0, c1, c2, c3): """Get the curve y_value according to x_value and curve analysis formula y = c3 * x**3 + c2 * x**2 + c1 * x + c0 Args: x_value: value of x c3: curvature_derivative c2: curvature c1: heading_angle c0...
def float_overlap(min_a, max_a, min_b, max_b): """Get the overlap between two floating point ranges. Adapted from https://stackoverflow.com/questions/2953967/built-in-function-for-computing-overlap-in-python Parameters ---------- min_a : :obj:`float` First range's minimum max_a : :obj:...
def rgbToHtmlColor(r, g, b): """ Return HTML color '#hhhhhh' format string. """ return "#%02X%02X%02X" % (r, g, b)
def reject_h0(crit_val, value, tail): """ Function to determine if reject the null hypothesis or not reject it based on the tail-type test. Parameters: -------------------------- crit_val : tuple, float Critical values to consider. value : float, double Value to...
def previously_valid_data(data: list, invalid_data: set): """ Return a list of valid data from a input list. When an element is in the invalid data set, is must be replaced with the previous valid data. >>> previously_valid_data(['0', '2', None, '1', None, '0', None, '2'], {None}) ['0', '2', '2', '...
def exception_string(e): """Return an interpreter like error string from an exception.""" s = type(e).__name__ # If e is not a built-in exception add module to exception name. if hasattr(e, '__module__'): s = '{}.{}'.format(e.__module__, s) # If e has a message add ':' and message. if ...
def csg_table_header(x: str): """Create a CSG table with its default values.""" return f""" {x} The following table contains the input options for CSG, .. list-table:: :header-rows: 1 :align: center * - Property Name - Description - Default Value"""
def maplabels(labels): """ Returns a dictionary mapping a set of labels to an index :param labels: :return: """ poslabels = {} for lab, p in zip(labels,range(len(labels))): poslabels[lab] = p return poslabels
def linear_search(collection, search_value): """Return element's index if it exist in collection. Args: collection: iterable collection search_value: search element Returns: index (int): index elementa if it exist, else -1 """ for (index, element) in enumerate(collection): ...
def toggle_bit(a, order): """ Set the value of a bit at index <order> to be the inverse of original. """ return a ^ (1 << order)
def _first_or_blank_string(items): """ Return first `item` from `items` or blank string. Args: items (list/tuple): Indexable object. Returns: str: Content of first item, or blank string. """ if not items: return "" return items[0]
def degree_to_compass(degree): """ Converts the wind direction from degrees to a compass bearing. Shamelessly copied from @steve-gregory https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words """ val = int((degree / 22.5) + .5) bearings = ["N","NN...
def format_crypto(crypto_mail, tag): """ Genera un valore booleano sulla base del tag passato in input :param crypto_mail: valore impostato tabella settings per l'invio della mail :param tag: CryptoTag :return: True/False """ if crypto_mail == tag: return True return False
def power(intList, num, step): #5 """ Performs the nth power to list items and num with index increasing by step """ newIntList = [] thingsToAdd = [] for index in range(0, len(intList), step): thingsToAdd.append(index) for index, item in enumerate(intList): if index in thing...
def key_exists(element, *keys): """ Check if *keys (nested) exists in `element` (dict). :param keys: :return: True if key exists, False if not """ if type(element) is not dict: raise AttributeError('keys_exists() expects dict as first argument.') if len(keys) == 0: raise Attr...
def invert(d): """ Invert dictionary. >>> d = { ... "cat1": ["a", "b"], ... "cat2": ["c", "d"], ... } >>> invert(d) {'a': 'cat1', 'b': 'cat1', 'c': 'cat2', 'd': 'cat2'} """ return {v: k for k, values in d.items() for v in values}
def strip(value): """ REMOVE WHITESPACE (INCLUDING CONTROL CHARACTERS) """ if not value or (ord(value[0]) > 32 and ord(value[-1]) > 32): return value s = 0 e = len(value) while s < e: if ord(value[s]) > 32: break s += 1 else: return "" fo...
def unique_list(seq): """ Delete redundant entrances within a list, keeping the original order """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def bot_key(version, desc, part=None): """Returns a memcache key for bot entries.""" key = 'code-%s-%s' % (version, desc) if part is not None: key = '%s-%d' % (key, part) return key
def filter_dict_page(pagetext_list, keyslist): """Filters webtext of a given .html page, which is parsed and in list format, to only those strings within pagetext_list containing an element (word or words) of inputted keyslist. Returns list filteredtext wherein each element has original case (not coe...
def double_quote(name: str) -> str: """Represent a identify in SQL.""" if name.startswith('"') and name.endswith('"'): return name return '"%s"' % name
def add(a, b): """ add two nums :param a: first num :param b: second num :return: result """ c = a + b return c
def bytes_to_int(x_bytes: bytes) -> int: """ Convert bytes to integer """ return int.from_bytes(x_bytes, "big")
def _get_tf(pos, n): """ Calculate tf """ pos = sorted(pos) freq = {} for doc in pos: if doc in freq: freq[doc] += 1 else: freq[doc] = 1 for f in freq.keys(): freq[f] = freq[f]/n[f] return freq
def craft_post_header(length=0, content_length=True): """ returns header with 'content-length' set to 'num' """ if content_length: header = b"POST /jsproxy HTTP/1.1\r\nContent-Length: " header += "{}\r\n\r\n".format(str(length)).encode() else: header = b"POST /jsproxy HTTP/1.1\r\n\r...
def _maxBandwidthAvailable(a,b): """ Helper Function: Prints highest of two bandwidth amounts Author: David J. Stern Date: DEC 2017 Parameters: a: (int): number b: (int): number Returns: (int) highest of two numbers compared. The number if they are equal. ...
def _die_range_calc(die_type, point_min, point_max): """ Returns the largest number of dice of a given type and any adjustments necessary to provide a range that matches the min and max points given. Inputs: - Outputs: """ #pdb.set_trace() if point_max < die_t...
def flatten_nested(iterable): """ Recursively flatten nested structure of tuples, list and dicts. """ result = [] if isinstance(iterable, (tuple, list)): for item in iterable: result.extend(flatten_nested(item)) elif isinstance(iterable, dict): for key, value in sorted(iterab...
def get_ability_modifier(stat): """ Get ability modifier for a stat """ # array of dnd ability modifiers modifiers = { "1": "-5", "2": "-4", "3": "-4", "4": "-3", "5": "-3", "6": "-2", "7": "-2", "8": "-1", "9": "-1", "10": "+0", "11": "+0", "12": "+1", "13": "+1", "14": "+2", "15...
def list_flatten(lst): """ The flatten function here turns the list into a string, takes out all of the square brackets, attaches square brackets back onto the ends, and turns it back into a list. :type lst: list :example: """ return eval("[" + str(lst).replace("[", "").replace("]", "") + ...
def lingray(x, a, b): """Auxiliary function that specifies the linear gray scale. a and b are the cutoffs.""" return 255 * (x-float(a))/(b-a)
def find_bucket_key(s3_path): """ This is a helper function that given an s3 path such that the path is of the form: bucket/key It will return the bucket and the key represented by the s3 path """ s3_components = s3_path.split("/") bucket = s3_components[0] s3_key = "" if len(s3_comp...
def pad(str_in, mode=0, in_type=0): """ mode : pad (0) , unpad (1) in_type: plaintext (0) , key (1) """ sl = len(str_in) if mode == 0: if in_type == 0: if sl < 16: num = 16 - (sl % 16) str_in += chr(num) * num # adds padding elements at the en...
def arr_to_bin(arr): """Byte array -> string of binary representation (8 bits per byte).""" return ''.join([bin(b)[2:].zfill(8) for b in arr])
def is_repeated_chars(text: str) -> bool: """Find repeated characters in a redaction. This often indicates something like XXXXXXXX under the redaction or a bunch of space, etc. :param text: A string to check :returns: True if only repeated characters, else False """ if len(text) <= 1: ...
def getkey(d,key,default=None): """gets key from dict (d), if key does not exist, return default""" if key in d: return d[key] else: return default
def Contains(field): """ A criterion used to search for records where `field` id defined. For example * search for cases that have the custom field `customer` Arguments: field (str): field name Returns: dict: JSON repsentation of the criterion ```python ...
def update_input(job, business, catpial_gains, rental_income, other_income, housing_expense, transportation_expense, utility_expense, grocery_expense, debt_repayment_expense, leisure_expense, ...
def is_boolean(s): """ Determine if a string is a boolean string (e.g.: "True" or "False"). Args: s (str): The string. Returns: bool: True if the string is a boolean string. """ if str(s).lower() in ['true', 'false']: return True else: return False