content
stringlengths
42
6.51k
def binary_search(n,arr,ele): """ Function to perform iterative binary search params: n : Size of input array arr : input array ele : element to be searched in array returns: index : index of element if found else -1. """ left = 0 right = n-1 while left<...
def mnormalize(matrix): """Scale a matrix according to the value in the center.""" width = len(matrix[0]) height = len(matrix) factor = 1.0 / matrix[int(height / 2)][int(width / 2)] if 1.0 == factor: return matrix for i in range(height): for j in range(width): matrix[...
def PickHistoryName(args): """Returns the results history name to use to look up a history ID. The history ID corresponds to a history name. If the user provides their own history name, we use that to look up the history ID; If not, but the user provides an app-package name, we use the app-package name with ' ...
def main(args=None): """Console script for chutie.""" # click.echo("See the 'screenshots' command.") return 0
def linear_search(a, v): """Linear search algorithm. If v exist in a, returns index. Returns None if not found.""" for index, e in enumerate(a): if e == v: return index return None
def rgb_to_brightness(r, g, b, grayscale=False): """ Calc a brightness factor according to rgb color """ if grayscale: return 0.2126*r + 0.7152*g + 0.0722*b else: return 0.267*r + 0.642*g + 0.091*b
def parse_name(text): """Split an arbitrary (maybe empty) word from the beginning of a string.""" lth = 0 while text[lth] not in ' ,*%();': lth += 1 return text[:lth], text[lth:]
def poly5(x, a5, a4, a3, a2, a1, a0, export=False): """Polynom 5th degree for fitting. :param x: parameter :param a5: coeff :param a4: coeff :param a3: coeff :param a2: coeff :param a1: coeff :param a0: coeff :param export: enable text output of function :returns: function -- p...
def make_fully_qualified_url(url): """ Ensure url is qualified """ if url.startswith("//"): return "https:" + url if url.startswith("/"): return "https://en.wikipedia.org" + url assert url.startswith("http"), "Bad URL (relative to unknown location): " + url return url
def xml_escape(s): """Escape XML meta characters '<' and '&'.""" answer = s.replace("<", "&lt;") answer = answer.replace("&", "&amp;") return answer
def quadraticProbe(hk, size, i): """Default quadratic probe using c1=1/2 and c2=1/2.""" return int(hk + 0.5 + i*i*0.5) % size
def summation(n, term): """Sum the first n terms of a sequence. >>> summation(5, double) 30 >>> summation(5, square) 55 >>> summation(5, cube) 225 """ total = 0 k = 1 while k <= n: total = total + term(k) # <-- FIX THIS LINE! k += 1 return total
def func_xy_kwargs(x, y, **kwargs): """func. Parameters ---------- x, y: float kwargs: dict Returns ------- x, y: float kwargs: dict """ return x, y, None, None, None, None, None, kwargs
def find_substring(s, indicator, terminator): """ Given a string, returns the substring strictly between the indicator and terminator strings, if they exist. Otherwise returns None. It is possible that an empty string is returned if the indicator and terminator are adjacent. """ i = s.fi...
def distance_point_segment(ps1, ps2, external_p): """Returns the distance between segment and point. Don't ask why.""" x3, y3 = external_p x1, y1 = ps1 x2, y2 = ps2 px = x2-x1 py = y2-y1 norm = px*px + py*py u = ((x3 - x1) * px + (y3 - y1) * py) / float(norm) if u > 1: u...
def similarity( M_c, X_L_list, X_D_list, given_row_id, target_row_id, target_column=None): """Returns the similarity of the given row to the target row, averaged over all the column indexes given by col_idxs. Similarity is defined as the proportion of times that two cells are in the same ...
def remove_keys(dct, keys=[]): """Remove keys from a dict.""" return {key: val for key, val in dct.items() if key not in keys}
def generate_model_masks( depth, mask = None, masked_layer_indices = None): """Creates empty masks for this model, or initializes with existing mask. Args: depth: Number of layers in the model. mask: Existing model mask for layers in this model, if not given, all module masks are initiali...
def wage_feature_eng(wage): """ Feature engineering by making the quantitative type data in WAGE column into categorical data """ if wage <= 50000: return "VERY LOW" elif wage in range(50000,75000): return "LOW" elif wage in range(75000,100000): return "AVER...
def event_type(play_description): """ Returns the event type (ex: a SHOT or a GOAL...etc) given the event description :param play_description: description of play :return: event """ events = {'GOAL SCORED': 'GOAL', 'SHOT ON GOAL': 'SHOT', 'SHOT MISSED': 'MISS', 'SHOT BLOCKED': 'BLOCK'...
def convert_neg_indices(indices, ndim): """converts negative values in tuple/list indices""" def canonicalizer(ax): return ax + ndim if ax < 0 else ax indices = tuple([canonicalizer(axis) for axis in indices]) return indices
def min_n_discretes_acyclic_graph(n_global_discretes): """The minimal system size RootSolution/Unfold can handle with acyclic_graphs. Args: n_global_discretes: Number of global discretes Returns: The minimum number of discretes needed. """ term_width = 2 # 2-body building_blocks first_limit = n_gl...
def determine_nohit_score(cons, invert): """ Determine the value in the matrix assigned to nohit given SeqFindr options :param cons: whether the Seqfindr run is using mapping consensus data or not :param invert: whether the Seqfindr run is inverting (missing hits to ...
def similar_mers(desiredcomplementset, revcomplementset): """2013-12-04 14:21 WEV This should return a list of Nmer sequences which match up DesiredCompliment <- should be sequences which are oriented the way That the parts are oriented RevCompliment <- This is the revComplement - We are looking at ...
def key_(arg): """ get an argument's destiation key """ _, kwargs = arg return kwargs['dest']
def normalize_spaces(s): """ Replaces all sequences of whitespace characters with a single space """ if not s: return '' return ' '.join(s.split())
def row_sum_odd_numbers(n): """function takes in number and returns sum of numbers in that row.""" calculate_index = sum([num for num in range(1, n)]) odd_numbers = [] m = 1 while len(odd_numbers) != calculate_index + n: odd_numbers.append(m) m += 2 numbers = [] for i in rang...
def _right_child(node): """ Args: node: index of a binary tree node Returns: index of node's right child """ return 2 * node + 2
def fibonacci(k: int) -> int: """Finds fibonacci number in index k. Parameters ---------- k : Index of fibonacci. Returns ------- int Fibonacci number in position k. >>> fibonacci(0) 0 >>> fibonacci(2) 1 >>> fibonacci(5) 5 >>>...
def dasherize(word): """Replace underscores with dashes in the string. Example:: >>> dasherize("foo_bar") "foo-bar" Args: word (str): input word Returns: input word with underscores replaced by dashes """ return word.replace('_', '-')
def is_id(argument: str): """Check if argument is #. Parameters ---------- argument: str text to parse Returns ---------- str the bare id """ status = True for x in argument: try: _ = int(x) except: status = False ...
def aggregate_str_content(array_of_elements): """ Takes an array of DOM elements with text and merges their text content """ u = "" for h in array_of_elements: u+=h.text return u
def has_extension(file_path: str, *args: str) -> bool: """ Checks to see if the given file path ends with any of the specified file extensions. If a file extension does not begin with a '.' it will be added automatically :param file_path: The path on which the extensions will be tested for ...
def get_text(score): """Returns a textual representation of the likelihood that a domain is parked, based on the score. """ if score == 0: return 'Unlikely' elif score <= 0.3: return 'Possibly' elif score <= 0.6: return 'Fairly likely' elif score <= 0.85: retu...
def merge_rings(rings): """ Merge rings at the endpoints. """ endpoints = {} for ring in rings: if len(ring.refs) < 2: continue left = ring.refs[0] right = ring.refs[-1] orig_ring = None if left in endpoints: orig_ring = endpoints.pop(l...
def IsUnderAlphabet(s, alphabet): """ ################################################################# Judge the string is within the scope of the alphabet or not. :param s: The string. :param alphabet: alphabet. Return True or the error character. ########################################...
def parse_lanes(lane_expr): """ Break up a 'lane expression' into a list of lane numbers A 'lane expression' is a string consisting of: - a single integer (e.g. 1), or - a list of comma-separated integers (e.g. 1,2,3), or - a range (e.g. 1-4), or - a combination of lists and ranges (e.g. 1...
def sweep_div_toggle_style(mode_val): """toggle the layout for sweep""" if mode_val == 'single': return {'display': 'none'} else: return { 'display': 'flex', 'flex-direction': 'column', 'alignItems': 'center' }
def parse_layers_string(layers_string): """Convert a layer size string (e.g., `128_64_32`) to a list of integers.""" if not layers_string: return () num_hidden = layers_string.split('_') num_hidden = [int(num) for num in num_hidden] return num_hidden
def get_dict_values(dicts, keys, return_dict=False): """Get values from `dicts` specified by `keys`. When `return_dict` is True, return values are in dictionary format. Parameters ---------- dicts : dict keys : list return_dict : bool Returns ------- dict or list Exampl...
def cxSet(ind1, ind2): """ Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets. Parameters ---------- ind1: Set Parent 1. ind2: Set Parent 1 Returns ------- :tuple ...
def clean_unsheltered(battlefield: str) -> str: """ Clean letters outside the shelter :param battlefield: :return: """ result = '' temp = battlefield.split('[') for char in temp: if char.count(']') == 0: c = ''.join(k for k in char if not k.isalpha()) result += c elif len(char) == char.count('#'): ...
def _worst_size(str_len): """ Given a string length, what's the worst size that we should grow to """ if str_len == 0: return 0 elif str_len == 1: return 2 elif str_len % 255 in (0, 1): return (str_len / 255) * 2 + str_len + (str_len % 255) else: return ((str_len / 25...
def get_human_number(num): """Get Human Readable Format of the number.""" if num < 1000: return num magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 # add more suffixes if you need them return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
def _check_data(list_data: list) -> list: """ Checking test data format. :param list_data: :return: """ if isinstance(list_data, list) is False: raise TypeError("The data format is not `list`.") if len(list_data) == 0: raise ValueError("The data format cannot be `[]`.") i...
def space_pad(instring, minlength): """ Pad a string with spaces until it's the minimum length. :param instring: String to pad. :type instring: str :param minlength: Pad while len(instring) < minlength. :type minlength: int """ while len(instring) < minlength: instring += " " ...
def check_args(args: list) -> bool: """ The arguments passed to crapgrep.py """ if len(args) < 2 or args[0] == '--help': return False return True
def parse_range_specification(spec): """Parses a range specification used as arguments for some options in ``qplot``. Range specifications contain two numbers separated by a colon (``:``). Either of the numbers may be replaced by an underscore (``_``) or an empty string meaning 'automatic'.""" retur...
def group_consecutives(vals, step=1): """Return list of consecutive lists of numbers from vals (number list).""" len_limit = 32 run = [] result = [run] expect = None for v in vals: if (v == expect) or (expect is None): run.append(v) else: run = [v] ...
def resource_type_from_id(context, resource_id): """Get resource type by ID Returns a string representation of the Amazon resource type, if known. Returns None on failure. :param context: context under which the method is called :param resource_id: resource_id to evaluate """ known_types ...
def snitch_contained_at_end(metadata, three_class=False): """Return 1 if snitch is contained at the end.""" ever_contained = False res = None for _, movements in metadata['movements'].items(): contain_start = None for movement in movements: if movement[0] == '_contain' and mo...
def __isIntType__(obj): """ Returns true if the obj is an integer """ return isinstance(obj, int)
def find_prev_month(year, month): """Find CENTURY's representation of the month previous to year, month.""" if month == 1: prev_month = 12 year = year - 1 else: prev_month = month - 1 prev_date = year + float('%.2f' % (prev_month / 12.)) return prev_date
def splitIndent(text): """ Return tuple (ind, t) where ind is a string of the indentation characters (normally spaces) and t is text without the indentation. """ pl = len(text) textOnly = text.lstrip() return (text[:pl-len(textOnly)], textOnly)
def _seconds_and_microseconds(timestamp): """ Split a floating point timestamp into an integer number of seconds since the epoch, and an integer number of microseconds (having rounded to the nearest microsecond). If `_seconds_and_microseconds(x) = (y, z)` then the following holds (up to the err...
def get_attr(obj, attr, default=None): """Recursive get object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> get_attr(a, 'b.c') 4 >>> get_attr(a, 'b.c.y', None) >>> get_attr(a, 'b.c.y', 1) 1 """ if '.' not in a...
def net_shortwave_radiation_daily(rs, albedo): """ :param rs: daily shortwave radiation [MJ m-2 day-1] :param albedo: reflection coefficient (0 <= albedo <= 1), which is 0.23 for the hypothetical grass reference crop [-] :return: daily net shortwave radiation reaching the earth [MJ m-2 day-1] """ ...
def factors_list(n): """Return a list containing all the numbers that divide `n` evenly, except for the number itself. Make sure the list is in ascending order. >>> factors_list(6) [1, 2, 3] >>> factors_list(8) [1, 2, 4] >>> factors_list(28) [1, 2, 4, 7, 14] """ all_factors = []...
def unordered_list(value): """ Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> tags. The list is assumed to be in the proper format. For example, if ``var`` contains ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois'...
def get_default_span_name(method): """Default implementation for name_callback, returns HTTP {method_name}.""" return "HTTP {}".format(method).strip()
def unscale_data(data, min_val=0, max_val=255): """ Scale data ranging from -1 to 1 back to its original range. Args: data: min_val: max_val: Returns: """ unscaled_data = (data + 1) / 2 * (max_val - min_val) + min_val return unscaled_data
def important_words(words): """Filters a list of words to those are are valuable. Currently only makes sure that words are at least three characters. >>> w = ['hello', 'world', 'the', 'a', 'an'] >>> important_words(w) ['hello', 'world', 'the'] """ return [x for x in words if len(x) ...
def load_spectrum_settings(settings_dict): """Set missing parameters to their defaults.""" settings = settings_dict.copy() if "feature" not in settings: settings["feature"] = "Stft" if "fft_sample_rate" not in settings: settings["fft_sample_rate"] = 44100 if "stft_window_length" not ...
def gen_h_file(file_list): """ generate the c header file for audio tone """ h_file = '' h_file += '#ifndef __AUDIO_TONEURI_H__\r\n#define __AUDIO_TONEURI_H__\r\n\r\n' h_file += 'extern const char* tone_uri[];\r\n\r\n' h_file += 'typedef enum {\r\n' for line in [' TONE_TYPE_' + name....
def all_lowercase(question): """ Lower case all of the string. """ return question.lower()
def squeeze(data: object) -> object: """ Overview: Squeeze data from tuple, list or dict to single object Example: >>> a = (4, ) >>> a = squeeze(a) >>> print(a) >>> 4 """ if isinstance(data, tuple) or isinstance(data, list): if len(data) == 1: ...
def _get_subdir_list(dir_name): """ Get a list of subdirectories. """ subdir_list = [] if dir_name: dirlink = '' dir_items = dir_name.split('/') dir_items.pop() for dirname in dir_items: dirlink = dirlink + dirname + '/' subdir_list.append...
def get_digit_prefix(characters): """ Return the digit prefix from a list of characters. """ value = 0 while characters and characters[0].isdigit(): value = value * 10 + int(characters.pop(0)) return value
def uv60_to_xy(u60, v60): # CIE1960 to CIE1931 """ convert CIE1960 uv to CIE1931 xy coordinates :param u60: u value (CIE1960) :param v60: v value (CIE1960) :return: CIE1931 x, y """ denominator = (((6 * u60) / 2) - (12 * v60) + 6) if denominator == 0.0: x, y = 0.0, 0.0 else: ...
def get_update_author_profile(d_included, base_url): """Parse a dict and returns, if present, the URL corresponding the profile :param d_included: a dict, as returned by res.json().get("included", {}) :type d_raw: dict :param base_url: site URL :type d_raw: str :return: URL with either company...
def obtain_range(list_object): """ Return the range of the list """ min_value = min(list_object) max_value = max(list_object) return max_value - min_value
def create_return_value(status, message, log=None, error=None): """Convenience functiont that creates the start of the return_value dictionary, setting the "status" key to the value of 'status', the "message" key to the value of 'message' and the "log" key to the value of 'log'. If 'erro...
def bytesto(bytes, from_='b', to='m', bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'b': 0, 'k': 1, 'Ki': 1, 'm': 2, 'Mi': 2, 'g': 3, 'Gi': 3, 't': 4, 'Ti': 4, 'p'...
def img(src, options=None): """takes a src, returns an img tag""" option_str = "" if options: option_list = [" "] for option in options: option_list.extend([option, '="', str(options[option]), '" ']) option_str = "".join(option_list) stub = [ '<img {}src="d...
def filter_medal_counts(medal_list, minimum_medal_count): """ This function will filter a <medal_list> of countries and their medal counts (e.g. <medal_counts>) by the number of medals that country won. If the total number of medals won by that country is greater than or equal to <minimum_medal_coun...
def time_over(until, now): """ Checks if we are over the time we want to film until. Splits on every loop but it's not like it's a big performance drain. """ if until is None: return False until_hour, until_minutes = until.split(':') hour = int(until_hour) minutes = int(unti...
def verify(str,ref,match=0,start=0): """ return the index of the first character in string that is not also in reference. if "Match" is given, then return the result index of the first character in string that is in reference """ if start<0: start = 0 if start>=len(str): return -1 for i in range(start,len(str...
def parity(num: int) -> int: """Return the parity of a non-negative integer. For example, here are the parities of the first ten integers: >>> [parity(n) for n in range(10)] [0, 1, 1, 0, 1, 0, 0, 1, 1, 0] This function is undefined for negative integers: >>> parity(-1) Traceback (most re...
def func_fact(x): """ >>> func_fact(0) 0 >>> func_fact(1) 1 >>> func_fact(4) 24 >>> func_fact(10) 3628800 >>> func_fact(20) 2432902008176640000L """ if x == 0: return 0 elif x == 1: return 1 else: return x *...
def cmp(v1, v2): """ A helper function to compare the two values Parameters:\n v1: first value v2: second value """ if v1 < v2: return -1 elif v1 == v2: return 0 else: return 1
def unique_classes_from_lines(lines): """Return sorted list of unique classes that occur in all lines.""" # Build sorted list of unique classes. unique_classes = sorted( list({x.split(':')[0] for line in lines for x in line})) # pylint: disable=g-complex-comprehension return unique_classes
def _is_dtype(obj): """ True if object is `numpy.dtype`. """ return isinstance(obj, type) and ( obj.__module__ == 'numpy' or obj == complex)
def cmakeScopedDefine(projectName, name, value): """ Formats a CMake -D<projectName>_<name>=<value> argument. """ return '-D%s_%s=%s' % (projectName, name, value)
def get_http_path(http_request): """Given a HTTP request, return the resource path.""" return http_request.split('\n')[0].split(' ')[1]
def serialize_softlearning_class_and_config(cls_name, cls_config): """Returns the serialization of the class with the given config.""" return {'class_name': cls_name, 'config': cls_config}
def guess_content_type_from_body(body): """Guess the content-type based of the body. * "text/html" for str bodies starting with ``<!DOCTYPE html>`` or ``<html>``. * "text/plain" for other str bodies. * "application/json" for dict bodies. * "application/octet-stream" otherwise. """ if isinst...
def add_missing_levels(ff, summ=True): """ Sum-up the internal abundances from leaf to root """ if sum([f.count(".") for f in ff]) < 1: return ff clades2leaves = {} for f in ff: fs = f.split(".") if len(fs) < 2: continue for l in range(1, len(fs)+1)...
def scale_bytes(value, units): """Convert a value in bytes to a different unit. Parameters ---------- value : int Value (in bytes) to be converted. units : string Requested units for output. Options: 'bytes', 'kB', 'MB', 'GB', 'TB' Returns ------- float ...
def _format_range_unified(start, stop): """Convert range to the "ed" format""" beginning = start + 1 length = stop - start if length == 1: return '{}'.format(beginning) if not length: beginning -= 1 return '{},{}'.format(beginning, length)
def delete_nodes_from_list(connecting_points, point_remove): """ Deletes the nodes from the connecting_points list to avoid creation of virtual points. """ for i in range(len(point_remove)): try: connecting_points.RemoveAll(point_remove[i]) except Va...
def extract_column(table, index): """ Returns the values of a specific column in a table given the column index """ try: return [j[index] for j in table] except IndexError: raise IndexError("Index outside of table")
def generate_date_id(mx_room: str, name: str) -> str: """ Generate a date-id from room-name and date-name :param mx_room: matrix room id :param name: name of the date :return: a combination of room-id and name """ return f"{mx_room}::{name}"
def _convert_str_to_float(str): """ TypeError will take care the case that str is None ValueError will take care the case that str is empty """ if not str: return None try: return float(str) except (TypeError, ValueError): return None
def dsr_pb(D_eq): """ Pruppacher and Beard drop shape relationship function. Arguments: D_eq: Drop volume-equivalent diameter (mm) Returns: r: The vertical-to-horizontal drop axis ratio. Note: the Scatterer class expects horizontal to vertical, so you should pass 1/dsr_pb ""...
def delay_from_foffsets(df, dfd, dfdd, times): """ Return the delays in phase caused by offsets in frequency (df), and two frequency derivatives (dfd, dfdd) at the given times in seconds. """ f_delays = df * times fd_delays = dfd * times**2 / 2.0 fdd_delays = dfdd * times**3 / 6.0 re...
def parse_tabbed_table(txt): """Parse a tab-separated table into list of dicts. Expect first row to be column names. Very primitive. """ txt = txt.replace("\r\n", "\n") fields = None data = [] for ln in txt.split("\n"): if not ln: continue if not fields...
def int_to_roman(input): """ Convert an integer to Roman numerals. Examples: >>> int_to_roman(0) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>> int_to_roman(-1) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>>...
def to_deg(value, loc): """convert decimal coordinates into degrees, munutes and seconds tuple Keyword arguments: value is float gps-value, loc is direction list ["S", "N"] or ["W", "E"] return: tuple like (25, 13, 48.343 ,'N') """ if value < 0: loc_value = loc[0] elif value > 0: ...
def pentagonal(n): """Returns the n-th pentagonal number""" return n*(3*n-1)/2
def f(t,x,p,q): """ rhs of the ODE""" return p[1] + q[0]*x