content
stringlengths
42
6.51k
def _isIPv4Addr(strIPv4Addr): """Confirm whether the specified address is an IPv4 address. :param str strIPv4Addr: IPv4 address string. :return: True when the specified address is an IPv4 address. :rtype: bool Example:: strIPv4Addr Return ------------------------- '...
def get_admin_site_name(context): """ Get admin site name from context. First it tries to find variable named admin_site_name in context. If this variable is not available, admin site name is taken from request path (it is first part of path - between first and second slash). """ admin_site_...
def sizeof_fmt(num, suffix='B'): """Reformats `num`, which is num bytes""" for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def join(*paths): """A shortcut for os.path.join""" import os return os.path.join(*paths)
def lookup(dic, key, *keys): """A generic dictionary access helper. This helps simplify code that uses heavily nested dictionaries. It will return None if any of the keys in *keys do not exist. :: >>> lookup({'this': {'is': 'nested'}}, 'this', 'is') nested >>> lookup({}, 'thi...
def evaluateModel(model, variables): """ Evaluates a model given all datapoints required. LModel model the model to be evaluated dict variables the variables of the model Remark Need to restrict the global values used for evaluation. return float ...
def string_to_board(board_in_string): """Converts string into sudoku board params : board_in_string : string returns : list """ board = [] for row in range(9): row_list = [] for col in range(9): row_list.append(int(board_in_string[row * 9 + col])) ...
def representative_feature(path, values): """Helper function for TSEL filter. Returns the representative node of a given path. Args: path (list): Path containing some node names. values (dict): values containing nodes and their values. Returns: str: Name of most valuable/repres...
def get_state(uid): """ :param uid: ' - '.join([relation, obj1_uid, obj2_uid, state_name]) """ state = uid.split(' - ')[-1] return state
def remove_nones(d: dict): """ Recurses through dictionary and removes keys with None values, empty strings, empty lists, and empty dicts """ _clean: dict = {} for k, v in d.items(): if isinstance(v, dict): d2 = remove_nones(v) if len(d2) > 0: _cle...
def get_in(d, ks): """ Returns the value in a nested associative structure, where `ks` is a sequence of keys. Returns None if the key is not present. Returns `d` if `ks` is empty.""" tmp = d for k in ks: tmp = tmp.get(k) if tmp is None: return None return tmp
def bonferroni(false_positive_rate, original_p_values): """ Bonferrnoi correction. :param false_positive_rate: alpha value before correction :type false_positive_rate: float :param original_p_values: p values from all the tests :type original_p_values: list[float] :return: new critical value...
def specindex(nu1, nu2, f1, alpha): """ Calculate some flux given two wavelengths, one flux, and the spectral index. """ return f1*(nu2/nu1)**(alpha)
def overflow_64(val): """ Check Overflow for 64-bit values: - result > 0xFFFFFFFFFFFFFFFF """ return (val >> 64) != 0
def is_float(z): """ Check if z[0] is a float. That usually means the board is working. """ try: float(z[0]) return True except: return False
def get_fname(config): """ Parameters ---------- config : dict A dictionary with all the arguments and flags. Returns ------- fname : str The filename for the saved model. """ hidden_dims_str = '_'.join([str(x) for x in config['hidden_dims']]) num_heads_str = '_'...
def extract_ccs_path(file_path): """Extracts and returns the ccs path from file path. Args: file_path (str): full path of file Returns: str: ccs path (contained in 'file_path') """ file_path = file_path.replace('\\', '/') index = file_path.index('ccsv') end = file_path.inde...
def msb(l): """ Given a list of bits, find the most significant bit position, counting from right E.g. For [0, 1, 0, 1], the output would be 2 :param list l: list containing bits :return int: most significant bit position in the list """ LtoR_index = min([i for i in range(len(l)) if l[i] ==...
def get_item(dictionary, tuple_key, default_value): """Grab values from a dictionary using an unordered tuple as a key. Dictionary should not contain None, 0, or False as dictionary values. Args: dictionary: Dictionary that uses two-element tuple as keys tuple_key: Unordered tuple of two e...
def genWindowCoords(n, windowLen): """Generate coordinates for the nth window""" return (n*windowLen, (n+1)*windowLen-1)
def string_to_tuple(in_str): """Splits input string to tuple at ','. Args: in_str (str): input string. Returns: tuple: Returns a tuple of strings by splitting in_str at ','. """ return tuple(substring.strip() for substring in in_str.split(","))
def extract_text(tweet): """Gets the full text from a tweet if it's short or long (extended).""" def get_available_text(t): if t['truncated'] and 'extended_tweet' in t: # if a tweet is retreived in 'compatible' mode, it may be # truncated _without_ the associated extended_tweet ...
def getPreviousTimeStep(cycle, node, burnSteps): """Return the time step before the specified time step""" if (cycle, node) == (0, 0): raise ValueError("There is not Time step before (0, 0)") if node != 0: return (cycle, node - 1) else: # index starts at zero, so the last node in...
def vector_add(first: tuple, second: tuple) -> tuple: """ 2-D simple vector addition w/o numpy overhead. Tuples must be of the same size""" return first[0] + second[0], first[1] + second[1]
def normalize_execute_kwargs(kwargs): """Replace alias names in keyword arguments for graphql()""" if "root" in kwargs and "root_value" not in kwargs: kwargs["root_value"] = kwargs.pop("root") if "context" in kwargs and "context_value" not in kwargs: kwargs["context_value"] = kwargs.pop("con...
def getGlobValue(globs, path): """ Returns the value of the glob, where path matches @param globs: The glob list (C{[(glob, associated value)]}) @type globs: C{list} of C{tuple} @param path: The path to match @type path: C{str} @return: The matched value or C{None} ...
def clean_nones(dict_to_clean): """Recursively remove all keys which values are None from a nested dictionary return the cleaned dictionary :param dict_to_clean: (dict): python dictionary to remove keys with None as value :return: dict, cleaned dictionary """ new_dict = {} for key, val in d...
def consume_byte(content, offset, byte, length=1): """Consume length bytes from content, starting at offset. If they are not all byte, raises a ValueError. """ for i in range(length-1): if content[offset + i:offset + i+1] != byte: raise ValueError(("Expected byte '0x%s' at offs...
def slope(point_a, point_b, flip): """Slope between two pixels. Parameters ---------- a : (int) (x, y) coordinate of first pixel b : (int) (x, y) coordinate of second pixel flip : bool true if slope is needed from a flipped x and y axes Returns ------- float...
def division_primality_test(p: int) -> bool: """ Standard division test for primality params: p: Number that is being tested for primality """ # negatives, 0, 1 are not prime if p < 2: return False # Checks divisors from 3 to p/2 for divisor in range(2, int(p / 2) + 1):...
def check_padding(query): """ Check for missing padding in base64 encoding and fill it up with "=". :param query: :return: query """ missing_padding = len(query) % 4 if missing_padding: query += "=" * (4 - missing_padding) return query
def sigma(l, b): """Return the sum of body 'b' for indices i1..in running simultaneously thru lists l1..ln. List 'l' is of the form [[i1 l1]..[in ln]]""" # 'l' is a list of 'n' lists of the same lenght 'L' [l1, l2, l3, ...] # 'b' is a lambda with 'n' args # 'sigma' sums all 'L' applications of '...
def overlaps_and_intact(mapped_cloth): """Take mapped cloth return No. of overlaps and fully intact claim id.""" ids, unintact_ids = set(), set() overlapped = 0 for value in mapped_cloth.values(): if len(value) > 1: ids.update(value) unintact_ids.update(value) ...
def pad(ids, pad_id, length): """Pad or trim list to len length. Args: ids: list of ints to pad pad_id: what to pad with length: length to pad or trim to Returns: ids trimmed or padded with pad_id """ assert pad_id is not None assert length is not None if len(ids) < ...
def next_nl_or_end(s, n=0): """Next newline or end of text""" # first identify starting newlines, we pass them start = n while start < len(s) - 1 and s[start] == '\n': start += 1 p = s.find('\n', start + 1) if p > -1: # Another newline found, continue until no more newlines or en...
def y_intercept_line(slope, point): """ Calculate a y-intercept of a line for given values of slope and point. Parameters ---------- slope : float A value of slope line. point : tuple A tuple with xy coordinates. Returns ------- y-intercept : float A vaule o...
def _lambda_LT_theta_com(lambda_LT, k_y_theta_com, k_E_theta_com): """ [Eq. 5.65] :param lambda_LT: Non-dimensional slenderness at normal temperature :param k_y_theta_com: Reduction factor for Young's modulus at the maximum steel temp. in the com. flange :param k_E_theta_com: Reduction factor for Yo...
def compare_sets(a, b, name, limit=None): """ :param limit: :param a: :param b: :param name: :return: """ p = '' if not isinstance(a, set): a = set(a) if not isinstance(b, set): b = set(b) d = sorted(list(a - b)) if d and limit != 'notus': p += ' ...
def defocus_to_image_displacement(W020, fno, wavelength=None): """Compute image displacment from wavefront defocus expressed in waves 0-P to. Parameters ---------- W020 : `float` or `numpy.ndarray` wavefront defocus, units of waves if wavelength != None, else units of length fno : `float` ...
def _pad_with_empty_dicts(tup, target_length=4): """Pads tuple with empty dicts""" return tup + tuple([{}] * max(0, target_length - len(tup)))
def get_dataset_json(met, version): """Generated HySDS dataset JSON from met JSON.""" return { "version": version, "label": met['data_product_name'], "starttime": met['sensingStart'], }
def convert_to_html( text ): """ Convert common utf-8 encoded characters to html for the various display of names etc.""" text = text.replace( '<', '&lt;' ) text = text.replace( '>', '&gt;' ) text = text.replace( '\xe7', '&#231;' ) #c cedilia text = text.replace( '\xe9', '&#233;' ) #e acute ...
def factorial(n): """Factorial Function -> n:int """ # print(n) if n == 1: # n < 2 return 1 else: return n * factorial(n - 1)
def hasExt(path, allowedExts): """Convenience function which returns ``True`` if the given ``path`` ends with any of the given ``allowedExts``, ``False`` otherwise. """ return any([path.endswith(e) for e in allowedExts])
def find_files_like(datapath, pattern): """Finds files in a folder whose name matches a pattern This function looks for files in folder `datapath` that match a regular expression `pattern`. Parameters ---------- datapath : str Path to search pattern : str A valid regular ex...
def find_min_max(shape): """Finds min/max coordinates for a given shape and returns a tuple of the form (minx, maxx, miny, maxy) shape: list with points""" minx = miny = 1000 maxx = maxy = -1000 for x, y in shape: if x < minx: minx = x if x > maxx: maxx = ...
def discrete_seir_update(susceptible, exposed, infected, exposure_rate, symptom_rate, recovery_rate): """All quantities are in per-population units.""" new_exposures = exposure_rate * susceptible * infected new_infections = symptom_rate * exposed new_recoveries = recovery_rate * infecte...
def sizeof_fmt(size_in_bytes: int) -> str: """ Convert file size (in bytes) to human readable format. """ value: float = size_in_bytes for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if value < 1024.0: return "{0:.2f} {1}".format(value, x) # value /= 1024.0 # ...
def _impaired_or_not(z_score, cutoff): """ Dichotimize z-score by applying a cutoff :param z_score: the z-score, i.e. performance relative to a reference population :param cutoff: the cut-off to decide impaired (<=) or preserved (>) on the cognitive domain :return: 1 if impaired, 0 if preserved """...
def recursive_obfuscate(obj, keys_to_obfuscate=('password',)): """ Recursively obfuscate the values of keys with names specified in ``keys_to_obfuscate``. return: The same object passed in but hopefully obfuscated. """ if isinstance(obj, dict): keys = obj.keys() for key in keys: ...
def _format_date(pdb_date): """Convert dates from DD-Mon-YY to YYYY-MM-DD format (PRIVATE).""" date = "" year = int(pdb_date[7:]) if year < 50: century = 2000 else: century = 1900 date = str(century + year) + "-" all_months = [ "xxx", "Jan", "Feb", ...
def _construct_output(results: list, keys: list): """A helper function to converts all results to a dict list with only the keys arguments""" output = [] for col in results: row = {} for (label, data_keys) in keys: value = col if isinstance(data_keys, list): ...
def extrap_2pt(E1, x1, E2, x2): """Performs CBS two-point linear extrapolation in 1/x**3. This tool should properly account the error bars in the energies E1 and E2, if they exist. x1 and x2 are the correlation consistent basis cardinal number.""" # Based on the formulas below, I recommended that x2 be # g...
def accuracy_score(y_true, y_pred): """Accuracy classification score. In multilabel classification, this function computes subset accuracy: the set of labels predicted for a sample must *exactly* match the corresponding set of labels in y_true. Args: y_true : 2d array. Ground truth (correc...
def linear_conv(old, min, max, new_min, new_max): """ A simple linear conversion of one value for one scale to another """ return ((old - min) / (max - min)) * ((new_max - new_min) + new_min)
def create_delete_rule(table_name): """Helper function to make SQL to create a rule to prevent deleting from the ecommerce table""" return f"CREATE RULE delete_protect AS ON DELETE TO ecommerce_{table_name} DO INSTEAD NOTHING"
def _distill_params(multiparams, params): """Given arguments from the calling form *multiparams, **params, return a list of bind parameter structures, usually a list of dictionaries. In the case of 'raw' execution which accepts positional parameters, it may be a list of tuples or lists. """ ...
def bytes_to_index(lead, tail): """ Map a pair of ShiftJIS bytes to the WHATWG index. """ lead_offset = 0x81 if lead < 0xA0 else 0xC1 tail_offset = 0x40 if tail < 0x7F else 0x41 return (lead - lead_offset) * 188 + tail - tail_offset
def change(value, reference): """ Calculate the relative change between a value and a reference point. """ if not reference: # handle both None and divide by zero case return None return ((value or 0) - reference) / float(reference)
def letters_to_exclude(word_list: list, exclude_list: list) -> list: """Remove words from word_list if they are in exclude_list of characters and return.""" return [word for word in word_list if all(char not in exclude_list for char in word)]
def binary_search_base(nums: list, target: int) -> int: """ Time complexi O(logn) The basic binary search nums is a sorted list if multi targets in nums, return one target index else return -1 """ if not nums: return -1 left, right = 0, len(nums) - 1 while left < right: ...
def _NormalizeField(field): """Takes a field name and turns it into a human readable name for display. Args: field: The field name, used to index into the inspection dict. Returns: The human readable name, suitable for display in a help string. """ if field == 'type_name': field = 'type' return...
def gather_lists(list_): """ Concatenate all the sublists of L and return the result. @param list[list[object]] list_: list of lists to concatenate @rtype: list[object] >>> gather_lists([[1, 2], [3, 4, 5]]) [1, 2, 3, 4, 5] >>> gather_lists([[6, 7], [8], [9, 10, 11]]) [6, 7, 8, 9, 10, 1...
def patch(string): """ patch for boolean variable from tojson """ if string == "false": return "False" if string == "true": return "True" return string
def LEFT(string, num_chars=1): """ Returns a substring of length num_chars from the beginning of the given string. If num_chars is omitted, it is assumed to be 1. Same as `string[:num_chars]`. >>> LEFT("Sale Price", 4) 'Sale' >>> LEFT('Swededn') 'S' >>> LEFT('Text', -1) Traceback (most recent call la...
def find_release(s): """ Given a package version string, return the release """ r = s.rpartition('-') if r[0] == '': return '' else: return r[2]
def decodeToString(toDecode): """ This function is needed for Python 3, because a subprocess can return bytes instead of a string. """ try: return toDecode.decode('utf-8') except AttributeError: # bytesToDecode was of type string before return toDecode
def splitStringIntoChunks( string, length=25 ): """ Split string into chunks of defined size """ if len(string) <= length: return [ string ] else: return [ string[ 0+i : length+i ] \ for i in range( 0, len( string ), length ) ]
def rounded_str(num): """ round the model values to 3 digits and return string :param self: :param num: :return: string rounded to 3 digits """ return str(round(num, 3))
def eh_posicao(pos): # universal -> booleano """ Indica se o argumento introduzido e uma posicao de um tabuleiro 3x3. Argumentos: pos - Argumento que sera analisado. Retorno: True - O argumento for uma posicao de um tabuleiro 3x3. False - O argumento nao e uma posicao...
def type_check(tags): """Perform a type check on a list of tags""" if type(tags) in (list, tuple): single = False elif tags == None: tags = [] single = False else: tags = [tags] single = True if len([t for t in tags if type(t) not in (str,bytes)]) == 0: valid = Tr...
def is_question(input_string): """Check if the input is a question. Parameters ---------- input_string : string String that may contain '?'. Returns ------- output_string : boolean Boolean that asserts whether the input contains '?'. """ if "?" in inp...
def create_bq_dict(parameters): """Create BigQuery Dict from parameters""" return { "barcode": parameters["barcode"], "imagecode": parameters["imagecode"], "extension": parameters["extension"], "path": parameters["path_in_db"], "width": parameters["img_width"], "h...
def nb_listener(genre, final_dic) : """Retrieves number of listeners for a specific genre thanks to the function dico_nb_listener""" if genre in final_dic : return final_dic[genre] else : return "Pas de nombre moyen d'auditeurs car ce genre n'est pas connu"
def is_int(s): """Test if a number is an integer """ try: return str(int(s)) == s except ValueError: return False
def cool_recomb(ne, nH, xn, T): """ Returns cooling due to recombination of H see Krumholz et al. (2007) 6.1e-10*ne*nH*(1.0 - xn)*kB*T*T**(-0.89) (for T>100K) """ return 8.422e-26*ne*nH*(1.0 - xn)*T**0.11
def get_edges(scan_result): """ Stores edges (connections) found in the specified scan_result in a list. Returns list. :param dict scan_result: the jsonized scan result file :return list edges: """ edges = [] if scan_result.get('linkedSites'): edges.extend(scan_result['linkedSites'...
def string_like(s): """ Return True if s operates like a string. """ try: s + '' except Exception: return False return True
def _set_columns(x, columns): """ set the columns attribute of something it is possible if columns is None, or x doesn't have an columns attribute it won't do anything """ if columns is None: return x if hasattr(x, "columns"): x.columns = columns return x
def distance_calculator(start, end_list): """Accepts start (tuple of x,y) and end_list (list of tuples of (x,y)). Returns list of tuples (x,y, distance to start)""" return_list = [] for end_spot in end_list: distance = ((end_spot[0] - start[0])**2 + (end_spot[1] - start[1])**2)*...
def create_link(n, d, suffix): """ Creates a link from the name of the manpage. This hasn't been tested extensively, as there are 10k+ links... but it's worked for the handful that I tried? """ return (n, f"http://man7.org/linux/man-pages/man{d}/{n}.{d}{suffix}.html")
def avoid_keyerror(dictionary, key): """ Returns the value associated with key in dictionary. If key does not exist in the dictionary, print out 'Avoid Exception' and map it to the string 'no value'. >>> d = {1: 'one', 3: 'three', 5: 'five'} >>> avoid_keyerror(d, 3) 'three' >>> avoid_keyer...
def d2t(d): """Dict into tuple.""" return tuple(sorted(d.items()))
def group_coadds(fname_to_spats: dict): """ Groups coadds. Destroys input. Takes in dict mapping filenames to a list of integer spatial positions Returns list of dicts mapping 'fnames' to a list of filenames and 'spats' to a list of integer spatial positions. """ # input is dict mapping...
def ge_quotient(left, right): """ Returns whether the left quotient is greater than or equal than the right quotient. Only works for quotients that have positive numerator and denominator. """ (a, b) = left (c, d) = right return a * d >= b * c
def prettycase(var): # Some Variable """ Pretty case convention. Include space between each element and uppercase the first letter of element. :param var: Variable to transform :type var: :py:class:`list` :returns: **transformed**: (:py:class:`str`) - Transformed input in ``Pretty Case`` ...
def is_bool(text): """ This function checks if a string is a boolean ("True" or "False") :type text: string :param text: string to be tested :rtype: bool :return: True if it is a boolean, False otherwise >>> is_bool("True") True >>> is_bool("False") True >>> ...
def OR(logical_expression, *logical_expressions): """ Returns True if any of the arguments is logically true, and false if all of the arguments are false. Same as `any([value1, value2, ...])`. >>> OR(1) True >>> OR(0) False >>> OR(1, 1) True >>> OR(0, 1) True >>> OR(0, 0) False >>> OR(0,F...
def str_to_bytes(string): """ Convert from string to bytes """ if string is None: return None return string.encode('utf-8')
def digitize(n): """ You have to return the digits of this number within an array in reverse order. :param n: an input integer. :return: the input integer in the form of an array in reverse order. """ return list(map(int, str(n)[::-1]))
def is_parameter(name): """Check if a section name corresponds to a parameter definition.""" return name.startswith('par-')
def is_url(path): """ Whether path is URL. Args: path (string): URL string or not. """ return path.startswith('http://') or path.startswith('https://')
def flat(mystring): """ Replace line breaks by commas """ return mystring.replace('\n', ', ')
def _merge_subject_data(subject_area_data): """Auxiliary function to collect and concatenate subject area data into string. Returns tuple of strings for subject area names, subject area codes and subject area abbreviations deliminated by ';'. """ codes = set([j.get('@code') for j in subject_area_da...
def glue_template_and_params(template_and_params) -> str: """Return wiki text of template glued from params. You can use items from extract_templates_and_params here to get an equivalent template wiki text (it may happen that the order of the params changes). """ template, params = template_and...
def fuzzy_match(keys, fuzzy_key): """Match a fuzzy key against sequence of canonical key names. :param keys: Sequence of canonical key names. :param str fuzzy_key: Fuzzy key to match against canonical keys. :returns: Canonical matching key name. :raises KeyError: If fuzzy key does not match. "...
def float_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval. Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: A float that re...
def max_compressed_bytes(length): """ return the maximum number of compressed bytes given length input integers """ cb = int((length + 3) / 4) db = length * 4 return cb + db
def map_fields(record, field_map): """ Replace field names according to field map. Used to replace ArcGIS Online reference feature service field names with database field names. Parameters ---------- record : TYPE Description field_map : TYPE Description Returns...
def _list_intersection(list1, list2): """Compute the list of all elements present in both list1 and list2. Duplicates are allowed. Assumes both lists are sorted.""" intersection = [] pos1 = 0 pos2 = 0 while pos1 < len(list1) and pos2 < len(list2): val1 = list1[pos1] val2 = list...