content
stringlengths
42
6.51k
def element_flatten(element): """Flatten the element into a single item if it's a single item list.""" # If there's only one result in the list, then return that single result. if isinstance(element, list) and len(element) == 1: return element[0] else: return element
def get_data_dim(dataset): """ :param dataset: Name of dataset :return: Number of dimensions in data """ if dataset == "SMAP": return 25 elif dataset == "MSL": return 55 elif str(dataset).startswith("machine"): return 38 else: raise ValueError(...
def short_instance_profile(instance_profile=None): """ @type instance_profile: dict """ if instance_profile and instance_profile.get('Arn'): return instance_profile.get('Arn')
def format_flag(name): """Formats a flag given the name.""" return '--{}'.format(name.replace('_', '-'))
def linear_search_recursive(array, item, index=0): """Incrementing index until item is found in the array recursively. array: list item: str Best case running time: O(1) if the item is at the beginning of the array. Worst case running time: O(n) if the item is last in the array. ...
def bin_from_float(number: float): """Return binary from float value. >>> bin_from_float(446.15625) 0b110111110.00101 """ integer = int(number) fractional = abs(number) % 1 count = len(str(fractional)[2:]) binary = [] while (count > 0): # print(number, integer, fractional...
def diff_list(first, second): """Computes the difference between two input sets, with the elements in the first set that are not in the second. """ second = set(second) return [item for item in first if item not in second]
def quote_path_component(text): """ Puts quotes around the path compoenents, and escapes any special characters. """ return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'"
def formatted(command): """Detects whether command is acceptable.""" if "official" in command: return False new = command.split() if len(new) == 1: return new[0] in [ "quit", "options", "adjourn", "reload", "redo_confidence", ...
def parse_sub_phase(raw): """Pass.""" parsed = {} parsed["is_done"] = raw["status"] == 1 parsed["name"] = raw["name"] parsed["progress"] = {} for name, status in raw["additional_data"].items(): if status not in parsed["progress"]: parsed["progress"][status] = [] parse...
def fizz_buzz(current): """ Play fizz buzz :param current: Number to check :return: "Fizz" if current divisible by 3 "Buzz" if current divisible by 5 "Fizz Buzz" if current divisible by both 3 and 5 """ if current % 3 == 0: return "fizz" elif current % 5 == 0: ...
def truncate( input_line: str) -> str: """ When a string is over 80 characters long, string is limited to 79 characters for readability in GUI window, An ellipsis (...) is added to denote unseen text """ if len(input_line) >= 80: input_line = input_line[0:79] return input...
def get_id_from_stripe_data(data): """ Extract stripe id from stripe field data """ if isinstance(data, str): # data like "sub_6lsC8pt7IcFpjA" return data elif data: # data like {"id": sub_6lsC8pt7IcFpjA", ...} return data.get("id") else: return None
def detect_language(kernel_string): """attempt to detect language from the kernel_string""" if "__global__" in kernel_string: lang = "CUDA" elif "__kernel" in kernel_string: lang = "OpenCL" else: lang = "C" return lang
def bin(value: int, bits: int = 0) -> str: """Similar to built-in function bin(), except negative values are represented in two's complement, and the leading bit always indicates the sign (0 = positive, 1 = negative). """ length = value.bit_length() if value < 0: sign = 1 val...
def calc_y(f, t): """Calc y from t. :param f: the param of interp :type f: dict :param t: step of interp :type t: int :return: y corrdinate :rtype: float """ return f['a_y'] + f['b_y'] * t + f['c_y'] * t * t + f['d_y'] * t * t * t
def palindrome(word: str) -> bool: """ Check if a string is palindrome :param word: the word to analyze :return: True if the statement is verified, False otherwise """ i=0 while i < int((len(word)+1)/2): if word[i] != word[-(i+1)]: return False i+=1 return True
def get_modified_columns(fields, fields_to_replace): """ This method updates the columns by adding prefix to each column if the column is being replaced and joins it with other columns. :param fields: list of fields of a particular table :param fields_to_replace: dictionary of fields of a table wh...
def calculate_spendings(queryResult): """ calculate_spendings(queryResult): Takes 1 argument for processing - queryResult which is the query result from the display total function in the same file. It parses the query result and turns it into a form suitable for display on the UI by the user. """ ...
def get_result_sum(resultMap): """ Returns the corresponding entries of whether expressions should be summed or concatenated in a list. :param resultMap: :returns: """ return list(map(lambda row: row[3], resultMap))
def get_stochastic_depth_rate(init_rate, i, n): """Get drop connect rate for the ith block. Args: init_rate: `float` initial drop rate. i: `int` order of the current block. n: `int` total number of blocks. Returns: Drop rate of the ith block. """ if init_rate is not None: if init_rate < ...
def verify_name(prior_name, inferred_name): """Verfies that the given/prior name matches with the inferred name. """ if prior_name is None: prior_name = inferred_name else: assert prior_name == inferred_name, f"""given name {prior_name} does not mach with ...
def format_date(value, format='%I:%M %m-%d-%Y'): """For use by Jinja to format dates on the frontend. Default format HH:MM M-D-YYYY""" if value is None: return '' return value.strftime(format)
def decodeIntLength(byte): """ Extract the encoded size from an initial byte. @return: The size, and the byte with the size removed (it is the first byte of the value). """ # An inelegant implementation, but it's fast. if byte >= 128: return 1, byte & 0b1111111 elif byte...
def generate_primes(n: int): """Generate primes less than `n` (except 2) using the Sieve of Sundaram.""" half_m1 = int((n - 2) / 2) sieve = [0] * (half_m1 + 1) for outer in range(1, half_m1 + 1): inner = outer while outer + inner + 2 * outer * inner <= half_m1: sieve[outer + inner + (2 * outer * i...
def __find_number_of_repeats(seq_before, seq, seq_after): """ Finds the number of repeats before or after a mutation. :param seq_before: the genomic sequence before the mutation (str) :param seq: the genomic sequence of the mutation (str) :param seq_after: the sequence after the mutation (str) ...
def need_to_escape(options): """ Need escape string Args: options (dict): translation options Returns: boolean """ if 'escape' in options: return options['escape'] return True
def get_ugly(n: int) -> int: """ Get nth ugly number. Parameters ----------- Returns --------- Notes ------ """ if n <= 0: return 0 uglies = [1] + [0] * (n-1) nxt, u2, u3, u5 = 1, 0, 0, 0 while nxt < n: minn = min(uglies[u2]*2, uglies[u3]*3, ugli...
def find_available_path(from_list: list): """ Function to identify non empty items from nested list Parameters ---------- from_list : list Nested list containing None and not None entries. Returns ------- available_item_list: list 1D list >>> relative_paths = ['spe...
def get_partition_nodes(nodes_in_scheduler): """Get static nodes and dynamic nodes.""" static_nodes = [] dynamic_nodes = [] for node in nodes_in_scheduler: if "-st-" in node: static_nodes.append(node) if "-dy-" in node: dynamic_nodes.append(node) return static...
def lowercase(string): """Convert string into lower case. Args: string: String to convert. Returns: string: Lowercase case string. """ return str(string).lower()
def get_person_uniqname(record, delimiter=','): """Spilt string and return uniqname by index position. Parameters: record (str): string to be split delimiter (str): delimiter used to perform split Returns: str: uniqname """ return record.split(delimiter)[2]
def parse_string (s): """Grab a string, stripping it of quotes; return string, length.""" if s[0] != '"': string, delim, garbage = s.partition (" ") return string.strip (), len (string) + 1 else: try: second_quote = s[1:].index ('"') + 1 except ValueError: ...
def get_collection(collection, key, default=None): """ Retrieves a key from a collection, replacing None and unset values with the default value. If default is None, an empty dictionary will be the default. If key is a list, it is treated as a key traversal. This is useful for configs, where ...
def parse_bool(value): """Parse string that represents a boolean value. Arguments: value (str): The value to parse. Returns: bool: True if the value is "on", "true", or "yes", False otherwise. """ return (value or '').lower() in ('on', 'true', 'yes')
def ensure_tuple(tuple_or_mixed, *, cls=None): """ If it's not a tuple, let's make a tuple of one item. Otherwise, not changed. :param tuple_or_mixed: material to work on. :param cls: type of the resulting tuple, or `tuple` if not provided. :param length: provided by `_with_length_check` decora...
def iter_to_string(it, format_spec, separator=", "): """Represents an iterable (list, tuple, etc.) as a formatted string. Parameters ---------- it : Iterable An iterable with numeric elements. format_spec : str Format specifier according to https://docs.python.org/3/library/...
def _tofloat(obj): """Convert to float if object is a float string.""" if "inf" in obj.lower().strip(): return obj try: return int(obj) except ValueError: try: return float(obj) except ValueError: return obj
def get_2comp(val_int, val_size=16): """Get the 2's complement of Python int val_int :param val_int: int value to apply 2's complement :type val_int: int :param val_size: bit size of int value (word = 16, long = 32) (optional) :type val_size: int :returns: 2's complement res...
def latex_criteria(value): """ Priority justification criteria in A4 latex PDF """ value = value.replace(' ', '\hspace*{0.5cm}').replace('\n', '\\newline') return value
def add_article(str_): """Appends the article 'the' to a string if necessary. """ if str_.istitle() or str_.find('the ') > -1: str_ = str_ else: str_ = 'the ' + str_ return str_
def cast_to_num(val): """Attempt to cast the given value to a float.""" try: return float(val) except ValueError: return val
def get_config_version(config_blob: dict): """ Get the version of a config file """ if "cfgpull" not in config_blob: return 0 elif "version" not in config_blob["cfgpull"]: return 0 return config_blob["cfgpull"]["version"]
def parse_as_numeric(value, return_type=int): """ Try isolating converting to return type, if a ValueError Arises then return zero. """ try: return return_type(value) except ValueError: return 0
def check_provided_metadata_dict(metadata, ktk_cube_dataset_ids): """ Check metadata dict provided by the user. Parameters ---------- metadata: Optional[Dict[str, Dict[str, Any]]] Optional metadata provided by the user. ktk_cube_dataset_ids: Iterable[str] ktk_cube_dataset_ids an...
def _name(ref): """Returns the username or email of a reference.""" return ref.get('username', ref.get('email'))
def normScale( x, y ): """Scale to apply to an xy vector to normalize it, or 0 if it's a 0 vector""" if x == 0 and y == 0: return 0 else: return 1.0 / pow( x*x + y*y, 0.5 )
def sqrt(x): """ Calculate the square root of argement x. """ # check that x is positive if x<0: print("Error: negative value supplied") return -1 else: print ("Here we go..") #Initial guess for the square root. z= x / 2.0 #continously improv the guess. ...
def get_media_from_object(tweet_obj): """Extract media from a tweet object Args: tweet_obj (dict): A dictionary that is the tweet object, extended_entities or extended_tweet Returns: list: list of medias that are extracted from the tweet. """ media_list = [] if "extended_entiti...
def sumof(nn): """ sum values from 1 to nn """ sum = 0 while nn > 0: sum = sum + nn nn -= 1 return sum
def _sanitize_text(text: str) -> str: """ note: in rich-click, single newline (\n) will be removed, double newlines (\n\n) will be preserved as one newline. """ return text.strip().replace('\n', '\n\n')
def GetFrameworkPath(name): """Return path to the library in the framework.""" return '%s.framework/Versions/5/%s' % (name, name)
def _compile_property_reference(prop): """Find the correct reference on the input feature""" if prop == "$type": return 'f.get("geometry").get("type")' elif prop == "$id": return 'f.get("id")' return 'p.get("{}")'.format(prop)
def get_os_url(url: str) -> str: """ idiotic fix for windows (\ --> \\\\) https://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file""" return url.replace('\\', '\\\\')
def get_entities_bio(seq): """Gets entities from sequence. note: BIO Args: seq (list): sequence of labels. Returns: list: list of (chunk_type, chunk_start, chunk_end). Example: seq = ['B-PER', 'I-PER', 'O', 'B-LOC', 'I-PER'] get_entity_bio(seq) #output ...
def _content_length(line): """Extract the content length from an input line.""" if line.startswith(b'Content-Length: '): _, value = line.split(b'Content-Length: ') value = value.strip() try: return int(value) except ValueError: raise ValueError("Invalid Co...
def intersect(lists): """ Return the intersection of all lists in "lists". """ if len(lists) == 0: return lists if len(lists) == 1: return lists[0] finalList = set(lists[0]) for aList in lists[1:]: finalList = finalList & set(aList) return list(finalList)
def get_halo_mass_key(mdef): """ For the input mass definition, return the string used to access halo table column storing the halo mass. For example, the function will return ``halo_mvir`` if passed the string ``vir``, and will return ``halo_m200m`` if passed ``200m``, each of which correspond to ...
def death_rate_ratio(age: int): """ Take into account age when calculating death probability. The 18-29 years old are the comparison group Based on `https://www.cdc.gov/coronavirus/2019-ncov/covid-data/investigations-discovery/hospitalization-death-by-age.html` :param age: age of the agent ...
def symbol_filename(name): """Adapt the name of a symbol to be suitable for use as a filename.""" return name.replace("::", "__")
def KWW_modulus(x,logomega0, b, height): """1-d KWW: KWW(x, logomega0, b, height)""" return height / ((1 - b) + (b / (1 + b)) * (b * (10**logomega0 / x) + (x / 10**logomega0)**b))
def gadgetMultipleFiles(rootName, fileIndex): """ Returns the name of gadget file 'fileIndex' when a snapshot is saved in multiple binary files. It takes 2 arguments: root name of the files and the file number whose name is requested (from 0 to GadgetHeader.num_files-1).""" return rootName + "%i" % fileInde...
def format_as_diagnostics(lines): """Format the lines as diagnostics output by prepending the diagnostic #. This function makes no assumptions about the line endings. """ return ''.join(['# ' + line for line in lines])
def is_callable(var_or_fn): """Returns whether an object is callable or not.""" # Python 2.7 as well as Python 3.x with x > 2 support 'callable'. # In between, callable was removed hence we need to do a more expansive check if hasattr(var_or_fn, '__call__'): return True try: return callable(var_or_fn)...
def upper(text): """ Uppercases given text. """ return text.upper()
def overlap(A, B): """Return the overlap (i.e. Jaccard index) of two sets >>> overlap({1, 2, 3}, set()) 0.0 >>> overlap({1, 2, 3}, {2, 5}) 0.25 >>> overlap(set(), {1, 2, 3}) 0.0 >>> overlap({1, 2, 3}, {1, 2, 3}) 1.0 """ return len(A.intersection(B)) / len(A.union(B))
def most_common(lst): """ """ return max(set(lst), key=lst.count)
def calculate_lux(r, g, b): """Calculate ambient light values""" # This only uses RGB ... how can we integrate clear or calculate lux # based exclusively on clear since this might be more reliable? illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) return illuminance
def is_structure_line(line): """Returns True if line is a structure line""" return line.startswith('#=GC SS_cons ')
def ami_quote_str(chars): """perform Amiga-like shell quoting with surrounding "..." quotes an special chars quoted with asterisk * """ if chars == "": return '""' res = ['"'] for c in chars: if c == "\n": res.append("*N") elif c == "\x1b": # ESCAPE ...
def nrvocale(text): """Scrieti o functie care calculeaza cate vocale sunt intr-un string""" count = 0 for c in text: if c in ['a', 'e', 'i', 'o', 'u']: count = count + 1 return count
def check_answer(guess, a_followers, b_followers): """ Check the user guess to the actual followers of an account to verify if user's guess is correct :param guess: user's guess :param a_followers: number of followers of account a :param b_followers: number of followers of account b :return: if ...
def verify_hr_info(in_dict): """ Verify the json contains the correct keys and data {"patient_id": 1, "heart_rate": 100} """ for key in ("patient_id", "heart_rate"): if key not in in_dict.keys(): return "Key {} not found".format(key) try: integer = int(in_...
def gcd_it(a: int, b: int) -> int: """iterative gcd :param a: :param b: >>> from pupy.maths import gcd_it >>> from pupy.maths import gcd_r >>> gcd_it(1, 4) == gcd_r(1, 4) True >>> gcd_it(2, 6) == gcd_r(2, 6) True >>> gcd_it(3, 14) == gcd_r(3, 14) ...
def decode_subs(s, mapping): """ >>> decode_subs('hi there', []) 'hi there' >>> decode_subs('g0SUB;there', [('hi ', 'g0SUB;')]) 'hi there' >>> decode_subs('g0SUB; theg1SUB;', [('hi', 'g0SUB;'), ('re', 'g1SUB;')]) 'hi there' """ for tup in mapping: s = s.replace(tup[1], tup[...
def Linear(score, score_min, score_max, val_start, val_end): """Computes a value as a linear function of a score within given bounds. This computes the linear growth/decay of a value based on a given score. Roughly speaking: ret = val_start + C * (score - score_min) where C = (val_end - val_start) /...
def string_to_array(string, conversion=None): """ Convert a string separated by spaces to an array, i.e. a b c -> [a,b,c] Parameters ---------- string : str String to convert to an array conversion : function, optional Function to use to convert the string to an array Retur...
def splitlines(text): """Split text into lines.""" return text.splitlines()
def jax_np_interp(x, xt, yt, indx_hi): """JAX-friendly implementation of np.interp. Requires indx_hi to be precomputed, e.g., using np.searchsorted. Parameters ---------- x : ndarray of shape (n, ) Abscissa values in the interpolation xt : ndarray of shape (k, ) Lookup table for...
def get_year_for_first_weekday(weekday=0): """Get the year that starts on 'weekday', eg. Monday=0.""" import calendar if weekday > 6: raise ValueError("weekday must be between 0 and 6") year = 2020 not_found = True while not_found: firstday = calendar.weekday(year, 1, 1) ...
def solution(n): """Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 """ prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: ...
def rectangles_contains_point(R, x, y): """Decides if at least one of the given rectangles contains a given point either strictly or on its left or top border """ for x1, y1, x2, y2 in R: if x1 <= x < x2 and y1 <= y < y2: return True return False
def string_to_values(input_string): """Method that takes a string of '|'-delimited values and converts them to a list of values.""" value_list = [] for token in input_string.split('|'): value_list.append(float(token)) return value_list
def indent(yaml: str): """Add indents to yaml""" lines = yaml.split("\n") def prefix(line): return " " if line.strip() else "" lines = [prefix(line) + line for line in lines] return "\n".join(lines)
def class_as_descriptor(name): """Return the JVM descriptor for the class `name`""" if not name.endswith(';'): return 'L' + name + ';' else: return name
def _construct_ws_obj_ver(wsid, objid, ver, is_public=False): """Test helper to create a ws_object_version vertex.""" return { "_key": f"{wsid}:{objid}:{ver}", "workspace_id": wsid, "object_id": objid, "version": ver, "name": f"obj_name{objid}", "hash": "xyz", ...
def get_url(server: str): """Formats url based on given server Args: server: str, abbreviation of server Return: str: op.gg url with correct server """ if server == 'euw': return 'https://euw.op.gg/summoner/userName=' elif server == 'na': return 'https://na.op.g...
def _decode_ctrl(key): """ Convert control codes ("\x01" - "\x1A") into ascii representation C-x """ assert len(key) == 1 if key == '\n': return 'RET' code = ord(key) if not 0 < code <= 0x1A: # Not control code return key letter = code + ord('a') - 1 return ("...
def _parse_label(line: str) -> list: """Only parse the lables. """ s = line.strip().split() if ':' in s[0]: labels = [] else: labels = s[0].split(',') labels = [int(v) for v in labels] labels = sorted(labels) return labels
def cross_idl(lon1, lon2, *lons): """ Return True if two longitude values define line crossing international date line. >>> cross_idl(-45, 45) False >>> cross_idl(-180, -179) False >>> cross_idl(180, 179) False >>> cross_idl(45, -45) False >>> cross_idl(0, 0) False ...
def f(x): """Assume x is an int > 0""" ans = 0 #Loop that takes constant time for i in range(1000): ans += 1 print('Number of additions so far', ans) #Loop that takes time x for i in range(x): ans += 1 print('Number of additions so far', ans) #Nested loops take time x**2 for i ...
def askQuestion(nodes_list): """ Displays a question and gathers a response :param nodes_list: a list of nodes to inquire about :return: the value (1 for yes, 0 for no) """ out_str_begin = "Suppose that if you regained consciousness, you would have ALL below - " out_str_end = " *Would you ...
def spendscript(*data): """Take binary data as parameters and return a spend script containing that data""" ret = [] for d in data: assert type(d) is bytes, "There can only be data in spend scripts (no opcodes allowed)" l = len(d) if l == 0: # push empty value onto the stack ...
def save_key(key: bytes, keyfile: str, *args): """Saves key to keyfile Arguments: key (bytes): key in bytes format keyfile (str): name of the file to save to Returns: nothing """ with open(keyfile, "w") as kf: kf.write(key.decode()) return "Success"
def lexer_scan(extensions): """Scans extensions for ``lexer_rules`` and ``preprocessors`` attributes. """ lexer_rules = {} preprocessors = [] postprocessors = [] for extension in extensions: if hasattr(extension, "lexer_rules"): lexer_rules.update(extension.lexer_rules) ...
def _shift_header_up( header_names, col_index, row_index=0, shift_val=0, found_first=False ): """Recursively shift headers up so that top level is not empty""" rows = len(header_names) if row_index < rows: current_value = header_names[row_index][col_index] if current_value == "" and not...
def filter_spouts(table, header): """ filter to keep spouts """ spouts_info = [] for row in table: if row[0] == 'spout': spouts_info.append(row) return spouts_info, header
def fix_carets(expr): """Converts carets to exponent symbol in string""" import re as _re caret = _re.compile('[\\^]') return caret.sub('**', expr)
def vfs_construct_path(base_path, *path_components): """Mimics behavior of os.path.join on Posix machines.""" path = base_path for component in path_components: if component.startswith('/'): path = component elif path == '' or path.endswith('/'): path += component ...
def filter_key_blocks(blocks: dict) -> list: """Identify blocks that are keys in extracted key-value pairs.""" return [ k for k, v in blocks.items() if v["BlockType"] == "KEY_VALUE_SET" and "KEY" in v["EntityTypes"] ]