content
stringlengths
42
6.51k
def get_random_time_segment(segment_ms): """ Gets a random time segment of duration segment_ms in a 10,000 ms audio clip. Arguments: segment_ms -- the duration of the audio clip in ms ("ms" stands for "milliseconds") Returns: segment_time -- a tuple of (segment_start, segment_end) in ms ""...
def clamp(number: float, min_val: float, max_val: float) -> float: """Retuned the value of number clamped between min_val and max_val. Args: - number: The number to be clamped. - min_val: The minimum value of the returned number. - max_val: The maximum value of the returned number. ...
def get_duplicates(values: list) -> list: """ Finds duplicates in a list """ duplicates = list( set(filter(lambda value: value if values.count(value) > 1 else None, values)) ) duplicates.sort() return duplicates
def lineno(loc,strg): """Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parse...
def perfect_root_int(n, k): """Determines whether an Integer n is a perfect k power, returns the integer i such that i^k = n or None if it doesn't exist Arguments: - `n`: - `k`: """ high = n low = 0 while high - low > 1: mid = (low + high) // 2 mid_to_k = pow...
def formatField (Field, x, xerr): """ Parameters ---------- Field : The name of the field x : Value of the field xerr : Error in the field Returns ------- Str Field: x +/- xerr """ return str(Field) + " " + str(x) + " +/- " + str(xerr) + "\n"
def returnDay(v_value): """Returns which day it was , given the value calculated past""" weekday = "" if v_value == 1 : weekday = "Sunday" elif v_value == 2 : weekday = "Monday" elif v_value == 3 : weekday = "Tuesday" elif v_value == 4 : weekday = "...
def compose(red, green, blue): """Generate a 24-bit RGB color value from the provided red, green, blue component byte values. """ return (((red & 0xFF) << 16) | ((green & 0xFF) << 8) | (blue & 0xFF)) & 0xFFFFFF
def get_lesser(num_a, num_b): """ Return the lesser of int num_a and int num_b. If the lesser number is less than 0, return 0 :param num_a: (int) :param num_b: (int) :return: Return the smaller of num_a or num_b. """ return max(0, min(num_a, num_b))
def calcbb(verts): """ Calcultate bounding box """ minX = verts[0][0] maxX = minX minY = verts[0][1] maxY = minY minZ = verts[0][2] maxZ = minZ for v in verts: if v[0] < minX: minX = v[0] if v[0] > maxX: maxX = v[0] if...
def to_text(a_list): """Returns list as string """ return " ".join(a_list)
def pretty_kwargs(kwargs): """pretty prints the keyword arguments in a string """ return ", ".join([ f"{key}={repr(value)}" for key, value in kwargs.items() ])
def add_w_to_param_names(parameter_dict): """ add a "W" string to the end of the parameter name to indicate that we should over-write up the chain :param parameter_dict: dict the dictionary before the adjustments :return: dict same dictionary but with the "W" string added to each of the ...
def vol_cuboid(width: float, height: float, length: float) -> float: """ Calculate the Volume of a Cuboid. :return multiple of width, length and height >>> vol_cuboid(1, 1, 1) 1.0 >>> vol_cuboid(1, 2, 3) 6.0 """ return float(width * height * length)
def make_c_string(string): """Render a Python string into C string literal format.""" if string == None: return "\"\"" string = string.replace("\n", "\\n") string = string.replace("\t", "\\t") string = string.replace('"', '\\"') #string = string.replace("'", "\\'") string = '"' + str...
def clone_graph2(node): """ Returns a new graph as seen from the given node using an iterative depth first search (DFS). """ if not node: return None node_copy = node.shallow_copy() dic = {node: node_copy} stack = [node] while stack: node = stack.pop() for neighbo...
def get_voltage(channel: int, realtime: bool = False): """ Returns either the programmed setting or a realtime reading for channel. """ return f"V{('SET','OUT')[realtime]}{channel}?"
def append_sort(L, a, n): """ Add an element in a sorted List and keep the constrain of sorted and no duplicate. Use Insertion sort. :parameters: - L : the sorted List - a : the element we want to place in the list - n : the size of the list :return: - L : the sorted list with...
def days_in_year_365(cycle=1, year=0): """Days of the year (365 days calendar). Parameters ---------- cycle : int, optional (dummy value). year : int, optional (dummy value). Returns ------- out : list of int 365 days of the year. Notes ----- Approp...
def get_24_bit_bg_color(r, g, b): """"Returns the 24 bit color value for the provided RGB values. Note: not all terminals support this""" return '48;2;%d;%d;%d' % (r, g, b)
def _create_project_id(name): """Create project id from input name.""" if isinstance(name, str) \ and len(name) > 0 \ and not name[0].isalnum(): raise ValueError("First character should be alphabet" " letter (a-z) or number (0-9).") if not name \ ...
def add_to_dict_if_not_none(target_dict, target_key, value): """Adds the given value to the give dict as the given key only if the given value is not None. """ if value is None: return False target_dict[target_key] = value return True
def group_recognition_results(data, clump_threshold_ms=1000): """Groups together objects that have been detected in previous frames.""" sorted_data = sorted(data, key=lambda k: (str(k['found']), int(k['start']))) results = [] prev_result = None for result in sorted_data: if not prev_result: ...
def unhex(x): """Ensure hexidecimal strings are converted to decimal form.""" if x == '': return '0' elif x.startswith('0x'): return str(int(x, base=16)) else: return x
def addressblock(address): """Output an address as a HTML formatted text block""" return {"address" : address}
def match_file(patterns, file): """ Matches the file to the patterns. *patterns* (:class:`~collections.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :data:`True` if *file* matched; othe...
def poly_time(N,K,ts): """ Bonus implementation. https://en.wikipedia.org/wiki/Subset_sum_problem#Polynomial_time_approximate_algorithm args: N :: int length of ts K :: int ts :: list of ints returns: True :: if a subset of ts sums to K False...
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 divide(x, y): """ Function to divide two numbers Parameters ---------- x : int/float First number to be divided y : int/float Second number to be divided Returns ------- quotient : int/float Sum of the...
def parse_groups(groups): """Parse groups separated by empty element.""" parsed_groups = [] cur_group = [] for person in groups: if not person: parsed_groups.append(cur_group) cur_group = [] else: cur_group.append(person) parsed_groups.append(cur_g...
def two_prime_phi(p1: int, p2: int) -> int: """Returns the totient of the product of two primes p1 and p2.""" return (p1 - 1) * (p2 - 1)
def vals_sortby_key(dict_to_sort): """ sort dict by keys alphanumerically, then return vals. Keys should be "feat_00, feat_01", or "stage_00, stage_01" etc. """ return [val for (key, val) in sorted(dict_to_sort.items())]
def ack(eq, red): """One step calculation of Ackermann function""" assert red <= 3 start = eq[:eq.rfind('(')-1] calc = eq[eq.rfind('(')+1:eq.find(')')].split(',') end = eq[eq.find(')')+1:len(eq)] m = int(calc[0]) n = int(calc[1]) if m <= red: result = str([n+1, n+2, 2*n + 3, 2**(...
def construct_resource_kwargs(**kwargs) -> dict: """ Extracts user-parsed values and re-mapping them into parameters corresponding to resource allocations Args: kwargs: Any user input captured Returns: Resource configurations (dict) """ cpus = kwargs['cpus'] gpus = kwa...
def _get_dict_subset(dic, keys): """ Return a subset of a dictionary containing only the specified keys. """ return dict((k, dic[k]) for k in keys if k in dic)
def max3(a, b, c): """returns maximum value among a, b, c""" maximum = a if b > maximum: maximum = b if c > maximum: maximum = c return maximum
def yesno(x): """[yesno] all or sufficient part of any of the words true, false, yes, no, 0, 1, OK""" if len(x)==0: raise ValueError('no answer') is_true = False is_false = False for c in x.lower(): if c in 'truy1k': # spots TRUe, Yes 1, oK is_true = True...
def skillClassValidityChecker(data): """ :param data: arry of strings :return: bool """ if isinstance(data, list): for elem in data: if not isinstance(elem, str): return False else: return False return True
def is_float(istring): """Convert a string to a float. Parameters ---------- istring : str String to convert to a float. Returns ------- float Converted float when successful, ``0`` when when failed. """ try: return float(istring.strip()) except Exceptio...
def list_photo_urls(profile): """ Lists display URLs for a profile, [] if None""" if profile: order = profile.photo_list() urls = profile.get_display_urls() photos = [urls[x] for x in order if x is not None] else: photos = [] return photos
def to_hex_str(data_bytes: bytes) -> str: """ Converts bytes into its string hex representation. :param data_bytes: data to represent as hex. :type data_bytes: bytearray or bytes :return: the hex representation of the data :rtype: str """ if isinstance(data_bytes, bytes): data_...
def _truncate_string_right(strg, maxlen): """ Helper function which truncates the right hand side of a string to the given length and adds a continuation characters, "...". """ if len(strg) > maxlen: rhs = maxlen - 4 return "%s ..." % strg[:rhs] else: return strg
def preprocessing_chain(*args): """ Wraps and returns a sequence of functions """ functions = [x for x in args if x is not None] if not functions: return None def wrapped(x): for function in functions: x = function(x) return x return wrapped
def title2filename(title: str, unavailable_str: str = "%:/,\\[]<>{}*?") -> str: """Convert youtube title to filename.""" name = "".join([c for c in title if c not in unavailable_str]) name = name.replace(" ", "_") return name
def get_filename(filepath): """ Extracts the file name from a complete path assuming it's the last item in the path :param string filepath: a full path to a file :returns the name of the file in the path """ last_item = filepath.split('/')[-1] if '.' not in last_item: raise ValueError("...
def process_value(value: str) -> str: """Returns a processed value for an environment variable.""" if len(value) > 0 and value[0] == value[-1] == '"': return value[1:-1] return value
def format_nodes(n, fmt="{:1.1f}"): """Select appropriate form for big values.""" if n < 10**3: #less than 3 digits return "%d"%(n) elif n < 10**6: #less than 6 digits => Knodes return (fmt+"k").format(n/1000) elif n < 10**9: #less than 9 digits => Mnodes return (fmt+"m").format(...
def ends_with_semi_colon(contents: str) -> bool: """ Returns `True` if a given line ends with a semi-colon. """ # FIXME add "is_statement" contents = contents.strip() return contents.endswith(';') and not contents == '};'
def minkowski(rating1, rating2, r): """Computes the Minkowski distance. Both rating1 and rating2 are dictionaries of the form {'The Strokes': 3.0, 'Slightly Stoopid': 2.5}""" distance = 0 commonRatings = False for key in rating1: if key in rating2: distance += pow(abs(rating1[...
def get_uniform_moments(min_val, max_val): """Get mean, var of a uniform distribution.""" mean = (max_val + min_val) / 2 var = (1 / 12) * (max_val - min_val) * (max_val - min_val) return mean, var
def _pf1c(val1, val2): """ Parameters ---------- val1 : float Description of the parameter Value 1 - Line 1. Description of the parameter Value 1 - Line 2. Description of the parameter Value 1 - Line 3. val2 : list(str) Description of the parameter Value 2 - Line 1. ...
def serialize_titular_bien(titulares): """ # $ref: '#/components/schemas/titularBien' """ # TBD if titulares: return [{ "clave": titulares.codigo if titulares.codigo else "DEC", "valor": titulares.tipo_titular if titulares.tipo_titular else "DECLARANT...
def test_equal_f(x0, x1, epsilon = 1.0e-10): """ Test for floating point precision within epsilon. """ return abs(x0 - x1) < epsilon
def rosenbrock(x): """Rosenbrock test fitness function""" n = len(x) if n < 2: raise ValueError('dimension must be greater than one') return -sum(100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2 for i in range(n-1))
def to_list(values, none_to_list=True): """Converts `values` of any type to a `list`.""" if (hasattr(values, '__iter__') and not isinstance(values, str) and not isinstance(values, dict)): return list(values) elif none_to_list and values is None: return [] else: return [values]
def false_report(report): """Converts a boolean report into a string for output Only used when the --boolean option is used. Converts the boolean report into a string that is every key in the boolean report that has a False value, joined by linebreaks (\\n) Arguments: report (list): the ...
def get_query_words(word_array): """ Generate query words from user input word arguments. """ if len(word_array) == 0 or word_array is None: return "" return " ".join(word_array)
def safeEval(data, eval=eval): """A safe replacement for eval.""" return eval(data, {"__builtins__":{}}, {})
def existing_set_insertion_sort(numbers, existing_set): """Will sort any given number iterable into a min first list.""" new = list(existing_set) while len(new) < len(numbers) + len(existing_set): x = 0 for i in numbers: while True: try: if x i...
def is_valid_port(port): """Check whether a port is valid. :param port: port to check. :return: `True` if port is valid else `False`. """ try: return 1 <= int(port) <= 65535 except ValueError: return False
def float_parameter(level, maxval): """Helper function to scale a value between 0 and maxval and return as a float. Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Return...
def matrix(R): """Returns the 3x3 rotation matrix corresponding to R""" return [[R[0],R[3],R[6]], [R[1],R[4],R[7]], [R[2],R[5],R[8]]]
def ideal_gas_law(T, Vm): """ Calculates the pressure in atm of a gas given the temperature in K and the molar volume in L/mol using the ideal gas law Parameters ---------- T: Temperature in Kelvin (a constant - double or int) Vm: Molar Volume (a constant - double or int) Returns ...
def fragment( otherwise, uri ): """Extracts the fragment component.""" first = uri.find('#') if -1 == first: return otherwise return uri[1+first:]
def calc_funnel_ratio(keys_len, queries_len): """Calculate funnel ratio.""" if queries_len > keys_len: # Upsampling assert queries_len % keys_len == 0 funnel_factor = queries_len // keys_len is_upsampling = True else: # Downsampling assert keys_len % queries_len == 0 funnel_factor = keys_le...
def leaveOlder(x, y): """ In reduceByKey, leave idea with older DetectTime (x[1]/y[1]) :param x: first element in reduce process :param y: second element in reduce process """ if x[1] <= y[1]: return x else: return y
def maxVal(toConsider, avail): """Assumes toConsider a list of items, avail a weight Returns a tuple of the total value of a solution to 0/1 knapsack problem and the items of that soultion""" if toConsider == [] or avail == 0: result = (0, ()) # return no value and items if list is empty ...
def create_pair(urls): """Parses a urls pair string into urls pair.""" tokens = urls.split(",") source_URL = tokens[0] neighbor_URL = tokens[1] return (source_URL, neighbor_URL)
def merge_maps(*maps): """ Merge the given a sequence of :class:`~collections.Mapping` instances. :param maps: Sequence of mapping instance to merge together. :return: A :class:`dict` containing all merged maps. """ merged = {} for m in maps: merged.update(m) return merged
def apply_environments_order(capabilities, environments): """traverses the capabilities and orders the environment files by dependency rules defined in capabilities-map, so that parent environments are first and children environments override these parents :param capabilities: dict representing ca...
def is_too_long_row(tokens, seq_len_to_accept): """Check if the number of tokens does not exceed the allowed length.""" if len(tokens) > seq_len_to_accept: return True return False
def connect(index, data, index_binary_length): """ introduction: Integrate index and data, list 0100+111101010. :param index: The index of data. Type: int. :param data: Data from input. Type: One-dimensional list(int). :param index_binary_length: Length of bin...
def combine_dicts(*args): """ Combines multiple Python dictionaries into a single dictionary Used primarily to pass arguments contained in multiple dictionaries to the `render()` method for Jinja2 templates Args: *args: The dictionaries to be combined Returns: A single Python dict...
def mixture_check(unlabeled_smiles): """ Aborts the prediction if the SMILES contains mixtures. Parameters ---------- unlabeled_smiles : str SMILES string describing a compound. Returns ------- str : the SMILES if it's not disconnected. Raises an error otherwise. "...
def feof(fileid): """Reproduces the behavior of the mel command of the same name. if writing pymel scripts from scratch, you should use a more pythonic construct for looping through files: >>> f = open('myfile.txt') # doctest: +SKIP ... for line in f: ... print line This command is provide...
def case_transform_dict_values(dictionary, func_name, transform): """Transform the string-type values of a dictionary. :param dictionary: dict to transform :param func_name: name of the transformation function used for error messages :param transform: transformation function :returns: dictionary wh...
def sig_test_format(sig_test): """ Process the signaling result to have a short result """ nb_passed = 0 nb_failures = 0 nb_skipped = 0 for data_test in sig_test: if data_test['result'] == "passed": nb_passed += 1 elif data_test['result'] == "failed": ...
def format_bytes(bytes, precision=2): """ Format an integer number of bytes to a human readable string. If bytes is negative, this method raises ArithmeticError """ import math if bytes < 0: raise ArithmeticError("Only Positive Integers Allowed") if bytes != 0: exponen...
def properPrefix(pref, word): """removes the $unk$ tag on proper nouns and numbers""" word = word.replace("$unk$", "") pref = pref.replace("$unk$", "") if word == "" or pref == "": return False if word.startswith(pref) and not word == pref: return True return False
def getMedian(nums): """ Calculate median of a given set of values. Arguments: nums An iterable of numbers. Returns: median The median of the given values. """ nums = sorted(nums) if len(nums) % 2 == 1: return nums[((len(nums)+...
def is_in_polygon(point, polygon): """ :param point: (lat, lng) :param polygon: [point1, point2, point3, point4](points are ordered) :return: True if point is in the polygon else False """ point_num = len(polygon) if point_num < 3: return False result = False for i in range(...
def formating_size(size): """Return an int formatted to human readable size Taken from here : https://stackoverflow.com/a/1094933 Parameters ---------- size : int Value to be formatted """ for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(size) < 1024.0: ...
def check_for_border(m_index_list, m_borders): """ Checks for the borders of membrane regions, from M indices. Parameters ---------- m_indices : list List of membrane region indices, extracted from the flatfile, (e.g. IIIMMMMMMMMMOOOO for Inside, Membrane and Outside), giving the list o...
def set_files_path(instance, filename): """ This'll be appended to your MEDIA_ROOT as the save directory. """ # one option is also to create date-based sub-dirs: # upload = models.FileField(upload_to='uploads/%Y/%m/%d/') # results in files saved to: MEDIA_ROOT/2021/01/09/ # used in this function, it...
def ctd_sbe37im_condwat(c0): """ Description: OOI Level 1 Conductivity core data product, which is calculated using data from the Sea-Bird Electronics conductivity, temperature and depth (CTD) family of instruments. This data product is derived from SBE 37IM instruments and app...
def get_frame(generator): """Given a generator, returns its current frame.""" if getattr(generator, 'gi_frame', None) is not None: return generator.gi_frame return None
def latex_line_spacing_from_logical_line_spacing(line_spacing: float) -> float: """ Latex for some reason has 1.65 as double line spacing, 1.325 as one and a half line spacing, and 1 as single spacing. Take an input on a normal scale (2 is double spaced, 1 is single space, 1.5 is one and a half spacing,...
def recursive_matches_extract(src, key, separator=None, **kwargs): """ Searches the 'src' recursively for nested elements provided in 'key' with dot notation. In case some levels are iterable (list, tuple) it checks every element in it till finds it. Returns the first found element or None. In case...
def reg_tap_gld_to_cim(tap_pos, step_voltage_increment, ndigits=4): """ :param tap_pos: :param step_voltage_increment: :return: """ return round(tap_pos * step_voltage_increment / 100 + 1, ndigits)
def find_star_info(line, column): """ For a given .STAR file line entry, extract the data at the given column index. If the column does not exist (e.g. for a header line read in), return 'False' """ # break an input line into a list data type for column-by-column indexing line_to_list = line.spl...
def hass_to_myhomeserver_brightness(value: int): """Convert hass brightness (0..100) to MyHomeSERVER format (0..255)""" return int((value / 255.0) * 100)
def split_to_odd(n): """ Return values 2 ^ k, such that 2^k*q = n; or an odd integer to test for primiality Let n be an odd prime. Then n-1 is even, where k is a positive integer. """ k = 0 while (n > 0) and (n % 2 == 0): k += 1 n >>= 1 return (k, n)
def get_last_update_id(updates): """ Return last update_id from the list of updates @updates: list of updates retrieved from the API """ update_ids = [] for update in updates["result"]: update_ids.append(int(update["update_id"])) return max(update_ids)
def _calculate_key(name): """Generate a Redis key with the given name. Args: name: The name of the named actor. Returns: The key to use for storing a named actor in Redis. """ return b"Actor:" + name.encode("ascii")
def valid_pass(password): """ validate password Arguments: - `password`: """ if len(password) < 6: return 1 return 0
def hex_to_rgb(hx): """Converts an hexadecimal string (starting with '#') to a RGB tuple""" return tuple([int(hx[i:i+2], 16) for i in range(1, 6, 2)])
def normalizeEntities(formattedEntities): """ Normalizes the provider's entity types to match the ones used in our evaluation. Arguments: formattedEntities {List} -- List of recognized named entities and their types. Returns: List -- A copy of the input list with modified entity types....
def bitLeftShift(binIn, n): """ Input: - binIn: a binary number stored as a string. The most significant bit is stored as the first character in the string and so forth. - n: the number of bits to be shifted and n >= 0. Output: bin(binIn << n) """ pos = 0 allZero = True fo...
def intersect(nums1, nums2): """ Given two arrays, write a function to compute their intersection. :param nums1: list :param nums2: list :return: list """ nums1, nums2 = sorted(nums1), sorted(nums2) pt1 = pt2 = 0 res = [] while True: try: if nums1[pt1] > num...
def format_number(number): """ >>> format_number(1) 1 >>> format_number(22) 22 >>> format_number(333) 333 >>> format_number(4444) '4,444' >>> format_number(55555) '55,555' >>> format_number(666666) '666,666' >>> format_number(7777777) '7,777,777' """ c...