content
stringlengths
42
6.51k
def generate_one_or_none(generator, enforce=True): """ Return first item from a generator. Optionally check that nothing else was generated. Return None if nothing was generated. """ result = None for item in generator: result = item break if enforce: for item i...
def isnamedtuple(x): """ namedtuples are subclasses of tuple with a list of _fields """ t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
def convert_to_bq_string(mapping_list): """ Converts list of lists to bq INSERT friendly string :param mapping_list: list of lists where the inner lists have two items :return: bq INSERT formatted string """ bq_insert_list = [] for hpo_rdr_item in mapping_list: bq_insert_list.append(...
def HSVtoRGB(HSVcol): """ Convert HSVcol=(H,S,V) color data to RGB(R,G,B) color data :param lst HSVcol: [H(float),S(float),V(float)] :return: RGBcol(lst) - [R(int),G(int),B(int)], int(0-255) :note: H:Hue, S:Saturation,Value.Lightness,Brightness). http://en.wikipedia.org/wiki/HSL_and_HSV """ ...
def map_tags(segmented_target, original_tags, segmentation_suffix=u'@@'): """ Maps tags from the original segmentation into a new tag sequence, performing two operations: (1) append the corresponding target word to the tag (2) if the original corresponding word was segmented, duplicate the tag Para...
def split_list_at(lst, i): """ >>> split_list_at([1, 2, 3], 1) ([1], [2, 3]) """ first = lst[:i] second = lst[i:] return (first, second)
def _check_lunch_hours(time, lunch_start, lunch_end): """Checks if the time is during lunch""" return (time < lunch_start) or (time >= lunch_end)
def number_row_check(lst): """ Function to check all rows for correct numbers >>> number_row_check(['***', ' * 1', '123', '111']) False """ list_board = [] for i in lst: list_board.append(list(i)) for j in list_board: for _ in j: if _ != '*' and _ != ' ' ...
def end_of_chunk(prev_tag, tag, prev_type, type_): """Checks if a chunk ended between the previous and current word. Args: prev_tag: previous chunk tag. tag: current chunk tag. prev_type: previous type. type_: current type. Returns: chunk_end: boolean. """ c...
def extractFQDNfromX509Identity(identity): """ Givens strings like: "/O=Grid/O=NorduGrid/CN=benedict.grid.aau.dk" "/O=Grid/O=NorduGrid/CN=host/fyrkat.grid.aau.dk" this function returns the FQDN of the identity. """ if identity is None: return '.' # this is technically a hostname ...
def maybe_unsorted(low, high): """Tells if a half-open interval is big enough to possibly be unsorted.""" return high - low > 1
def decode_sudoku_to_ascii(n, solution): """Encodes a Sudoku from complex Datastructure to Ascii-art. :param n: Sidelength of the Sudoku. :param solution: The Sudoku in complex Datastructure. """ grid = [["."] * n for _ in range(n)] for i, j, d in solution: grid[i][j] = d return "\n...
def binary_fp(gold, pred): """ if there is any member of pred that overlaps with no member of gold, return 1 else return 0 """ fps = 0 for p in pred: fp = True for word in p: for span in gold: if word in span: fp = False ...
def shift(seq, n): """ left-shift a sliceable object by n :param seq: sequence to shift :type seq: string or list :param n: shift length :type n: int >>> shift('hello world', 3) 'lo worldhel' >>> shift(['sdfg', 'dsfg', '111', '222'], 1) ['dsfg', '111', '222', 'sdfg'] """ ...
def _to_bytes(value): """Converts value from str to bytes on Python 3.x. Does nothing on Python 2.7.""" return value.encode('utf-8')
def get_class(file): """ Return 1 if it is malware, 0 if benign """ return int('dsc180a-wi20-public' in file)
def is_connectable(bnode, cnode): """ >>> bnode = {'entry': {'pos': 'N'}} >>> cnode = {'entry': {'pos': 'J-K'}} >>> is_connectable(bnode, cnode) True >>> bnode = {'entry': {'pos': 'V-Y'}} >>> cnode = {'entry': {'pos': 'V-S'}} >>> is_connectable(bnode, cnode) False """ ctable ...
def max_range(pixels): """Find the index of the value (r,g,b) along which pixels has the maximum range""" r = [p[0] for p in pixels] g = [p[1] for p in pixels] b = [p[2] for p in pixels] r_range = max(r) - min(r) g_range = max(g) - min(g) b_range = max(b) - min(b) ranges = [r_range, ...
def some_text(name): """ Some method that doesn't even know about the decorator :param name: string some name :return: Some ipsum with a name """ return "Ipsum {n}, Ipsum!".format(n=name)
def check_all_jobs_complete(jobs): """Given a list of jobs from the DB, check that all are done processing.""" for job in jobs: if(job['status'] == 'processing'): return False return True
def list_ints(num): """ creates a list of integers from num to zero, starting from num. """ if num == 0: return [0] # range returns list excluding num, so just use num+1 return list(reversed(list(range(num+1))))
def compare_range(a, astart, aend, b, bstart, bend): """Compare a[astart:aend] == b[bstart:bend], without slicing. """ if (aend - astart) != (bend - bstart): return False for ia, ib in zip(range(astart, aend), range(bstart, bend)): if a[ia] != b[ib]: return False else: ...
def cleanup_string(string): """ >>> cleanup_string(u', Road - ') u'road' >>> cleanup_string(u',Lighting - ') u'lighting' >>> cleanup_string(u', Length - ') u'length' >>> cleanup_string(None) '' >>> cleanup_string(' LIT ..') 'lit' >>> cleanup_string('poor.') 'poor' ...
def coerce_int_except(v, msg): """Convert to an int, throw an exception if it isn't""" try: return int(v) except: raise ValueError("Bad value: '{}'; {} ".format(v,msg) )
def get_last_part(astring, aseparator = ':'): """ Gets the last part of an <asaparator> seprated string. """ partlist = astring.split(aseparator) return partlist[len(partlist) - 1]
def expand_dictionary(record, separator='.'): """Return expanded dictionary: treat keys are paths separated by `separator`, create sub-dictionaries as necessary""" result = {} for key, value in record.items(): current = result path = key.split(separator) for part in path[:-1]: ...
def custom_format(source, language, class_name, options, md): """Custom format.""" return '<div lang="%s" class_name="class-%s", option="%s">%s</div>' % (language, class_name, options['opt'], source)
def dot_bound(low_left_x, low_left_y, up_right_x, up_right_y): """Places dots at the corners of the specified rectangle""" coords = [(low_left_x, low_left_y), (up_right_x, low_left_y), (low_left_x, up_right_y), (up_right_x, up_right_y)] instructions = [] for (x,...
def _formatwarning(message, category, filename, lineno, line=None): # pylint: disable=unused-argument """ Replacement for warnings.formatwarning() that is monkey patched in. """ return "{}: {}\n".format(category.__name__, message)
def remove_star_from_pathway_name(pathway_name): """Remove the star that label the reference pathway in isPartOf statements. :param str statements: pathway name """ return pathway_name.replace("*", "").strip()
def agestr2years(age_str: str) -> int: """Convert an Age String into a int where the age unit is in years. Expected formats are: nnnD, nnnW, nnnM, nnnY. Notes ----- The return value may not yield precise results as the following assumptions are made: there are 365 days in a year, there are 52 ...
def chebyshev_distance(point1, point2): """! @brief Calculate Chebyshev distance (maximum metric) between between two vectors. @details Chebyshev distance is a metric defined on a vector space where the distance between two vectors is the greatest of their differences along any coordinate ...
def parse_anonymous_op_xname(xname, xop): """ Parses the xname for anonymous operations. """ dotted_name = xname.replace('/', '.') onnx_prefix = 'onnx::' aten_prefix = 'aten::' prim_prefix = 'prim::' assert xop.find(onnx_prefix) == 0 or xop.find(aten_prefix) == 0 or xop.find(prim_prefix) == 0 ...
def delta_S_I(from_to, beta, compartments, totals, model=None): """Return number of new infections. Parameters: from_to (str): transition name consisting of two compartment names separated by an underscore (e.g. S_Ic) beta (float): effective contact rate compartments (dict): dic...
def indexstart(ii=None): """ Return starting index in papers (e.g. 0 or 1-based) """ if ii is None: return 1 else: return ii + 1
def kmh_to_si(vals): """Conversion from km/hr to SI wind speed units Note ---- Code was migrated from https://github.com/nguy/PyRadarMet. Parameters ---------- vals: float float or array of floats Wind speed in km/hr Returns ------- output: float float ...
def signed2unsigned(value, byteSize): """convers a signed integer into an unsigned integer""" if byteSize == 1: if value < 0: return (value + 0x100) elif byteSize == 2: if value < 0: return (value + 0x10000) elif byteSize == 4: if value < 0: return (value + 0x100000000) # positiv...
def _build_string(node): """Builds a formatted string for displaying the nodes. References: https://github.com/joowani/binarytree/blob/master/binarytree/__init__.py#L153 Args: node (Node): An instance of the Node class (can be a tree of Nodes). Returns: Formatted string ready ...
def check_matrix_equality(A,B, tol=None): """ Checks the equality of two matrices. :param A: The first matrix :param B: The second matrix :param tol: The decimal place tolerance of the check :return: The boolean result of the equality check """ if len(A) != len(B) or len...
def toInt(sText, nDefault=None): """ :param sText: a text string :param nDefault: a default value to return if sText is not a number :return: int value of sText or None if not a number """ if type(sText) is int: return sText if type(sText) is float: return int(sText) i...
def _build_stems_to_tokens_map(stems_and_tokens): """ Build a map to substitute each stem with the shortest word if word is different """ stems_tokens_map = {} for stem, token in stems_and_tokens: if stem != token: # Ignore tokens similar to stems if stem in stems_tokens_map: ...
def distance(lat0, lon0, lat1, lon1): """This only works for small distances!""" return (lat0 - lat1)**2 + (lon0 - lon1)**2
def _of(smiles): """ Order the fragments alphabetically. If smiles is None, returns None """ if smiles is None: return None return '.'.join(sorted(smiles.split('.')))
def check_dict_keys_not_empty(d): """ * check if dictionary key has empty value by recursive method @ parameters - * d - Dictionary @ Output: * True/ False value indicating whether all dict keys are not null """ is_keys_not_empty = False for k, v in d.items(): i...
def toa_rad(swdn_toa, swup_toa, olr): """All-sky TOA downward radiative flux.""" return swdn_toa - swup_toa - olr
def str_to_bool(text): """ Parses a boolean value from the given text """ return text and text.lower() in ["true", "y", "yes", "1"]
def pref_to_str(pref_value): """If the value of a preference is None return an empty string type so we can write this data to a plist. Convert Bool values to strings for easy display in MunkiReport.""" if pref_value is None: # convert to empty string for values that are not set pref_valu...
def log2(instructions): """Integer only algorithm to calculate the number of bits needed to store a number""" bits = 1 power = 2 while power < instructions: bits += 1 power *= 2 return bits
def get_vector_bow(row): """ Given a dataframe row with an user story, return the bag of words (BoW) across the 'Role', 'Feature' and 'Benefit' columns of that user story """ bow_role = str(row['role']).split(' ') bow_feature = str(row['feature']).split(' ') bow_benefit = str(row['benefit'])...
def split_list(list, size=108): """ Splits the list into batches consisting of 108 PNG images. The function returns a list of a sub-lists. """ return [list[i:i+size] for i in range(0, len(list), size)]
def report_to_fields(report, fields=None): """ Take a single report and convert the KEY: value lines into a dict of key-value pairs. Ignore any lines that don't have a colon in them. :param report: A list of text lines. :param fields: If not None, then update an existing dict. :return: ...
def jlpoint(x, y, z): """Return a 3D coordinate dict. Args: x (float): X-coordinate. y (float): Y-coordinate. z (float): Z-coordinate. Returns: (dict): 3D coordinate object. """ try: x, y, z = float(x), float(y), float(z)...
def modpow(a,e,n): """Returns a^e (mod n). More efficient for large values than directly computing.""" if(n<1): return -1 b=bin(e)[2:] prod=1 current=a for i in range(len(b)): if(b[-i-1]=='1'): prod *= current prod %= n current *= current ...
def isvalid_config(config, key, default, valid_list, logger=None): """Function that checks if a value for key exist in config and if it doesnt exist uses the default value, and see if the value/default exists in the valid_list Args: config (dict): config object key (str): key to used to get...
def construct_dvc_url_from_git_url_dagshub(git_url: str) -> str: """ Construct the dvc url from the git url, given the git url is from DagsHub :param git_url: The git url provided :return: The dvc url """ return git_url.replace(".git", ".dvc")
def get_first_search_result(resp): """ Gets first search result from json response """ try: first_result = resp['items'][0] return first_result except IndexError: raise Exception("Repository Not Found.")
def format_fixed_width(rows): """Taken from Trey Hunner's Python Morsels. Formats output for summary.""" column_lengths = [max(len(cell) for cell in col) for col in zip(*rows)] output = "" for row in rows: for column, length in zip(row, column_lengths): output += column.ljust(length ...
def sortedSquaredArrayBetter(array): """ This function takes in a sorted array and return another sorted array which is formed by squared of elements in the input array. O(n) time complexity and O(n) space complexity. args: --------- array : sorted array with numbers output: --------- array : which consists...
def string_(string): """ Returns string or None """ if string: return string else: return None
def isbn13_checksum (isbn_str): """ Return the checksum over the coding (first 12 digits) of an ISBN-13. :Parameters: isbn_str : string An ISBN-13 without the trailing checksum digit. :Returns: The checksum character, ``0`` to ``9``. For example: >>> isbn13_checksum ("978094001673") '6' >>> isbn13...
def slices_full_ids_from_patients(patients): """ Extract full ids of cine-MRI slices that belong to specified list of patients """ slices_full_ids = [] for patient in patients: slices_full_ids.extend([slice.full_id for slice in patient.cinemri_slices]) return slices_full_ids
def myAdd(a, b): """ Adds two numbers together Parameters ---------- a : int or float First of two numbers to add together b : int or float Second of two numbers to add together Returns ------- int or float Returns the sum of the two parameters """ x...
def rgb2int(rgb_tuple): """Return the int number of a color from (r,g,b), with 0<r<1 etc.""" rgb = (int(rgb_tuple[0] * 255), int(rgb_tuple[1] * 255), int(rgb_tuple[2] * 255)) return 65536 * rgb[0] + 256 * rgb[1] + rgb[2]
def _fix_case(configuration, string): """ some databases return column names in upper case """ capabilities = configuration['capabilities'] if capabilities['reports_column_names_as_upper_case']: return string.upper() else: return string
def split_semver(version_str): """Split a SemVer-format version number into numeric representations of its components. Args: version_str (string): A SemVer-format string. Returns: list of int: A list containing numeric representations of the Major, Minor and Patch components. """ ...
def strip_slash(s): """Returns string [s] without a trailing slash. This project uses rather basic path-handling, which makes for slightly clunky but easy-to-debug code. Generally, paths CAN NOT end in slashes or f-strings using them will break! """ return s if not s[-1] == "/" else s[:-1]
def pitch_class_index_to_hue(midinum): """Returns a handpicked hue value of the pitch class index.""" hue_range = [0, 24, 48, 65, 85, 120, 185, 214, 240, 264, 284, 315] return hue_range[midinum % 12] / 120
def get_recursively1(search_object, field, search_within_field: bool = False, max_depth=100000): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided. """ fields_found = [] if not search_object or max_depth == 0: return fields_found ...
def largest_prime_factor_improved(number): """Find the largest prime factor of the given number. Seconds to execute 1000 times when finding the largest factor of 13195: 0.00467586517334. Seconds to execute 1000 times when finding the largest factor of 600851475143: 0.82680296897. Crazy! """ for can...
def cal_confidence(antecedents_support, combination_support): """ calculate confidence of antecedents and consequents Parameters ---------- antecedents_support : float support of antecedents. for example : - 0.43 combination_support : float support o...
def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ ...
def fib_basic(n): """Simple fibonacci sequence implementation Arguments: n (Integer): Index of the fibonacci number Returns: Integer: Value of the fibonacci sequence at the provided index """ if n == 0: return 0 if n == 1: return 1 return fib_basic(n - 1) + ...
def cal_sort_key(cal): """ Sort key for the list of calendars: primary calendar first, then other selected calendars, then unselected calendars. (" " sorts before "X", and tuples are compared piecewise) :param cal: a calendars :return: the sorted calendar """ if cal['selected']: ...
def pretty_size(size): """ Return human readable size as a string, eg '512GiB', for an integer size. """ if size % 1024 == 0: for suffix in ['', 'KiB', 'MiB', 'GiB', 'TiB']: if size % 1024: return '%d%s' % (size, suffix) size /= 1024 return '%d%s' ...
def update_okta_settings(okta_settings, k, v): """ Pytest-django does a shallow compare to determine which parts of its settings fixture to roll back, so if we don't replace the OKTA_AUTH dict entirely settings don't roll back between tests. """ new_settings = okta_settings.copy() new_settin...
def linear(x, m, b): """ Helper function to be used with scipy.optimize.curve_fit in order to find energy drift in a learned set of physically-interpretable ODEs """ return m * x + b
def pretty_grep_to_str(grep_result, haystack, ignore=None): """ Returns a str containing the grep results without the ignored paths :param dict grep_result: the result of a pretty_grep call :param str haystack: the base path of the grrp haystack :param list ignore: a list of str with paths to be ig...
def currencies_filter(query, code, currency_name, favorites=None): """Determine whether query matched with the code or currency name For query to match, it must not be a item in favorites (if favorites is provided), and be one of the following: * Empty query * Matching code from start (case insensi...
def num_to_char(x: int) -> str: """Converts a number to a character :param x: Number :type x: int :return: Corresponding character :rtype: str """ if x <= 26: return chr(x + 64).upper() elif x <= 26 * 26: return f"{chr(x//26+64).upper()}{chr(x%26+64).upper()}" else:...
def file_decode_type(query, type=None): """Decode file type. >>> file_decode_type('thread_41') 'thread' """ q = query.split('_') if len(q) < 2: return type return q[0]
def breakup_hyphen(s): """ Function to convert string 110-114 to list [110, 111, 112, 113, 114] """ numbers = [] l,h = map(int, s.split('-')) numbers += range(l,h+1) return numbers
def remove_invalid(string: str) -> str: """ Removes characters that Windows doesn't allow in filenames from the specified string :param s: string to remove characters from :return: the given string without invalid characters """ string = string.replace('"', "'") for invalid_char in ["\\", "/...
def unflatten(dictionary, separator=" "): """ turn flattened dict keys into nested """ hierarch_dict = dict() for key, value in dictionary.items(): parts = key.split(separator) tmp_dict = hierarch_dict for part in parts[:-1]: if part not in tmp_dict: tmp_d...
def _convert_to_type_or_raise(target_type, key, value): """Tries to convert value to a target type. Used when setting items in mappings. Args: target_type: the target type for conversion key: originating key - used in the error message value: value to be converted Returns: ...
def find_max_recursively(S, n): """Find the maximum element in a sequence S, of n elements.""" if n == 1: # reached the left most item return S[n-1] else: previous = find_max_recursively(S, n-1) current = S[n-1] if previous > current: return previous else...
def int_to_roman(number: int) -> str: """ Convert an integer to a Roman numeral. >>> int_to_roman(12) 'XII' >>> int_to_roman(2020) 'MMXX' Source: https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s24.html """ # if not 0 < number < 4000: # r...
def valid_uris(uris: set, uri_type: str = 'track') -> bool: """Checks if given uris are valid. In this case, valid means each uri is of the form: f"spotify:{uri_type}:{id_string}". Args: uris (set): Set of uris that the user would like to check for validity. uri_type (str): ...
def deg2hr(hr): """Convert hours into degrees.""" return (hr * 15.0)
def default_params(dparams, params): """Copies all key value pairs from params to dparams if not present""" matched_params = dparams.copy() default_keys = dparams.keys() param_keys = params.keys() for key in param_keys: matched_params[key] = params[key] if key in default_keys: ...
def is_equal(left, right): """ If both left and right are None, then they are equal because both haven't been initialized yet. If only one of them is None, they they are not equal If both of them is not None, then it's possible they are equal, and we'll return True and do some more comparision l...
def text_length(text: str) -> int: """The length of the text. This is one of the features. """ return len(text) - text.count(" ")
def tag_arg(tag: str): """ A countdown tag. """ return tag.lower().replace(" ", "")
def state_to_index(grid_cells, state_bounds, state): """Transforms the state into the index of the nearest grid. Args: grid_cells (tuple of ints): where the ith value is the number of grid_cells for ith dimension of state state_bounds (list of tuples): where ith tuple contains the min and ...
def factor_correction(values): """ Multiplies values by 1000 """ return(list(x*1000 for x in values))
def _set_default_contact_form(contact_form_id: int, type_id: int) -> int: """Set the default contact form for mechanical relays. :param contact_form_id: the current contact form ID. :param type_id: the type ID of the relay with missing defaults. :return: _contact_form_id :rtype: int """ if ...
def is_numpy(value): """ Determines whether the specified value is a NumPy value, i.e. an numpy.ndarray or a NumPy scalar, etc. Parameters: ----------- value: The value for which is to be determined if it is a NumPy value or not. Returns: -------- boolean: Returns T...
def square_root_3param(t, a, b, t0): """t^1/2 fit w/ 3 params: slope a, horizontal shift t0, & vertical shift b.""" return a*(t-t0)**(0.5) + b
def _map_nested_lists(f, x, *arg, **kw): """Recursively map lists, with non-lists at the bottom. Useful for applying `dd.bdd.copy_bdd` to several lists. """ if isinstance(x, list): return [_map_nested_lists(f, y, *arg, **kw) for y in x] else: return f(x, *arg, **kw)
def beautifyData(number): """ Turns number into beautiful string. e.g. 1,000,000,000 ---> 1G 1,000,000 ---> 100M 10,000 ---> 10K 10 ---> 10 """ if number > 1000000000: return str(number/1000000000) + "G" elif number > 1000000: ...
def str_to_bool(s: str) -> bool: """ Args: s: string representation of boolean, either 'True' or 'False' Returns: boolean """ if s == "True": return True assert s == "False" return False