content
stringlengths
42
6.51k
def u32le_list_to_byte_list(data): """! @brief Convert a word array into a byte array""" res = [] for x in data: res.append((x >> 0) & 0xff) res.append((x >> 8) & 0xff) res.append((x >> 16) & 0xff) res.append((x >> 24) & 0xff) return res
def convert_size(size, input_unit="B", output_unit="KB"): """ Converts bytes from one unit to another, rounded up to 2 decimals :param size: The initial amount of bytes :type size: int or float :param str input_unit: The current unit for the given amount. Defaults to "B". :param str output_unit:...
def num_word(my_str): """ count number of word in string sentence INPUT - This is testing program OUTPUT - 4 """ count = 0 for i in range(len(my_str)): # search space at each position if my_str[i] == " ": count = count + 1 return count + 1
def scaleTimeAxis(time=0): """ Calculates time axis scaling factor :returns: A float, X-axis (time) number of data points """ return 2000//(10**(time))
def get_sign_of_float(number: float): """Return sign of float""" if(number > 0): return 1 else: return -1
def serialize_biomass_v2(analysis, type): """Convert the output of the biomass_loss analysis to json""" return { 'id': None, 'type': type, 'attributes': { 'biomassLoss': analysis.get('biomassLoss', None), 'biomassLossByYear': analysis.get('biomassLossByYear', None...
def parseHeaderText(header): """ parseHeaderText(): Go through our parsed headers, and create text descriptions based on them. """ retval = {} if header["qr"] == 0: retval["qr"] = "Question" elif header["qr"] == 1: retval["qr"] = "Response" else: retval["qr"] = "Unknown! (%s)" % header["qr"] if header[...
def fill(bitdef, value): """ Fill undefined bits with a value. For example ``1..0100.1`` becomes ``111010011`` when filled with 1s. Args: bitdef (str): The bitdef to fill. value (str): The value to fill with, "0" or "1". Returns: str: The filled bitdef. """ output ...
def convert_number(number_with_comma): """ function for modifying number strings so they can be cast into float: "4,5" -> "4.5" input: number_with_comma (str), string representing float number with comma output: number_with_period (str), string representing float number with period ...
def _generate_path(directory: str, project_folder: str) -> str: """ Generate the path to where we want to setup repo. :argument directory: str the directory variable from the projects.toml :argument project_folder: str the folder name for the project """ return f"{directory}{project_folder}"
def water_thermal_expansion(tC_water): """ Description Returns the thermal expansion of water. Used in both the warmlayer and coolskin algorithms. Implemented by: 2014-08-29: Russell Desiderio. Initial Code. Usage: Al = water_thermal_expansion(tC_water) ...
def split_into_page_and_sent_id(x, separator="_"): """ converts evidence id to the official fever scorer format :param x: evidence id in format pagename_linenum :return: evidence id in format [pagename, linenum' """ p, sid = x.rsplit(separator, 1) return [p, int(sid.strip("\""))]
def get_inventory_index(inventory_dict, id): """ This method returns the index of the item in inventory dictionary Returns: index of the item if found Raises: KeyError if the id is not found """ count = 0 for item in inventory_dict["items"]: if item['id'] == id: ...
def conv_C2F(value): """Converts degree Celsius to degree Fahrenheit. Input parameter: scalar or array """ value_f = (value*(9/5))+32 if(hasattr(value_f, 'units')): value_f.attrs.update(units='degF') return(value_f)
def max_fund(village): """Find a contiguous subarray with the largest sum.""" # Hint: while iterating, you could save the best_sum collected so far # return total, starting, ending running_total = 0 max_total = 0 max_start = 0 max_end = 0 for i in range(len(village)+1): ...
def float_to_str(number): """ :param number: any number :return: """ if number > 0: integer_str = '+' + str(int(number)) else: integer_str = str(int(number)) return integer_str
def to_bool_type(arg): """ change bool argument to python bool type """ in_s = str(arg).upper() if 'TRUE'.startswith(in_s): return True elif 'FALSE'.startswith(in_s): return False else: raise ValueError("argument must be 'False' or 'True' for bool type")
def file_name(search_entry, typ="summary"): """ By entering the search entry we generate an uniqe file name to save or load the summaries or the books. Input: ----- search_entry : the search entry we look for typ : the type of text we are looking for. Can be "summary" for api summary, or "book" for...
def is_prime(n): """ from https://stackoverflow.com/questions/15285534/isprime-function-for-python-language """ if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: # p...
def get_message_type_from_message(message: str) -> str: """Parses the message_type from the message.""" return message.split(" ")[2].replace("\n", "")
def str_is_parametrized(target_str): """ Determine if there are jinja2 parameters in the string :param target_str: :return: """ return '{' + '{' in target_str or '{' + '%' in target_str
def to_camel_case_var(word: str) -> str: """ Convert a string to camel case """ s = "".join(x.capitalize() or "_" for x in word.split("_")) return s[0].lower() + s[1:]
def normalize_cols(table): """ Pad short rows to the length of the longest row to help render "jagged" CSV files """ longest_row_len = max([len(row) for row in table]) for row in table: while len(row) < longest_row_len: row.append('') return table
def make2D_grid(rows, cols): """Returns a 2d grid filled with zeros""" grid = [] for x in range(0, cols): grid.append([]) for y in range(0, rows): grid[x].append(0) return grid
def countNestedNames(a): """ Count nested names, duplicate names are counted separately :param a: the nested array of names :return: the count """ cnt = len(a) for item in a: if type(item)==list: cnt = cnt-1 # cnt = cnt + countNestedNames(item) cnt += countNestedNames(item) re...
def get_matches(players): """This function takes a list of names and generates a list of matches. Args: players(list): List of player names. Returns: matches(list): List of player matches. Examples: >>> task_01.get_matches(['Harry', 'Howard', 'Hugh']) [('Harry', 'Howar...
def copy_dict(value, impl=dict): """ Perform a deep copy of a dict using the specified impl for each new dict constructed. Preserves the order of items as read from the source dict. :param value: the dict value to copy :param impl: the function to call to create new dicts :return: a deep copy o...
def get_nice_strings(strings, check_function): """Validate strings with check_function.""" return [ string for string in strings if check_function(string) ]
def w2xyz(w, extended_dims, **kwargs): """ For QC. FIXME: it's terribly slow so now only for single-value checks. We could use Adrian's formulas to vectorize it. """ assert float(w).is_integer() assert w > 0 enx, eny, enz = extended_dims if w > enx * eny * enz: raise ValueError('w > e...
def sequence_accuracy_scoring(y_true, y_pred): """Accuracy score which calculates two sequences to be equal only if all of their predicted tags are equal. Args: y_true (list): A sequence of true expected labels y_pred (list): A sequence of predicted labels Returns: float: T...
def get_leading_ws(s): """Returns the leading whitespace of 's'.""" i = 0 ; n = len(s) while i < n and s[i] in (' ','\t'): i += 1 return s[0:i]
def try_int(value): """Coerce an object into an int.""" try: return int(value) except Exception: return value
def fahrenheit2celcius(F): """ Convert Fahrenheit to Celcius :param F: Temperature in Fahrenheit :return: Temperature in Celcius """ return 5.0 / 9.0 * (F - 32)
def _format_83(f): """Format a single float into a string of width 8, with ideally 3 decimal places of precision. If the number is a little too large, we can gracefully degrade the precision by lopping off some of the decimal places. If it's much too large, we throw a ValueError""" if -999.999 < f <...
def simpleArraySum(ar): """:return the sum of all the numbers in the ar array as integer :param ar: list() of items :return: int() with the sum of all numbers """ _sum = 0 for item in ar: try: _sum += item except: pass return int(_sum)
def commas(number): """Insert commas in a number. Return the given number as a string with commas to separate the thousands positions. The number can be a float, int, long or string. Returns None for None. """ if number is None: return None if not number: return str(number)...
def split_name_schema(name_schema): """Input string output a tuple of the object schema and name as parts""" if name_schema is not None: name_schema = name_schema.split(".") if name_schema is None: object_name = None object_schema = None elif len(name_schema) == 1: object...
def tsh_diagnosis(float_list): """Diagnosis from data From the TSH results from each patient, assign one of the following diagnoses to the patient "hyperthyroidism", hypothyroidism", "normal thyroid function". Args: float_list (list): list of floats of the tsh data. ...
def is_json_file(filename): """ Check if file has a *.json type (just check an extension) :param filename: name of file :return: True if file has a *.json type """ return True if filename.lower().endswith('.json') else False
def CreateGrid(size): """Accept a list, create a size by size blank 2-d list""" #row = a list of the current row being added #board = the list that corresponds to the board being constructed board = [] for rows in range(size): row = [] for cols in range(size): row.appen...
def toggle_modal_object_prop(n1, n2, is_open): """ Callback for the modal (open/close) """ if n1 or n2: return not is_open return is_open
def row_col1(row): """Given row number, return value of number in first column.""" if row == 1: return 1 else: return int(row - 1 + row_col1(row-1))
def lowercase_first(text): """Convert 1st character of string to lowercase.""" return text[0].lower() + text[1:]
def get_lettercase_permutation(word): """O(2^n) worst case time and space complexities""" result = [''] for ch in word: if ch.isalpha(): result = [word + c for word in result for c in [ch.lower(), ch.upper()]] else: result = [word + ch for word in result] return r...
def punycode(domain): """Return the Punycode of the given domain if it's non-ASCII.""" return domain.encode("idna").decode("ascii")
def _flip_value(lst): """flips a 0 to 1 and vice-versa""" return [ 0 if val == 1 else 1 for val in lst ]
def _require(key, cfg, error_msg=None): """ Ensures that `key` is in the config `cfg`. """ error_msg = error_msg or f'Missing field `{key}` in the config file.' val = cfg.get(key) if not val: raise ValueError(error_msg) return val
def merge(l1, l2): """Merge two sorted lists.""" d = {'test': 'test'} i = 0 j = 0 lmerged = [] while (i <= len(l1) - 1) or (j <= len(l2) - 1): if i == len(l1): lmerged.extend(l2[j:]) break if j == len(l2): lmerged.extend(l1[i:]) ...
def _poa_ground_shadows(poa_ground, f_gnd_beam, df, vf_gnd_sky): """ Reduce ground-reflected irradiance to the tilted plane (poa_ground) to account for shadows on the ground. Parameters ---------- poa_ground : numeric Ground reflected irradiance on the tilted surface, assuming full GHI ...
def nb_binom(n, k): # pragma: no cover """Numba version of binomial coefficient function. Args: n (int): how many options k (int): how many are chosen Returns: int: how many ways of choosing """ if k < 0 or k > n: return 0 if k in (0, n): return 1 b...
def format_src(src, url): """ Reformat links and urls from the DOM. This reformat urls and links from the DOM by adding (if not present) the main dns of the website showcases by the server. This get rid of relative paths associated with link ref of the DOM. :param src: An u...
def combo(iter_1, iter_2): """ Assume both iterables has same length combo([1, 2, 3], 'abc') Output: [(1, 'a'), (2, 'b'), (3, 'c')] """ combo_list = [] for x in range(len(iter_1)): tupl = iter_1[x], iter_2[x] combo_list.append(tupl) return combo_list
def get_message_json(event, content) -> str: """ This function converts an event and its content to a json format. Parameters ---------- event : EVENT Event to translate content : str Content of event Returns ------- str json format of event and content "...
def anneal_value(base_value, progress, anneal_mode, default_target=0.0): """Anneals a base_value across a period of [0,1] Args: base_value: The initial value at time=0 progress: The current progress of the period in [0,1] (Greater than 1 is treated as 1) anneal_mode: How to ...
def extgcd(x, y): """ Return a tuple (u, v, d); they are the greatest common divisor d of two integers x and y and u, v such that d = x * u + y * v. """ # Crandall & Pomerance "PRIME NUMBERS", Algorithm 2.1.4 a, b, g, u, v, w = 1, 0, x, 0, 1, y while w: q, t = divmod(g, w) a,...
def calculate(user_input): """ This function is to calculate user inputted formula Args: user_input (str): Formula user inputted Returns: str: The result after evaluation """ try: return eval(user_input.replace('^', "**")) except: return 'Please chec...
def lower(value): # Only one argument. """Converts a string into all lowercase""" return value.lower()
def sum_even_fibonacci(n): """sum of the even-valued terms of the fibonacci sequence not exceeding n""" result = 0 if n >= 2: x, y = 1, 1 for _ in range(n): x, y = y, x + y if x > n: break if x % 2 == 0: # print(x,...
def selection_sort(collection): """ Examples: >>> selection_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> selection_sort([]) [] >>> selection_sort([-2, -5, -45]) [-45, -5, -2] """ length = len(collection) for i in range(length - 1): least = i for k in range(i +...
def high_income_amount(responses, derived): """ Return the guidelines table amount for a high income earner """ try: under = float(responses.get('child_support_amount_under_high_income', 0)) except ValueError: under = 0 try: over = float(responses.get('amount_income_over_high_i...
def clean_url(url: str) -> str: """ Removes unwanted characters from the end of certain URLs. Args: url (:obj:`str`): A URL. Returns: :obj:`str`: A URL without unwanted characters at the end. """ if 'achgut' in url and '/P' in url: retu...
def recover_bad_token(stream: str) -> str: """Pull the leading non-whitespace string off the input stream""" return stream.split(' ')[0]
def dict2list(dict_: dict) -> list: """ Converts a dict into a list of key-value dictionaries and returns it. Parameters ---------- dict_ Some dictionary to be converted. Returns ------- list_ Each element is a dict with one key-value pair. These key-value pairs ...
def periodic(t, T): """ Returns equivalent time of the first period if more than one period is simulated. :param t: Time. :param T: Period length. """ while t/T > 1.0: t = t - T return t
def merge_dicts(*dicts): """ Merges dicts in reversed order. :param dicts: dicts to be merged :return: merged dict """ result = {} for d in reversed(dicts): if d: result.update(d) return result
def make_grid(n, m): """nxm array with labeled coordinates ... pretty superfluous""" return [[(i,j) for j in range(m+1)] for i in range(n+1)] #h = [] #for i in range(n+1): h.append([(i, j) for j in range(m+1)]) #return h #return [(i, j) for i in range(n+1) for j in range(m+1)]
def create_single_selector(single_str, default="name"): """ description of the poco single condition selection element is converted into a dictionary for use by poco """ result = {} if "=" in single_str: single_split = single_str.split("=", 1) key = single_split[0].strip() ...
def db_delete_from_projects(project_id: str) -> str: """Remove the specified project from the ProjectsCollection.""" return f'db.ProjectsCollection.deleteOne({{ _id: ObjectId("{project_id}")}})'
def clean_topics(topics, word2id, bad_topics=None): """ Cleans the seed topic words list. - Gets rid of undesired topics - Gets rid of words in topics that are not in corpus vocab Args: topics = list, list of lsits containing topic words (dirty) vocab = list, list of ...
def _call(arg): """Call arg if it is callable otherwise return.""" return arg() if callable(arg) else arg
def roman_main(args): """Convert first arg to roman numeral if <= 5000 else :return: second arg.""" num = int(float(args.get('1'))) # Return a message for numbers too big to be expressed in Roman numerals. if 0 > num or num >= 5000: return args.get('2', 'N/A') def toRoman(n, romanNumeral...
def separate(notes): """ separate a score of notes into a tuple of frequencies, sustains and durations. """ frequencies = [] durations = [] sustains = [] if len(notes)==0: return ([],[]) length = len(max(notes, key = lambda x: len(x))) counter = 0 for i in range(0, length): freq_buffer = [...
def get_autologin_type(code): """Get autologin type from code.""" autologin_type = {0: "Disable", 1: "Enable"} if code in autologin_type: return autologin_type[code] + " (" + str(code) + ")" return "Unknown ({})".format(str(code))
def tmap( *args ): """Make a map and then wrap it in a tuple""" return tuple( map( *args ) )
def flatten(l): """ Flatten a list of lists into a plain list :param l: list to flatten (list) :return: list flattened (list) """ return [item for sublist in l for item in sublist]
def get_in(dct, path, default_val=None): """Gets a nested value in a dict by following the path :param dct: a python dictionary :param path: a list of keys pointing to a node in dct :returns: the value at the specified path :rtype: any """ if dct is None: return default_val asse...
def hashdigit(cpf, position): # type: (str, int) -> int """ Will compute the given `position` checksum digit for the `cpf` input. The input needs to contain all elements previous to `position` else computation will yield the wrong result. """ val = sum(int(digit) * weight for digit, weight in z...
def get_bbox(bbox): """ Compute square image crop window. """ y1, x1, y2, x2 = bbox img_width = 480 img_length = 640 window_size = (max(y2-y1, x2-x1) // 40 + 1) * 40 window_size = min(window_size, 440) center = [(y1 + y2) // 2, (x1 + x2) // 2] rmin = center[0] - int(window_size /...
def crossp(a, b): """Cross product of two 3D vectors""" a1, a2, a3 = a b1, b2, b3 = b return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)
def get_term_count_agg(results): """Convenience function for extracting the date histogram from the a term count aggregation. Returns: list: A list of aggregation buckets containing both the date and the aggregated term count for that bucket. """ return results.get('aggregations...
def check_if_number(value): """Check if value (str) looks like a number and return the converted value.""" res = None try: res = int(value) except ValueError: try: res = float(value) except ValueError: pass if res is not None: return res ...
def get_dict_from_args(args): """Extracts a dict from task argument string.""" d = {} if args: for k,v in [p.strip().split('=') for p in args.split(',')]: d[k] = v return d
def allocate_in_group(lst, fos_subset, tag="CI", fos_subset_tag="AI_CI"): """Find Fields of Study in a list. Args: lst (:obj:`list` of str): Fields of Study of a paper. group1 (:obj:`list` of str): CI fields of study. group2 (:obj:`list` of str): AI fields of study. Returns: ...
def update_env_vars_with_tf_var_values(os_env_vars, tf_vars): """Return os_env_vars with TF_VAR_ values for each tf_var.""" # https://www.terraform.io/docs/commands/environment-variables.html#tf_var_name for (key, val) in tf_vars.items(): if isinstance(val, dict): os_env_vars["TF_VAR_%s"...
def valid_type(str_of_type): """Function for returning a pandas type given a string value representing that type Args: str_of_type (str): a python type in string form Outputs: the Pandas term for that type """ if str_of_type in ['int','integer']: re...
def normalize_text(s): """Normalizes content of a text field""" return (s or '').strip().replace('\r', '')
def unpackinteger(s): """ The lexicographic integer unpacking :param s: The encoding bytes/string to decode to an integer :type s: str/bytes """ if isinstance(s, (str, bytes)): b = [int(s[i:i + 2], 16) for i in range(0, len(s), 2)] else: b = s # trivial case if len(...
def get_entry_param_name_from_content(entry, param_content): """ e.g. given 'cTextureSampler-bob!hi:hello' (or even just '!hi:hello') and 'hello', give 'hi' """ param_cropped_right = entry[:entry.find(param_content) - 1] param_name = param_cropped_right[param_cropped_right.rfind("!") + 1:] retur...
def new_varname(var, nname): """ var:str Old variable of format varname|bla|bla nname:str name for the resulting variable, based on var Returns ------- new variable name with nname|bla|bla """ return nname + '|' + '|'.join(var.split('|')[1:])
def get_hostgroup_type(code): """Get hostgroup type from code.""" hostgroup_type = {0: "Not internal", 1: "Internal"} if code in hostgroup_type: return hostgroup_type[code] + " (" + str(code) + ")" return "Unknown ({})".format(str(code))
def extract_enviro_params(params, delta): """ Processes the VUMPS params into those specific to the reduced-environment solver. """ keys = ["env_tol", "env_maxiter", "outer_k_lgmres", "inner_m_lgmres"] enviro_params = {k: params[k] for k in keys} # Extract subset of dict if params["adaptiv...
def clean_whitespaces(text): """ Remove multiple whitespaces from text. Also removes leading and trailing \ whitespaces. :param text: Text to remove multiple whitespaces from. :returns: A cleaned text. >>> clean_whitespaces("this is a text with spaces") 'this is a text with spaces' ...
def get_typing_type(plotly_type, array_ok=False): """ Get Python type corresponding to a valType string from the plotly schema Parameters ---------- plotly_type : str a plotly datatype string array_ok : bool Whether lists/arrays are permitted Returns ------- str ...
def is_inverted(photo_interp: str) -> bool: """Checks if pixel value 0 corresponds to white. See DICOM specification for more details.""" if photo_interp == "MONOCHROME1": return True elif photo_interp != "MONOCHROME2": # I don't think we need to handle any interpretations besides MONOCHROME...
def initiative_sort(init_order): """sorts all the characters for a given combat by initiative""" print("passed into sort function: ", init_order) for i in range(len(init_order)): check = init_order[i] print("the check is: ", check, " and i is: ", i) index = i while index > 0...
def param_strip(param): """Strips the key text info out of certain parameters""" return str(param)[:str(param).find('(')]
def compte_voyelles(mot: str) -> int: """Compte le nombre de voyelles dans le mot.""" total: int = 0 for lettre in mot: if lettre in "AEIOUY": total += 1 return total
def find_end_of_continued_line(lines, start_line: int): """Find the last line of a line explicitly extended using backslashes. Uses 0-indexed line numbers. """ end_line = start_line while lines[end_line].endswith('\\\n'): end_line += 1 if end_line >= len(lines): break ...
def block_label_tuple_to_string(block_tuple) : """ Parameters ------------ block_tuple : tuple Tuple containing the region name (str) and (pair of ages) Returns -------------- block_str : str String containing reduced info. """ name = block_tuple[0] name.split...
def str_to_list(data): """ Converts a string delimited by \n and \t to a list of lists. :param data: :type data: str :return: :rtype: List[List[str]] """ if isinstance(data, list): return data try: if data[-1] == '\n': data = data[:-1] except IndexEr...