content
stringlengths
42
6.51k
def _validate_structure(structure): """Validates the structure of the given observables collection. The collection must either be a dict, or a (list or tuple) of dicts. Args: structure: A candidate collection of observables. Returns: A boolean that is `True` if `structure` is either a list or a tuple...
def is_iterable(x): """Is the argument an iterable?""" try: iter(x) except TypeError: return False return True
def get_e_activity(data, meta): """ Returns activity of named component @ In, data, dict, request for data @ In, meta, dict, state information @ Out, data, dict, filled data @ In, meta, dict, state information """ data = {'driver': meta['HERON']['activity']['electricity']} return data, meta
def convert_by_engine_keys_to_regex(lookup_by_engine): """ Convert all the keys in a lookup_by_engine to a regex """ keys = set() for d in lookup_by_engine.values(): for k in d.keys(): if isinstance(k, str): keys.add(k) keys = list(keys) keys.sort(key=lambda item...
def match(word, allowed_letters): """checks if a given word can be built from the allowed letters exclusivly. Each allowed letter may only occur once""" allowed_letters = [letter.lower() for letter in allowed_letters] word = [letter.lower() for letter in word] for letter in word: if letter...
def host_and_page(url): """ Splits a `url` into the hostname and the rest of the url. """ url = url.split('//')[1] parts = url.split('/') host = parts[0] page = "/".join(parts[1:]) return host, '/' + page
def euclidean_gcd(a: int, b: int) -> int: """ Examples: >>> euclidean_gcd(3, 5) 1 >>> euclidean_gcd(6, 3) 3 """ while b: a, b = b, a % b return a
def short_bubble_sort(integer_list): """ This implementation is just the same as the normal bubble sort but it can recognize that the list is sorted if no exchanges are made in one pass """ exchanged = True for passnum in range(len(integer_list), 1, -1): exchanged = False for i i...
def file_path_to_dto(file_path): """Converts a `file_path` return value to a `FilePath` Swift DTO value. Args: file_path: A value returned from `file_path`. Returns: A `FilePath` Swift DTO value, which is either a string or a `struct` containing the following fields: * `...
def inches_to_pixels(inches): """ Converts Inches into Pixels """ pixels = inches / 0.0104166666667 return round(pixels, 0)
def merge(numbers_list): """ Mergesort algorithm :param numbers_list: list of number to order :return: new list with numbers ordered """ if len(numbers_list) <= 1: return numbers_list result = [] # identify the middle item mid = len(numbers_list) // 2 numbers_list_a = m...
def try_parse(value, default=0, type=int): """Try to parse the input value into certian type. Return default on error. """ try: return type(value) except (TypeError, ValueError): return default
def lin_thresh(x: float, objective: str, upper: float, lower: float, buffer: float, **kwargs): """ Transform values using a linear threshold :param x: Input valid :param objective: 'maximize', 'minimize' or 'range' :param upper: Upper bound for transforming values ('range' and 'maximize' only) :...
def get_3d_indices(indices, layout="NCDHW"): """Get 3d indices""" if layout == "NDHWC": n, z, y, x, c = indices cc = None elif layout == "NCDHW": n, c, z, y, x = indices cc = None else: n, c, z, y, x, cc = indices return n, c, z, y, x, cc
def As_Dollars_Pad(Number): """Format Dollars amounts to strings & Pad Right 10 Spaces""" Number_Display = f"${Number:,.2f}" Number_Display = f"{Number_Display:>10}" return Number_Display
def uppercase(string: str): """Safely recast a string to uppercase""" try: return string.upper() except AttributeError: return string
def lorenz(amplitude: float, fwhm: float, x: int, x_0: float): """Model of the frequency response.""" return amplitude * ((fwhm / 2.0) ** 2) / ((x - x_0) ** 2 + (fwhm / 2.0) ** 2)
def judge_checksum(content: bytes) -> bool: """ Judge if the checksum is right or not. :param content: the content of segment :return: A bool """ even_sum = 0x0 odd_sum = 0x0 for i in range(len(content)): b = content[i] if i % 2: odd_sum += b odd...
def to_list(obj): """ Wraps an object in a list if it's not already one """ if isinstance(obj, list): return obj return [obj]
def compact(iterable): """ Removes None items from `iterable`. Examples: ```python from flashback.iterating import compact for user_id in compact([1058, None, 85, 9264, 19475, None]): print(user_id) #=> 1058 #=> 85 #=> 9264 #=> 19475 ...
def iterative(x, y): """ Find the GCD or HCF of two numbers. :return: returns the hcf of two numbers. """ x, y = max(x, y), min(x, y) while y: x, y = y, x%y return x
def value_right(self, other): """ Returns the value of the type instance calling an to use in an operator method, namely when the method's instance is on the left side of the expression. """ return self if isinstance(other, self.__class__) else self.value
def to_java_map(map_var, keys_values): """Generate code to put a list of key-value pairs into a Java Map instance. map_var - The variable name of the Java Map instance. keys_values - A list of 2-tuples containing a key and value pair. """ result = [] for k, v in keys_values: result.append('%s.put(%s, %...
def escape_html(str): """Return an HTML-escaped version of STR.""" return str.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def preprocess_gdelt_gkg_tone(x): """ For GDELT GKG """ res = dict() res['tone'] = float(x[0]) res['positive_score'] = x[1] res['negative_score'] = x[2] res['polarity'] = x[3] res['activity_reference_density'] = x[4] res['group_reference_density'] = x[5] return res
def is_palindrome(s): """ (str) -> bool Return True if s is a palindrome, False otherwise. """ return s == s[::-1]
def get_jobs_by_type(data_dict): """ Examines 'algo' and creates new dict where the key is the value of 'algo' and value is a list of jobs (each one a dict) run with that 'algo' :param data_dict: :return: :rtype: dict """ jobtype_dict = dict() for entry in data_dict: if ...
def _idify(value): """Coerce value to valid path component.""" # Must be strings. Can not contain '@' return str(value).replace('@', '_')
def linlin(x, smi, sma, dmi, dma): """Linear mapping Parameters ---------- x : float input value smi : float input range's minimum sma : float input range's maximum dmi : float input range's minimum dma : Returns ------- _ : float map...
def symbol_type_to_human(type): """Convert a symbol type as printed by nm into a human-readable name.""" return { 'b': 'bss', 'd': 'data', 'r': 'read-only data', 't': 'code', 'u': 'weak symbol', # Unique global. 'w': 'weak symbol', 'v': 'weak symbol' ...
def f(t, T): """ returns -1, 0, or 1 based on relationship between t and T throws IndexError """ if(t > 0 and t < float(T/2)): return 1 elif(t == float(T/2)): return 0 elif(t > float(T/2) and t < T): return -1 raise IndexError("Out of function domain")
def parse_arxiv_url(url): """ examples is http://arxiv.org/abs/1512.08756v2 we want to extract the raw id and the version """ _, idversion = url.rsplit('/', 1) pid, ver = idversion.rsplit('v', 1) return pid, int(ver)
def uint8_to_byte(i): """ Utility function that converts an unsigned integer to its byte representation in little endian order. If `i` is not representable in a single byte it will raise OverflowError. Args: i (int): integer to convert Returns: bytes: the byte representation Raise...
def _memoized_fibonacci_aux(n: int, memo: dict) -> int: """Auxiliary function of memoized_fibonacci.""" if n == 0 or n == 1: return n if n not in memo: memo[n] = _memoized_fibonacci_aux(n - 1, memo) + \ _memoized_fibonacci_aux(n - 2, memo) return memo[n]
def _any_weight_initialized(keras_model): """Check if any weights has been initialized in the Keras model. Args: keras_model: An instance of compiled keras model. Returns: boolean, True if at least one weight has been initialized, else False. Currently keras initialize all weights at get_session(). ...
def is_bool(x): """Tests if something is a boolean""" return isinstance(x, bool)
def which(arg: str): """Return fullpath of arg, or None if file not exist""" import os try: fpath = os.path.split(arg) if not fpath: return None if os.path.isfile(arg): return arg for path in os.environ["PATH"].split(os.pathsep): f = os.pat...
def time2secs(timestr): """Converts time in format hh:mm:ss to number of seconds.""" h, m, s = timestr.split(':') return int(h) * 3600 + int(m) * 60 + int(s)
def unit_vector(v): """Return the unit vector of the points v = (a,b)""" h = ((v[0]**2)+(v[1]**2))**0.5 if h == 0: h = 0.000000000000001 ua = v[0] / h ub = v[1] / h return (ua, ub)
def undamaged_example( session_id, array_id, start, end, ): """ S03 P09, P10, P11, P12 2:11:22 4,090 P11 dropped from min ~15 to ~30 S04 P09, P10, P11, P12 2:29:36 5,563 S05 P13, p14, p15, P16 2:31:44 4,939 U03 missing (crashed) S06 P13, p14, p15, P16 2:30:06 5,097 ...
def _TransformOperationWarnings(metadata): """Returns a count of operations if any are present.""" if 'warnings' in metadata: return len(metadata['warnings']) return ''
def parse_signature(signature): """ Breaks 'func(address)(uint256)' into ['func', '(address)', '(uint256)'] """ parts = [] stack = [] start = 0 for end, letter in enumerate(signature): if letter == '(': stack.append(letter) if not parts: parts....
def square_area(x): """Takes a dimension of a square and calculates its area :param x: a number :return: Area of the square >>> square_area(5) 25""" area = x**2 return area
def del_start(x, start): """ >>> l = [1,2,3,4] >>> del_start(l, 2) [1, 2] >>> l = [1,2,3,4,5,6,7] >>> del_start(l, 20) [1, 2, 3, 4, 5, 6, 7] >>> del_start(l, 8) [1, 2, 3, 4, 5, 6, 7] >>> del_start(l, 4) [1, 2, 3, 4] >>> del_start(l, -2) [1, 2] >>> l [1, 2] ...
def find_largest_digit(n): """ :param n: int, a number input by the user :return: the largest digit in n """ if 0 <= n < 10: return n else: if n < 0: return find_largest_digit(-n) else: if (n % 10) <= ((n % 100 - n % 10)/10): return find_largest_digit((n-n % 10)//10) else: return find_large...
def skip_leading_ws_with_indent(s, i, tab_width): """Skips leading whitespace and returns (i, indent), - i points after the whitespace - indent is the width of the whitespace, assuming tab_width wide tabs.""" count = 0; n = len(s) while i < n: ch = s[i] if ch == ' ': cou...
def manhattan_distance(point_1, point_2): """Return Manhattan distance between two points.""" return sum(abs(a - b) for a, b in zip(point_1, point_2))
def new_in_list(my_list, idx, element): """ Replaces an element in a list at a specific position Without modifying the original list """ l_len = len(my_list) if idx >= l_len or idx < 0: return (my_list) new_list = my_list[:] new_list[idx] = element return (new_list)
def parse_range( range_string ): """ Parse a range object from a string of the form: <start>:<stop>[:<step>] No validation is performed on <start>, <stop>, <step>. Takes 1 argument: range_string - Returns 1 value: range_object - range() object. """ components = list...
def validateAuth(auth): """ validates an authentication dictionary to look for specific keys, returns a boolean result """ return ('user' in auth and 'password' in auth)
def wrap_css_lines(css, line_length): """Wrap the lines of the given CSS to an approximate length.""" lines = [] line_start = 0 for i, char in enumerate(css): # It's safe to break after `}` characters. if char == '}' and (i - line_start >= line_length): lines.append(css[...
def contains_unusual_content(result: dict) -> bool: """ returns True if the response indicates the PDF contains unusual content (Launch, Sound, Movie, ResetForm, ImportData and JavaScript actions) by checking if ISO 19005.1 clause 6.6.1 is among the failure reasons. :param result: The parsed JSON r...
def get_dicts_from_list(list_of_dicts, list_of_key_values, key='id'): """ Returns list of dictionaries with keys: @prm{key} equal to one from list @prm{list_of_key_values} from a list of dictionaries: @prm{list_of_dicts}. """ ret = [] for dictionary in list_of_dicts: if dictionary.get(ke...
def escape_markdown(string: str, codeblock: bool = False) -> str: """Escape the markdown of a given string. Args: string (str): The ``str`` that will have markdown escaped. codeblock (bool): The ``bool`` that tells if the escaped content will be in a code block. Returns: str: The `...
def next_arg(args, flag, case=False): """ :param list args: The list of command line arguments :param str flag: The list of command line arguments :param bool case: Pay attention to case sensitivity """ lookup_args = args if case else [_.lower() for _ in args] flag = flag if case else flag.l...
def filter_numeric(s): """If the given string is numeric, return a numeric value for it""" if s.isnumeric(): return int(s) else: try: fval = float(s) return fval except ValueError: return s
def L_v(t_air): """ Calculate latent heat of vaporization at a given temperature. Stull, pg. 641 Args: t_air (float) : Air temperature [deg C] Returns: lv : Latent heat of vaporization at t_air [J kg^-1] """ lv = (2.501 - 0.00237 * t_air) * 1e6 return lv
def empty_if_none(x): """Returns an empty list if passed None otherwise the argument""" if x: return x else: return []
def class_to_str(cl): """Converts the label of a class to the corresponding name """ return "positive" if cl == 1 else "negative"
def _create_input_remove_video_order(removed, PK): """remove video order""" orders = [] for uri in removed: input = { "TableName": "primary_table", "Key": {"PK": {"S": PK}, "SK": {"S": uri}}, } orders.append({"Delete": input}) print("remove video order se...
def asy_number(value) -> str: """Format an asymptote number""" return "%.5g" % value
def clean_mentions(line): """Escape anything that could resolve to mention.""" return line.replace("@", "@\u200b")
def _sort_and_unpack(states, return_states=None): """Maintain input order (even with parallelization on)""" states = sorted(states, key=lambda s: s[0]) states = {n: [s[1][n] for s in states] for n in states[0][1].keys()} for n, s in states.items(): if len(s) == 1: states[n] = s[0] ...
def fib_iter(n): """[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be positive integer' fib_1 = 0 fib_2 = 1 res = 0 if n <= 1: return n ...
def f1score(precision_value, recall_value, eps=1e-5): """ Calculating F1-score from precision and recall to reduce computation redundancy. Args: precision_value: precision (0-1) recall_value: recall (0-1) Returns: F1 score (0-1) """ numerator = 2 * (precision_value * ...
def fill_change_date_object(timestamp): """ change date object: { timestamp: timestamp } """ return dict(timestamp=timestamp)
def apply_polarity(value, polarity): """ Combine value and polarity. # Arguments value: int >= 0, Absolute value. polarity: int, Value indicating the sign. Value is considered to be negative when `polarity == 0`. Any non-zero polarity indicates positive value. # Return Integer with absolute value of `...
def merge(left, right): """Merges two arrays together from smallest to largest""" result = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1...
def get_resource_id_from_type_name(type_name): """Returns the key from type_name. Args: type_name (str): Type name. Returns: str: Resource id. """ if '/' in type_name: return type_name.split('/')[-1] return type_name
def confusion_matrix(match=lambda document:False, documents=[(None,False)]): """ Returns the reliability of a binary classifier, as a tuple with the amount of true positives (TP), true negatives (TN), false positives (FP), false negatives (FN). The classifier is a function that returns True or Fals...
def list_to_dict(lst): """ Takes a list an turns it into a list :param lst: the list that will be turned into a dict """ if len(lst) % 2 != 1: odd_indexes = [] even_indexes = [] for i in range(len(lst)): if i % 2 == 0: odd_indexes.append(lst[i]) ...
def add_values_to_config(defaults, values, source): """Given a defaults dictionary (structured like configurable_defaults above) and a possibly nested config dict, combine the two and return a new dict, structured like cfg_defaults. Every node will have at least 'type', 'source' and 'value' keys.""" ...
def get_keydefs(doc, soort, keydefs=None): """build dictionary of key combo definitions """ if not keydefs: keydefs = {} context = '' for line in doc: line = line.strip() if not line or line.startswith(';') or line.startswith('#'): continue elif line.sta...
def split_seconds(total_seconds, days=False, integer=None): """[summary] Args: total_seconds (int or float): total number of seconds. days (bool, optional): If true, it will return a 4-length tuple, including the days. Defaults to False. integer (bool or None, optional): If T...
def merge_clusters(articles): """Merges articles of every cluster into one article object.""" clusters = [] cluster_ids = set([article['cluster_id'] for article in articles]) for id in cluster_ids: body = [] for article in articles: if article['cluster_id'] == id: ...
def newEmpty(name,location=None,parentCenter=None,**kw): """ Create a new Null Object @type name: string @param name: name of the empty @type location: list @param location: position of the null object @type parentCenter: list @param parentCenter: position of the parent object ...
def modified(number, percent): """return the amount (or any other number) with added margin given by percent parameter (result has type float) """ if percent: return number * (100 + percent) / 100. else: return float(number)
def phase2(l, sum): """ Since we no longer assume an ordered list, the classic solution would be to calculate the diff on each element and save into memory. Than ask if we already seen a desired diff in the past, in case we did, return True Complexity O(n) """ m = set() for element in ...
def render_text(content): """ a simple renderer for text documents: replace new lines with <br> """ return "<br>".join(content.splitlines())
def _format_quad_str(quad): """Format a 4-element tuple of integers into a string of the form xxxx.xx.x.xxx""" return '{}.{}.{}.{}'.format(*quad)
def prod(it): """Compute the product of sequence of numbers ``it``. """ x = 1 for i in it: x *= i return x
def remove_hyphens(words): """ :param words: A list of words, some of which may contain hyphens :return: The same list, but all hyphenated words are split into parts and added back, in the same order """ hyphenated = [] # will break if I have cross correlation and cross-correlation will alw...
def filter_on_provided_extension(input_list, ext): """Takes in a list of files, returns filtered list of files that have the correct extension """ temp_list = [] for item in input_list: if item.endswith(ext): temp_list.append(item) return temp_list
def joinName(parts): """joinName(parts) Join the parts of an object name, taking dots and indexing into account. """ name = ".".join(parts) return name.replace(".[", "[")
def list_contains_only_os(lst): """Check whether the given list contains only o's""" for elem in lst: if elem != "O": return False return True
def format_test_id(test_id) -> str: """Format numeric to 0-padded string""" return f"{test_id:0>5}"
def string2array(value): """ covert a long string format into a list :param value: a string that can be split by "," :type value: str :return: the array of flaoting numbers from a sring :rtype: [float,float,....] """ value = value.replace("[", "").replace("]", "") value = value.split(...
def get_filenames_add_username(files, username): """ Adds the username to the end of a file name :param files: List of file names :param username: Username to append :return: filename with appended username """ filenames = [] for file in files: filenames.append(file + username...
def get_game_name(json): """Returns game name from json file.""" data = json app_id = '' if data is None: return None for dict_key in data.keys(): app_id = dict_key if data[app_id]['success']: return data[app_id]['data']['name'] return None
def _parse_positive_int_param(request, query_params, param_name): """Parses and asserts a positive (>0) integer query parameter. Args: request: The http request object. query_params: Dictionary of query parameters. param_name: Name of the parameter. Returns: None if parameter not present. -1 if ...
def average(v, state): """ Parameters ---------- v : number The next element of the input stream of the agent. state: (n, cumulative) The state of the agent where n : number The value of the next element in the agent's input stream. cumulative...
def select(population, to_retain): """Go through all of the warroirs and check which ones are best fit to breed and move on.""" #This starts off by sorting the population then gets all of the population dived by 2 using floor divison I think #that just makes sure it doesn't output as a pesky decimal. The...
def split_errors(errors): """Splits errors into (user_errors, synthetic_errors). Arguments: errors: A list of lists of _Message, which is a list of bundles of associated messages. Returns: (user_errors, synthetic_errors), where both user_errors and synthetic_errors are lists of lists...
def eqvalue(x): """ Checks whether all values of the iterable `x` are identical and returns that value if true, and otherwise raises a `ValueError` exception. >>> eqvalue([1, 1, 1]) 1 """ items = iter(x) first = next(items) for item in items: if item != first: r...
def split_items(num, items): """Split off the first num items in the sequence. Args: num: int. Split into a list of num. items: str. A str of "+" and "=". Returns: Two str which are sequences, the first with the first num items and the second with the remaining items. """ return items[:num...
def varSum_to_var(idx_new, series, win_size, mean_current, varSum): """ Returns the running variance based on a given time period. sources: http://subluminal.wordpress.com/2008/07/31/running-standard-deviations/ Keyword arguments: idx_new -- current index or location of the value in the series...
def generate_non_gap_position_lookup(seq): """ Creates a list of positions which correspond to the position of that base in a gapless sequence :param seq: string :return: list """ length = len(seq) num_gaps = 0 lookup = [] for i in range(0, length): base = seq[i] if b...
def camelize(key): """Convert a python_style_variable_name to lowerCamelCase. Examples -------- >>> camelize('variable_name') 'variableName' >>> camelize('variableName') 'variableName' """ return ''.join(x.capitalize() if i > 0 else x for i, x in enumerate(key.spl...
def choices_to_dict(t): """ Converts a ChoiceField two-tuple to a dict (for JSON) Assumes i[0][0] is always unique """ d = {} for i in t: k = str(i[0]) d[k] = i[1] return d
def findY(A,B,x): """ given a line formed by 2 points A and B returns the value of y at x on that line """ if B[0] - A[0] == 0: return 0 m = (B[1]-A[1]) / (B[0]-A[0]) b = A[1] - m*A[0] return m*x + b