content
stringlengths
42
6.51k
def getNumExtension(vid_id): """Given a video return the number extension""" # assume the video id is already fixed to cheat checking and return the fixed set return str(vid_id.split('-')[1])
def pull(AddressField, meat, BBLField=None): """This function takes the meat of the data files and splits them into fields to be searched. It creates a dict Pullback where the keys are the addresses of the E-Designation properties in each Borough. Parameters: AddressField= the ind...
def f(x): """does some math""" return x + x * x
def prepare_table(table): """ Make the table 'symmetric'. The lower left part of the matrix is the reverse probability. """ n = len(table) for i, row in enumerate(table): assert len(row) == n, f"len(row) = {len(row)} != {n} = n" for j, _ in enumerate(row): if i == j:...
def normalized_difference(x, y): """ Normalized difference helper function for computing an index such as NDVI. Example ------- >>> import descarteslabs.workflows as wf >>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR", ... start_datetime="2017-01-01", ... end_d...
def mergeDicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def is_int_greater_or_equal_to(min_val, value): """ Is th given value an int greater than or equal to the given minimum value? :param min_val: The minimum value :type min_val: int :param value: The value being checked :type value: Any :return: True if the value is an int greater than or equal to...
def get_day(period): """Returns the day of the week """ day = ((period - 1) // 24) + 1 return day
def rule(index): """Convert decimal index to binary rule list.""" return [int(x) for x in list(format(index, '08b'))]
def space_tokenize_with_bow(sentence): """Add <w> markers to ensure word-boundary alignment.""" return ["<w>" + t for t in sentence.split()]
def excluded(url, exclude_urls=None, exclude_patterns=None): """ Check if link is in the excluded URLs or patterns to ignore. Args: - url (str) : link to check. - exclude_urls (list) : list of excluded urls. - exclude_patterns (list) : list of excluded patterns. ...
def getSequenceEditDistance(SC, path): """ Calculate sequence edit distance of a solution to the constraint """ # IUPAC = { "A": "A", "C": "C", "G": "G", "U": "U", "R": "AG", "Y": "CU", "S": "GC", "W": "AU", "K": "GU", "M":...
def all(learn_from, batch_size): """ Return all points. Parameters ---------- learn_from : list List of data points batch_size : int Number of points to select Returns ------- list All indeces. """ total_size = len(learn_from) all = list(range(...
def is_symbol_in_ranges(sym, ranges): """ Given a list of start/end addresses, test if the symbol lies within any of these address ranges. """ for bound in ranges: if bound["start"] <= sym["st_value"] <= bound["end"]: return True return False
def _parse_port_param(param): """ Parses and assign given port range values i.e. remote_nc_port = 9999 remote_nc_port = 9999,1000 """ global xb_opt_remote_nc_port_min global xb_opt_remote_nc_port_max if not param: return False if param.isdigit(): xb_opt_remote_nc_port_m...
def lookup_module(filename): """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. """ # stolen from pdb import os import sys if os.path.isabs(filename) and os.path.exists(filena...
def extract_loc(row, field_name="lon") : """ extract field value from a cell's dict """ # print(row) # print (type(row)) return row[field_name]
def get_box_size(box): """Get box size""" x0, y0, x1, y1 = box sx = abs(x1 - x0) + 1 sy = abs(y1 - y0) + 1 return (sx, sy)
def nonzeros(u): """Return number of non-zero items in list `u`.""" return len([val for val in u if val != 0])
def get_pay_key(response): """ Utility method to retrieve the payKey from a PayPal response """ return response.get("payKey")
def text_from_affiliation_elements(department, institution, city, country): """ Given an author affiliation from """ text = "" for element in (department, institution, city, country): if text != "": text += ", " if element: text += element return text
def _parseUNIX(factory, address, mode='666', backlog=50, lockfile=True): """ Internal parser function for L{_parseServer} to convert the string arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or C{None}. (...
def unpack_di_block(di_block): """ This function unpacks a nested list of [dec,inc,mag_moment] into a list of declination values, a list of inclination values and a list of magnetic moment values. Mag_moment values are optional, while dec and inc values are required. Parameters ----------- ...
def find_input_index(index, input_ranges): """Find the input index given the index of training data.""" return next(i for i, input in enumerate(input_ranges) if input['start'] <= index < input['end'])
def name(num): """chapter number -> filename""" if num < 10: return "ch0" + str(num) + ".xml" elif num < 15: return "ch" + str(num) + ".xml" else: return "app" + chr(num + 82) + ".xml"
def is_point_in_path(latlong, poly): """ latlong -- a dict of the x and y coordinates of point poly -- a list of tuples [(x, y), (x, y), ...] """ x = latlong["lng"] y = latlong["lat"] num = len(poly) i = 0 j = num - 1 c = False for i in range(num): if ((poly[i][1] ...
def _separate_dirs_files(models): """ Split an iterable of models into a list of file paths and a list of directory paths. """ dirs = [] files = [] for model in models: if model['type'] == 'directory': dirs.append(model['path']) else: files.append(mode...
def new_barline(kern_line, beat): """Make a new barline dict. """ barline = {'beat': beat} first_token = kern_line.split('\t')[0] if '==@' in first_token: barline = { 'type': 'final', 'number': None } elif '==' in first_token: barline = { 'type': 'double', ...
def validate_rule_group_type(rule_group_type): """ Validate Type for RuleGroup Property: RuleGroup.Type """ VALID_RULE_GROUP_TYPES = ("STATEFUL", "STATELESS") if rule_group_type not in VALID_RULE_GROUP_TYPES: raise ValueError( "RuleGroup Type must be one of %s" % ", ".join(V...
def sr_gamma(beta_x=0, beta_y=0, beta_z=0): """The gamma used in special relativity using 3 velocites, some may be zero.""" return 1 / (1 - beta_x ** 2 - beta_y ** 2 - beta_z ** 2) ** (1 / 2)
def BitMask(num_bits): """ Returns num_bits 1s in binary """ return (1<<num_bits) - 1
def get_rain_str(risk_of_rain: float) -> str: """ Return string in french with risk of rain info :param risk_of_rain: Risk of rain between 0 and 1 :return: string """ if risk_of_rain < 0.33: return f'Risque de pluie : {int(100*risk_of_rain)}%.' if risk_of_rain < 0.66: return ...
def parse_job_pilottiming(pilottiming_str): """ Parsing pilot timing str into dict :param pilottiming_str: dict :return: dict of separate pilot timings """ pilot_timings_names = ['timegetjob', 'timestagein', 'timepayload', 'timestageout', 'timetotal_setup'] try: pilot_timings = [int...
def HUEtoNCOL(H): """ convert Hue to Natural color :param H: hue value (0;360) :return: Natural color (str) """ if H == -1.0: return "R0" H %= 360 if H < 60: return "R" + str(int(H / 0.6)) elif H < 120: return "Y" + str(int((H - 60) / 0.6)) elif H < 180: ...
def is_float(s: str) -> bool: """ Checks if input string can be turned into an float Checks if input string can be turned into an float :param s: input string :type s: str :return: True if input can be turned into an float False otherwise :rtype: bool """ try: out = fl...
def _split_and_keep(_str, separator): """Replace end of sentence with separator""" if not _str: return [] max_p = chr(ord(max(_str)) + 1) return _str.replace(separator, separator + max_p).split(max_p)
def get_exact_match(user_input, groups): """Return an exact match from the groups """ lower_groups = [group.lower() for group in groups] if user_input.lower() in lower_groups: return groups[lower_groups.index(user_input.lower())]
def transform_metadata(point): """Bring metadata from the point and put it to the dict.""" metadata = dict() for key, value in point.items(): if (value or value == 0) and key.startswith("metadata."): metadata[key[len("metadata."):]] = value return metadata
def parse_alias(alias, quote_char): """ Extract the alias if available. :param alias: antlr context :parma quote_char: which string quote character to use """ if alias: alias = alias.ID().getText().strip(quote_char) else: alias = None return alias
def quick_sort(array, ascending=True): """Sort array using quick sort algorithm. Parameters ---------- array : list List to be sorted; Can contain any Python objects that can be compared ascending : bool, optional If True sort array from smallest to largest; False -> sort array from...
def mangle_name(name, prefix='', postfix=''): """ "Mangles" *name* by putting a *prefix* and *postfix* around it. :param name: name to mangle :param prefix: *optional* - defaults to '' - prefix to put at the beginning of the name to mangle it :param postfix: *optional* - defaults to '' - postfix...
def merge_dicts(dict_1: dict, dict_2: dict): """Merges two dictionaries.""" if not isinstance(dict_1, dict): raise TypeError("First parameter must be of type 'dict'.") if not isinstance(dict_2, dict): raise TypeError("Second parameter must be of type 'dict'.") for key, value in dict_2....
def is_tagged_version(_hash): """returns true if a build/test has is a tagged version""" return False if "-g" in _hash else True
def eulerCromer(f: float, y1stDerivPrevious: float, yPrevious: float, h: float) -> tuple: """Implementation is kept general - it consumes only the values calculated outside of it""" y2ndDeriv = f # y''(x..) = f(*args); a = f/m - this is the 2nd derivative!!! (acceleration) y1stDeriv = y1stDerivPrevious + ...
def float_array_to_str(arr): """ Turn a float array into CUDA code string @arr: array of float numbers (e.g. [1.0, 2.0]) return: a string (e.g. "{1.0,2.0}") """ s = "{" for f in arr: s += str(f) + "," s = s[:-1] + "}" return s
def check_variable_exclusion(variable_name, ex_variables): """Checks whether the variable has to be excluded. Excluded variables are reported by the user in the .cfg file Arguments: variable_name {string} -- the variable name ex_variables {list} -- the list of excluded variables ...
def equal(a, b, eps=0.001): """ Check if a and b are approximately equal with a margin of eps """ return a == b or (abs(a - b) <= max(abs(a), abs(b)) * eps)
def divide_by(number: float, divisor: float) -> float: """Divide any number by zero.""" # Will throw a ZeroDivisionError if divisor is 0 result = number / divisor return result
def compression_level(n, q, oversampling=10, min_subspace_size=20): """ Compression level to use in svd_compressed Given the size ``n`` of a space, compress that that to one of size ``q`` plus oversampling. The oversampling allows for greater flexibility in finding an appropriate subspace, a low v...
def time(match, player_num, word_index): """A utility function for the time it took player_num to type the word at word_index""" assert word_index < len(match["words"]), "word_index out of range of words" assert player_num < len(match["times"]), "player_num out of range of players" return match["times"]...
def gen_rect(t, b, l, r): """ :param t: top latitude :param b: bottom latitude :param l: left longitude :param r: right longitude :return: GeoJSON rect with specified borders """ ret = { 'type': 'Feature', 'properties': {}, 'geometry': { 'type': 'Polyg...
def confusion_matrix(label, prediction): """ Creates a confusion matrix for a binary classification. :param label: list of int, binary class labels :param prediction: list of int, predicted class frequency for binary labels :return: 2D list respectively confusion matrix """ matrix = [[0, 0]...
def fields_for_mapping(mapping): """Summarize the list of fields in a table mapping""" fields = [] for sf_field, db_field in mapping.get("fields", {}).items(): fields.append({"sf": sf_field, "db": db_field}) for sf_field, lookup in mapping.get("lookups", {}).items(): fields.append({"sf":...
def binary_search(sorted_list, item): """ Implements a Binary Search, O(log n). If item is is list, returns amount of steps. If item not in list, returns None. """ steps = 0 start = 0 end = len(sorted_list) while start < end: steps += 1 mid = (start + end) // 2 ...
def _parse_version(raw): """ Given a colon delimited plugin string, parse a (name, version) tuple. >>> _parse_version("git:2.3.5") ('git', '2.3.5') >>> _parse_version("git") ('git', None) """ tmp = raw.split(':') name = tmp[0] version = None if len(tmp) == 1 else tmp[1] retu...
def get_resize_dimensions(original_size, dimensions): """ Gets the ideal resize dimensions given the original size. :param original_size: Original size. :param dimensions: Default target dimensions. :return: Ideal dimensions. """ dim_x, dim_y = dimensions img_x, img_y = original_size ...
def flatten(list_of_list): """Flatten list of lists.""" flattened_list = [] for lst in list_of_list: flattened_list += lst return flattened_list
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == 'plex' and password == 'status'
def append(data, value): """Append value to list :param data: Data to append to, in list form :param value: Value to append :returns: List """ data.append(value) return data
def _default_axis_units(n_dims): """Returns a tuple of the default axis units.""" return ('-', ) * n_dims
def split_seqid(seqid): """Split NCBI sequence ID to get last value.""" if '|' not in seqid: return seqid return seqid.split('|')[-2]
def GetPrincipleQuantumNumber(atNum): """ ################################################################# *Internal Use Only* Get the principle quantum number of atom with atomic number equal to atNum ################################################################# """ if atNum<=2: ...
def parse_prior_params(bt_config, code_config, key, default, prior='pre'): """ Parse parameters with priority. Args: bt_config(dict): bt config code_config(dict): code config key(string): parameter name default(default): default value prior(string): use bt_config in ...
def intListToString(list): """ This method is used for making MySQL queries with a list of int elements. """ str_list = [] for item in list: str_list.append("%s" % item) str = ','.join(str_list) return str
def isPalindrome(x): """ :type x: int :rtype: bool """ x=str(x) return x == x[::-1]
def unpack_worlds(items): """Handle all the ways we can pass multiple samples for back-compatibility. """ # Unpack nested lists of samples grouped together (old IPython style) if isinstance(items[0], (list, tuple)) and len(items[0]) == 1: out = [] for d in items: assert len(d...
def get_method(ioctl_code): """Returns the correct method type name for a 32 bit IOCTL code""" method_names = [ 'METHOD_BUFFERED', 'METHOD_IN_DIRECT', 'METHOD_OUT_DIRECT', 'METHOD_NEITHER', ] method = ioctl_code & 3 return method_names[method], method
def join_list(value, key): """ Iterate through a list and retrieve the keys from it """ return ", ".join([getattr(x, key, "") for x in value])
def match_edge(u_var, v_var, u_id, v_id, edge_var, u_label, v_label, edge_label='edge'): """Query for matching an edge. Parameters ---------- u_var Name of the variable corresponding to the source of the edge v_var Name of the variable corresponding to the tar...
def fibonacci(n): """ returns the n-th member of a fibonacci sequence (polynomial algorithm) """ if n == 0: return 0 f = [None] * (n + 1) f[0] = 0; f[1] = 1 for i in range(2, n + 1): f[i] = f[i - 1] + f[i - 2] return f[n]
def isCSERelative(uri:str) -> bool: """ Check whether a URI is CSE-Relative. """ return uri is not None and uri[0] != '/'
def extract_name(stringWpath): """This task will extract just the name of specific filename that includes the path in the name: 'stringWpath'. Tested. stringWpath : string input path to be processed Returns ------- stringname : string name of string """ while ...
def JoinFiles(files): """Take a list of file names, read and join their content. Args: files: list; String filenames to open and read. Returns: str; The consolidated content of the provided filenames. """ configlet = '' for f in files: # Let IOErrors happen naturally. configlet = configlet ...
def equation_cub(x, a, b, c, d, e): """Equation form for cub """ return a + b*x + c*x*x + d*x*x*x
def get_stats_location(docker_id): """ Stats for container cpu usage, individual core usage, and memory(Ram) usage and disk memory usage can be extracted from: /cgroup/cpuacct/docker/$CONTAINER_ID/cpuacct.usage, /cgroup/cpuacct/docker/$CONTAINER_ID/cpuacct.usage_percpu /cgroup/memory/docker/$CON...
def fish_gen(lifecycle, ticks): """given one fish at stage 'lifecycle', how many will we have in clock 'ticks' time?""" if ticks <= lifecycle: # this fish doesn't have time to reproduce # so one-fish stays one-fish return 1 else: # calculate the progeny recursively ...
def sorted_completions(completions): """Sort completions case insensitively.""" return list(sorted(completions, key=lambda x: x[0].lower()))
def round_down(num, factor): """Rounds num to next lowest multiple of factor.""" return (num // factor) * factor
def is_iterable(obj): """ Test if the given object is iterable :param obj: an object :return: True if obj is iterable, False otherwise """ try: _ = iter(obj) return True except TypeError: return False
def median(arr): """Determines the median of a list of numbers. Args: arr: a list of ints and/or floats of which to determine the median Returns: int or float: the median value in arr """ if len(arr) == 0: return None arr_sorted = sorted(arr) midpoint = int(len(arr...
def _valid_entries_type(_entries): """This function checks whether or not the ``archive_entries`` argument is a valid type. .. versionadded:: 2.7.0 :param _entries: The ``archive_entries`` value from the parent function :returns: Boolean value indicating whether the value is a ``dict``, ``tuple``, ``l...
def get_plotfiles(directory, prefix = 'plt'): """Get a sorted list of all the plotfiles in a directory.""" import os # Check to make sure the directory exists. if not os.path.isdir(directory): print("Error: Directory " + directory + " does not exist, exiting.") exit() # List all ...
def atoi(text): """ Se for digito retorna em formato integer, caso contrario retorna valor recebido """ return int(text) if text.isdigit() else text
def median(arr, __nosort=False): """ Returns the median of a given array or the middle element of an array """ sample = sorted(arr) if not __nosort else arr if(len(sample) % 2 == 1): return sample[len(sample) // 2] else: return (sample[len(sample)//2 - 1] + sample[len(sample)//2]...
def fix_samp_id(mystring): """Remove all of the extra ID info from TCGA barcodes.""" if mystring.startswith('TCGA'): return mystring[:12] else: return mystring
def mod(x,N): """ modulo function """ if (x <= 0): x += N if (x > N): x -= N return x
def resolve_from_path(path): """Resolve a module or object from a path of the form x.y.z.""" modname, field = path.rsplit(".", 1) mod = __import__(modname, fromlist=[field]) return getattr(mod, field)
def calculate_fs(fs: float, fy: float): """ Determine what to use for fs. :param fs: Steel stress :param fy: Steel yield stress. :return: """ return min(fs, fy)
def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... """ if str(value).lower() in ("yes...
def variance(rows): """ Calculates the class variance of the remaining data param rows -- the dataset in the current branch """ if len(rows) == 0: return 0 data = [float(row[len(row) - 1]) for row in rows] mean = sum(data) / len(data) variance = sum([(d - mean) ** 2 for d in data]) / len(data) ...
def _compile_negation(expression): """Negate the input expression""" return "not ({})".format(expression)
def check_if_valid(row): """ Check that all requirements on row are met Return true if all requirements are met """ if not all(str(x).isdigit() for x in row) or len(row) != 20: return False else: return True
def __world_coordinate_system_from(header): """ From the given NRRD header, determine the respective assumed anatomical world coordinate system. Parameters ---------- header : dict A dictionary containing the NRRD header (as returned by ``nrrd.read``, for example). Returns ------- ...
def mercator_lat(lat): """Helper coerce lat range""" return lat - 180 if lat > 90 else lat
def rh_id_from_instrument_url(url): """get the RH id from the instrument url. needed to look up stock data.""" tokens = url.split("/") return tokens[4]
def calc_distance(position_start: tuple, position_end: tuple) -> float: """Calculates the distance between two positions in format (lat, lon) """ from math import pi, sin, cos, sqrt, atan, radians f = 1 / 298.257223563 a = 6378173 F = radians((position_start[0] + position_end[0]) / 2.0) G = ...
def word_wrap(string, width=80, ind1=0, ind2=0, prefix=''): """ word wrapping function. string: the string to wrap width: the column number to wrap at prefix: prefix each line with this string (goes before any indentation) ind1: number of characters to indent the first line i...
def reverse(x): """This function reverses String""" return x[::-1]
def indices_to_coordinates(i, dx=1, offset=0): """dx = (X.max() - X.min()) / (N - 1) + offset X is an array of x's N is the length X """ return i * dx + offset
def binary_combinations(n): """ Returns all possible combinations of length n binary numbers as strings """ combinations = [] for i in range(2**n): bin_value = str(bin(i)).split('b')[1] while len(bin_value) < n: bin_value = "0" + bin_value combinations.append(bi...