content
stringlengths
42
6.51k
def validate_subclass(obj, _type, name="object", exception=TypeError): """ @type: obj: Any @type: _type: type or Tuple[type] @type: name: str @type: exception: Exception @raises: Exception @rtype: Any """ try: is_subclass = issubclass(obj, _type) except TypeError: ...
def encode(s: str) -> str: """ Turns all astral characters (code points U+10000 and bigger) in string ``s`` into surrogate pairs: a high surrogate (code points U+D800 to U+DBFF) followed by a low surrogate (code points U+DC00 to U+DFFF). """ if not isinstance(s, str): raise TypeError...
def unique_meals(meals): """ Counts number of unique meals in the list of objects """ unique_ingre = [] for meal in meals: ingre = sorted(meal["ingredients"]) if ingre not in unique_ingre: print(meal["name"]) unique_ingre.append(ingre) return len(un...
def vrange_str(vrange): """Return version range string from given range. >>> vrange_str(((2, 4), None)) '2.4-' >>> vrange_str(((2, 4), (2, 6))) '2.4-2.6' >>> vrange_str(((2, 4), (3, 0))) '2.4-3.0' >>> vrange_str((None, (2, 7))) '-2.7' >>> vrange_str(((2, 5), (2, 5))) '2.5' ...
def split_title(title, delim): """Return largest title piece.""" largest_len = 0 largest_piece = None piece_len = 0 for piece in title.split(delim): piece_len = len(piece) if piece_len > largest_len: largest_len = piece_len largest_piece = piece return la...
def normalize(coords, radius): """ Normalize a list of 3 coordinates relative to the origin :param coords: :param radius: :return co: """ co = coords.copy() # calculate current distance dist = (coords[0] ** 2 + coords[1] ** 2 + coords[2] ** 2) ** 0.5 # normalize for axis in ...
def zoom_arguments_scipy2cv(zoom_factor,zoom_interpol_method): """ Resulting images after performing ndimage.zoom or cv2.resize are never identical, but with certain settings you get at least similar results. Parameters ---------- zoom_factor: float, factor by which the size...
def grad_beta_logpdf(p: float, alpha: float, beta: float) -> float: """Gradient of the log-density function of the Beta distribution. Args: p: A point on the unit interval at which to evaluate the density. alpha: Beta distribution 'success' parameter. beta: Beta distribution 'failure' p...
def _partition(source, sub): """Our own string partitioning method. Splits `source` on `sub`. """ i = source.find(sub) if i == -1: return (source, None) return (source[:i], source[i + len(sub):])
def GreenFilter(c): """Returns True if color can be classified as a shade of green""" if (c[1] > c[0]) and (c[1] > c[2]) and (c[0] == c[2]): return True else: return False
def _reorient_starts(starts, blksizes, seqlen, strand): """Reorients block starts into the opposite strand's coordinates (PRIVATE). :param starts: start coordinates :type starts: list [int] :param blksizes: block sizes :type blksizes: list [int] :param seqlen: sequence length :type seqlen: ...
def get_post_id(dict_elem): """ Returns the key property of the attribute dict i.e. the post id :param dict_elem: dict with parsed XML attributes :return: key element, i.e. the post id """ return int(dict_elem['PostId'])
def readable_timedelta(days): # docstring with """ """Takes a value in days and returns weeks with days remaining """ weeks = days // 7 remainder = days % 7 total_time = "{} week(s) and {} day(s)".format(weeks, remainder) return total_time
def is_release(data): """ Returns whether the data is a release (embedded or linked, individual or compiled). """ return 'date' in data
def _add_input_output(input_files=None, output_file=None, pipe=True): """ Add input and output files to command in the form 'command input_files > output_file', 'command > output_file', 'command input_files |', 'command input_files', 'command |' or 'command' depending on the given files and the value of...
def _ConvertFromTestGroupingToConfigGrouping(string_map): """Converts |string| map to be grouped by typ tags/configuration. Args: string_map: The output of _ConvertAggregatedResultsToStringMap. Returns: A map in the format: { 'space separated typ tags': { 'suite': { 'test': [...
def _ShardName(name, number): """Add a shard number to the end of a target. Arguments: name: name of the target (foo#target) number: shard number Returns: Target name with shard added (foo_1#target) """ parts = name.rsplit('#', 1) parts[0] = '%s_%d' % (parts[0], number) return '#'.join(parts)
def display_value(value): """ Dropdown value change """ return 'You have selected "{}"'.format(value)
def get_wo1(conds): """ [ [wc, wo, wv], [wc, wo, wv], ... ] """ wo1 = [] for cond in conds: wo1.append(cond[1]) return wo1
def build_profile(first, last, **user_info): """Build a dictionary containing everything we know about a user.""" profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile
def any(seq): """ Returns True if not all elements in ``seq`` are ``None``, False otherwise. """ for x in seq: if x: return True return False
def path_to_module(path: str): """ Try to figure out the module a path would import into >>> path_to_module("foo/bar.py") "foo.bar" >>> path_to_module("foo/__init__.py") "foo" """ if path[-3:] != '.py': raise ValueError("Not a python module path ", path) path_minus_py = path...
def coarse_pos(tags): """ Coarse POS tags of Peykare corpus: N: Noun, V: Verb, AJ: Adjective, ADV: Adverb, PRO: Pronoun, DET: Determiner, P: Preposition, POSTP: Postposition, NUM: Number, CONJ: Conjunction, PUNC: Punctuation, RES: Residual, CL: Classifier, INT: Interjection >>> coarse_pos(['N','COM','SING']) 'N'...
def from_snake(s: str): """Convert from snake case cols to title""" return s.replace('_', ' ').title()
def compute_min_max(bitmap, width, height): """Minimum and maximum pixel value computation.""" # pro prepocet intenzit pixelu min = float("inf") max = float("-inf") # ziskani statistiky o obrazku - minimalni a maximalni hodnoty for j in range(height): for i in range(width): ...
def filterIntegerBeats(beat_locations_dict): """ Filter for only integer-valued beat number """ for measure_key in beat_locations_dict.keys(): for beat_key in list(beat_locations_dict[measure_key].keys()): if int(beat_key) != beat_key: del beat_locations_dict[m...
def annualize(returns, durations, one_year=365.): """ Annualize returns using their respective durations. Formula used is: (1 + returns) ** (1 / (durations / one_year)) - 1 """ return (1. + returns) ** (1. / (durations / one_year)) - 1.
def splitweight(weight): """Convert a weight / fraction in a string to a float / tuple. >>> [splitweight(a) for a in ('0.5', '0x1.0000000000000p-1', '1/2')] [0.5, 0.5, (1.0, 2.0)]""" if '/' in weight: a, b = weight.split('/') return (float(a), float(b)) elif weight.startswith('0x'): return float.fromhex(wei...
def expected_short_list(env): """Generate the expected output from the 'smt list' command, given the list of captured labels.""" return "\n".join(reversed(env["labels"]))
def ping(value=0): """Return given value + 1, must be an integer.""" return {'value': value + 1}
def is_dictionary_subset(sub, super_dict): """ This function checks if `sub` dictionary is a subset of `super` dictionary. :param sub: subset dictionary, for example user_provided_attr_value. :param super_dict: super dictionary, for example resources_attr_value. :return: True if sub is contained in ...
def midicps(m): """Convert midi number into cycle per second""" return 440.0 * 2 ** ((m - 69) / 12.0)
def nearest_leq_element(arr, target): """Return an item from the array which is the smallest value less than or equal to the target. Args: arr ([type]): [description] """ # Sublist of viable elementsa leq_elements = sorted([x for x in arr if x <= target]) return leq_elements[-1]
def solution(A, target): # O(N) """ Similar to src.arrays.two_sum, find all the combinations that can be added up to reach a given target. Given that all values are unique. >>> solution([1, 2, 3, 4, 5], 5) 2 >>> solution([3, 4, 5, 6], 9) 2 """ ...
def alarm_time(day, is_vacation: bool) -> int: """search for "alarmTime day isVacation" on Homework Help discord for context""" is_weekend = day in (0, 6) if is_vacation: if is_weekend: return 12 else: return 10 # weekday else: if is_weekend: return 10 else: return 7
def FormatFloat(x, percent): """Formats a floating-point number.""" if percent: return '{:.1f}%'.format(x * 100.0) else: return '{:.3f}'.format(x)
def doc(func): """ Find the message shown when someone calls the help command Parameters ---------- func : function the function Returns ------- str The help message for this command """ stripped_chars = " \t" if hasattr(func, '__doc__'): docstr...
def format_mapping(value, props): """Map formatter""" maps = props.get('maps') default = props.get('default') for map in maps: map_from = map.get('from') map_to = map.get('to') if value == map_from: return map_to if default is not None: return default ...
def uncomment(lines, prefix='#'): """Remove prefix and space, or only prefix, when possible""" if not prefix: return lines prefix_and_space = prefix + ' ' length_prefix = len(prefix) length_prefix_and_space = len(prefix_and_space) return [line[length_prefix_and_space:] if line.startswith...
def compare_scores(player_score, pc_score): """Take both the player and the computer's scores and compare them to establish the winner""" if player_score > 21: return "You lose!" elif pc_score > 21: return "You win!" elif player_score == 0 and pc_score == 0: return "You have Blac...
def get_wildcard_path(path): """Replace namespaces with wildcard Change "|foo:bar|foo:nah" into "|*:foo|*nah" """ wildcarded = list() for part in path.split("|"): namespaces, leaf = ([""] + part.rsplit(":", 1))[-2:] w = "*:" * len(namespaces.split(":")) + leaf wildcarded.ap...
def splitmessage(message): """Returns a tuple containing the command and arguments from a message. Returns None if there is no firstword found """ assert isinstance(message, str) words = message.split() if words: return (words[0], words[1:])
def shapefile_driver_args(distribution): """ Construct driver args for a GeoJSON distribution. """ url = distribution.get("downloadURL") or distribution.get("accessURL") if not url: raise KeyError(f"A download URL was not found for {str(distribution)}") args = {"urlpath": url} return...
def check_listen(listen_param): """ check LISTEN """ check_ret = True if ":" in listen_param and listen_param.count(":") == 1: host, port = listen_param.split(":") if int(port) > 65535 or int(port) <= 0: check_ret = False if "." in host and host.count(".") == 3: ...
def checkmatch(dtas, infs): """return True or False: checking if the .DTA and .INF files is matching""" def lacking(dtas,infs): if len(dtas)>len(infs): for i in dtas: if not i in infs: return i else: for i in infs: ...
def compute_trajectory_smoothness(trajectory): """ Returns the total and per step change in the orientation (in degrees) of the agent during the duration of the trajectory input : trajectory (a list of states) output : total change in orientation, avg change in orientation ...
def clean_intents(intents: list) -> list: """ Some intents may trigger actions which means they will be dict instead of strings. This method parses those dicts and returns the list of intents. Args: intents (list): list of intents taken from the domain Example: [{"start_dialogue": {"trigg...
def parse_clademodelc(branch_type_no, line_floats, site_classes): """Parse results specific to the clade model C. """ if not site_classes or len(line_floats) == 0: return for n in range(len(line_floats)): if site_classes[n].get("branch types") is None: site_classes[n]["branch...
def istupleoftuples(x): """Is an object a python list of lists x=[[1,2], [3,4]]""" return type(x) is tuple and type(x[0]) is tuple
def to_list(x:str): """ Convert string to list of strings """ x_list=str(x).split(',') x_list_cleaned=[" ".join(item.split()) for item in x_list] return x_list_cleaned
def _normalize(d): """Normalize Python kwargs to SVG XML attributes""" return {k.replace('_','-'):str(v) for k,v in d.items() if v is not None}
def _register_proxy(proxy_map, key, proxy_cls, *args, **kwargs): """ Implements the singleton mechanism for proxies """ # If it already exists, return it if key in proxy_map: return proxy_map[key] # Create a new one. It gets registered during initialization proxy = proxy_cls(*args, **kwargs) #...
def obj_ext(value): """ Returns extention of an object. e.g. For an object with name 'somecode.py' it returns 'py'. """ return value.split('.')[-1]
def extract(input_data: str) -> list: """take input data and return the appropriate data structure""" return list(map(int, input_data.split(',')))
def ssb_parse_query(variables): """Parses query to send to SSB api Args: variables (cell): {variable_code: list of vars} to get from the table Returns: str: query to send to SSB api Note: One should edit the results from <ssb_get_var_info> function that populates what variable code...
def _coeff_list(upoly, size): """ Return a list of given size consisting of coefficients of upoly and possibly zeros padded. """ return [upoly[i] for i in range(size)]
def _calculate_fdr(tp, fp): """Calculate fdr.""" return fp, (fp + tp)
def flatten_list(not_flat_list): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return [item for sublist in not_flat_list for item in sublist]
def circular_distance_law(distance, chr_segment_length, chr_bin): """Recalculate the distance to return the distance in a circular chromosome and not the distance between the two genomic positions. Parameters ---------- chr_segment_bins : list of floats The start and end indices of chromoso...
def agg_concat(group): """Concatenate the group into a string of unique values.""" group = [g for g in group if g] return '|'.join(set(group))
def get_username_from_payload_handler(payload): """ Override this function if username is formatted differently in payload """ return payload.get('email')
def spsp(n, a): """Rabin-Miller test. n should be odd number and 1 < b < n-1. """ if n % 2 == 0: return False # find s,d: n-1=2^s*d, d: odd number n1 = n - 1 d = n1 r = 1 s = 0 while r != 0: r = d % 2 d = d // 2 s += 1 # start with p = a...
def find_diff_start(old_src, new_src): """Find line number and column number where text first differs.""" old_lines = old_src.split("\n") new_lines = new_src.split("\n") for line in range(min(len(old_lines), len(new_lines))): old = old_lines[line] new = new_lines[line] if old ==...
def list_or_str(v): """ Convert a single value into a list. """ if isinstance(v, (list, tuple)): return v return [v]
def cut_one(src_pos, c, stack_size): """ :param src_pos: a position in the source stack :param c: cut point (can be negative) :param stack_size: total :return: a position in the destination stack """ """ # fix negative if c < 0: c = stack_size + c # let "s" represent the...
def buildaff(ulx: float, uly: float, pixelres: float) -> tuple: """ Build a gdal GeoTransform tuple Args: ulx: projected geo-spatial upper-left x reference coord uly: projected geo-spatial upper-left y reference coord pixelres: pixel resolution Returns: affine tuple ...
def feedback_percentage_liked(controller_dict): """ Controller dictionary should be in the following format: {feedback: {client_id : time / None}} in which time shows how much time (in seconds) after the latest transition the client left the channel. If the client_id is still ...
def my_sum(list_of_nums: list) -> float: """Returns the sum of numbers from list_of_nums. Stop if non-number is trying to be processed. >>> my_sum([2.0, -5, 'q', 3.14]) -3.0 """ result = 0.0 try: for num in list_of_nums: result += float(num) finally: return r...
def is_number(note): """ test is note is a number """ try: float(note) return True except ValueError: return False
def reverse_key_value(orig_dict): """ DESCRIPTION ----------- Reverse the key value pairs of a dictionary object. PARAMETERS ---------- orig_dict : dict A dictionary object. RETURNS ------- rev_dict : dict A dictionary with the values of the original dictionar...
def postfunct(INDIR, FUNCTION, OUTDIR, ARGS, intranet): """ Description ----------- Function executed after processing all files. Current working directory is "dat". example "collects all data from all files and summarizes it in one file" """ #if intranet = [], postfunct does not write ...
def inverse_z_score(X, std, mu=None): """ Reverses z_score normalization using previously computed mu and sigma. Parameters: X' (np.array)[*, k]: The normalized data. sigma (np.array)[k, k]: The previously computed standard deviations. Keywords: mu (np.array)[k]: Optional, prev...
def load_dct(dct, key): """Used to load and determine if dict has a key :param dct: the dictionary to be interrogated :param key: the key to be tried """ try: res = dct[key] is_success = True except KeyError: res = None is_success = False return res, is_suc...
def _is_true(x): """ _is_true : thing -> boolean _is_true : number -> boolean Determines whether the argument is true. Returns None when attempting to assert a non-boolean Examples: >>> _is_true(True) False >>> _is_true("hi") None >>> _is_true(False) False """ ...
def transcription(seq): """DNA -> RNA Transcription. Replacing Thymine with Uracil""" return seq.replace("T", "U")
def power_level(x, y, serial=8): """ A nonsense sequence of steps described in the puzzle instructions. """ rackID = x + 10 level = rackID * y level += serial level *= rackID level = (level // 100) % 10 level -= 5 return level
def get_remote_methods(klass): """Get all the remote methods declared on a class. @param klass: A class to search for AMP-exposed methods. """ remote_methods = {} for attribute_name in dir(klass): potential_method = getattr(klass, attribute_name) name = getattr(potential_method, "am...
def row_to_string(row, is_header=False): """Convert a row to a string, mangling times to be more compact Args: row (tuple): Row of values from a psycopg2 query Yields: string: Stringified version of the row """ row = list(row) for i, val in enumerate(row): if not is_hea...
def find_neighbor(x,y): """if y is within +-10bp of x""" # print (x,y) chr_x = x[:-1].split(":")[0] start_x = int(x[:-1].split(":")[-1].split("-")[0]) chr_y = y[:-1].split(":")[0] start_y = int(y[:-1].split(":")[-1].split("-")[0]) # print (chr_x,chr_y,start_x,start_y) if chr_x != chr_y: return Fals...
def is_return(param_name): """ Determine if a parameter is named as a (internal) return. :param param_name: String with a parameter name :returns: True iff the name has the form of an internal return name """ return param_name.startswith('$return')
def _get_square_matrix(M, x, y, size): """Extract square part with a side of size of matrix M from (x,y) point""" return [[M[i][j] for j in range(x, x+size)] for i in range(y,y+size)]
def merge_intervals(intervals): """ Merge intervals in the form of a list. """ if intervals is None: return None intervals.sort(key=lambda i: i[0]) out = [intervals.pop(0)] for i in intervals: if out[-1][-1] >= i[0]: out[-1][-1] = max(out[-1][-1], i[-1]) else: ...
def is_connection_test(json_data): """Check if event is just a connection test""" return "test" in json_data
def _cleanup_remappings(args, prefix): """ Remove all instances of args that start with prefix. This is used to remove args that were previously added (and are now being regenerated due to respawning) """ existing_args = [a for a in args if a.startswith(prefix)] for a in existing_args: ...
def list_diff(list_a, list_b): """ Expects two lists. Returns an array of the items in a that aren't in b. """ return [item for item in list_a if item not in list_b]
def delete_replace_str(filename, replaces): """ :param filename: :param replaces: :type filename: str :type replaces: list[str] :return: """ for rep in replaces: filename = filename.replace(rep, '') return filename
def procedure_open(name, args): """open procedure body""" args = ', '.join('{0}=None'.format(x) for x in args) if args: args = ', ' + args return "@coroutine\ndef {0}(connection{1}):".format(name, args)
def sum_of_proper_divisors(number: int): """ Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). :param number: :return: """ divisors = [] for n in range(1, number): if number % n == 0: divisors.append(n) retu...
def params(kernels, time, orbiting, center): """Input parameters from WGC API example.""" return { 'kernels': kernels, 'times': time, 'orbiting_body': orbiting, 'center_body': center, }
def binance2btrx(_data): """ Converts Binance data structure into Bittrex model. """ new_data = {'MarketName': str(_data['symbol']), 'Ask': float(_data['askPrice']), 'BaseVolume': float(_data['quoteVolume']), 'Bid': float(_data['bidPrice']), ...
def get_email_cc(current_cc=None, additional_cc=None): """Get current email cc and additional cc and combines them together. Args: current_cc: Current email cc. additional_cc: Additional email cc. Returns: str. Email's cc """ if current_cc: if additional_cc: ...
def asIntOrDefault(v, default=None): """Answers v converted to int. Answer None if the conversion raised an error. >>> asIntOrNone(1234) 1234 >>> asIntOrNone('1234') 1234 >>> asIntOrNone('1234.2') 1234 >>> asIntOrNone('1234a') is None True """ try: return int(rou...
def duration_parse(durstr): """Parse a duration of the form [[hh:]mm:]ss[.sss] and return a float with the duration or None for failure to parse. Enter: durstr: string with the duration. Exit: duration: duration in seconds.""" try: durstr = durstr.strip().split(":") dur = 0 ...
def ampersand_commands(commands): """Join UNIX commands together with an ampersand""" return ' && '.join(commands)
def set_kwargs_from_dflt(passed: dict, dflt: dict) -> dict: """Updates ++passed++ dictionary to add any missing keys and assign corresponding default values, with missing keys and default values as defined by ++dflt++""" for key, val in dflt.items(): passed.setdefault(key, val) return pass...
def ahs_url_helper(build_url, config, args): """Based on the configured year, get the version arg and replace it into the URL.""" version = config["years"][args["year"]] url = build_url url = url.replace("__ver__", version) return [url]
def formula_has_multi_bfunc(formula, bfunc): """Checks for repetitions of a particular basis function (e.g. phi_0_0 representing Cr) in a given cluster function formula :formula: str :bfunc: str :returns: bool """ return formula.count(bfunc)>1
def middle(seq): """Return middle item of a sequence, or the first of two middle items.""" return seq[(len(seq) - 1) // 2]
def filterSongs(data, filters=[]): """Filter the songs according to the passed filters. In the passed filters the first element is artist. The second element is album.""" # In some cases the data can be None, then just return if data is None: return data new_tuple = [] rest = [] ...
def _compose_simulator_name(platform, version): """Composes the name of simulator of platform and version strings.""" return '%s %s test simulator' % (platform, version)