content
stringlengths
42
6.51k
def no_duplicates(seq): """ Remove all duplicates from a sequence and preserve its order """ # source: https://www.peterbe.com/plog/uniqifiers-benchmark # Author: Dave Kirby # Order preserving seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
def mrg(tr): """return constituency string.""" if isinstance(tr, str): return tr + ' ' else: s = '( ' for subtr in tr: s += mrg(subtr) s += ') ' return s
def parse_file_to_bucket_and_filename(file_path): """Divides file path to bucket name and file name""" path_parts = file_path.split("//") if len(path_parts) >= 2: main_part = path_parts[1] if "/" in main_part: divide_index = main_part.index("/") bucket_name = main_part[:divide_index] file_name = main_part[divide_index + 1 - len(main_part):] # Creates file name for caching gcs file locally" file_name_path_parts = file_name.split("/") gcs_file_download_path = file_name_path_parts[-1] return bucket_name, file_name, gcs_file_download_path return "", "", ""
def fib_recursive_mathy_cached(n): """Same function as "fib_recursive_mathy", but this is cached using a generic memoizer as decorator. The decorator is implemented in "./util/cache.py". """ if n < 2: return n return fib_recursive_mathy_cached(n - 1) + fib_recursive_mathy_cached(n - 2)
def centroid_points(points): """Compute the centroid of a set of points. Warnings -------- Duplicate points are **NOT** removed. If there are duplicates in the sequence, they should be there intentionally. Parameters ---------- points : sequence A sequence of XYZ coordinates. Returns ------- list XYZ coordinates of the centroid. Examples -------- >>> """ p = len(points) x, y, z = zip(*points) return [sum(x) / p, sum(y) / p, sum(z) / p]
def ext_on_list(name, lst): """ Return True if `name` contains any extension in `lst` """ for ext in lst: if name.rfind(ext) >= 0: return True return False
def _release_to_path(release): """Compatibility function, allows us to use release identifiers like "3.0" and "3.1" in the public API, and map these internally into storage path segments.""" if release == "3.0": # special case return "v3" elif release.startswith("3."): return f"v{release}" else: raise ValueError(f"Invalid release: {release!r}")
def is_blocking(blocking: str) -> bool: """ Returns True if the value of `blocking` parameter represents true else returns false. :param blocking: Value of `blocking` parameter. """ return True if blocking.lower() == "true" else False
def query_doctypes(doctypes): """ES query for specified doctypes Args: doctypes (list) Returns: ES query (JSON) """ return {"query": {"terms": {"doctype": doctypes}}}
def flatten(d: dict, _key_prefix: tuple = tuple()) -> dict: """Convert nested dict `d` to a flat dict with tuple keys. Input `_key_prefix` is prepended to the keys of the resulting dict, and is used internally for recursively flattening the dict.""" result = {} for key, value in d.items(): flat_key = _key_prefix + (key,) if isinstance(value, dict): result.update(flatten(value, flat_key)) else: result[flat_key] = value return result
def change_semicolon(new_line_changed_batch): """Replace a semicolon character with a space """ return new_line_changed_batch.replace(':', ' ')
def expected_value(win_loss_ratio, win_probability): """ Calculates expected value of a bet. :return: Returns expected value. :rtype: Float """ return win_loss_ratio * win_probability - (1 - win_probability)
def metadata(data): """Convert a dictionary of strings into an RST metadata block.""" template = ":%s: %s\n" return ''.join(template % (key, data[key]) for key in data)
def urlunparse(data): """ Modified from urlparse.urlunparse to support file://./path/to urls """ scheme, netloc, url, params, query, fragment = data if params: url = "%s;%s" % (url, params) if netloc: url = '//' + (netloc or '') + url if scheme: url = scheme + ':' + url if query: url = url + '?' + query if fragment: url = url + '#' + fragment return url
def make_safe_id(idstr): """Make safe ID attribute used in HTML. The following characters are escaped in strings: - ``/`` - ``<`` - ``>`` """ rv = idstr\ .replace(u'/', u'-')\ .replace(u'<', u'') \ .replace(u">", u'') return rv
def get_head_dict(heads): """ Takes a list of heads for a sentence and returns a dictionary that maps words to the set with their children :param heads: :return: """ #usually, you want to call get_head_dict(some_heads[1:]) #strip off -1 head_dict = dict() for (m,h) in enumerate(heads): if h not in head_dict: head_dict[h] = set() head_dict[h].add(m+1) return head_dict
def _allowed_file(filename): """ Checks if the the filename belongs to a zip file. :param filename: filename to check :return: boolean value """ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['zip']
def calculate_package_base_hazard_rate(n_active_pins: int) -> float: """Calculate the package base hazard rate (lambdaBP). :param n_active_pins: the number of active (current carrying) pins. :return: _lambda_bd; the calculated package base hazard rate. :rtype: float """ return 0.0022 + (1.72e-5 * n_active_pins)
def apply_to_field_if_exists(effect, field_name, fn, default): """ Apply function to specified field of effect if it is not None, otherwise return default. """ value = getattr(effect, field_name, None) if value is None: return default else: return fn(value)
def get_function_block(code, function_name): """ Simplistic string manipulation to find single function call 'block', for example: maven_artifact( "group", "artifact", "version" ) The logic below assumes the character ')' doesn't appear anywhere in the function name or arguments. """ start = code.index(function_name) end = code.index(")", start + len(function_name)) return code[start:end+1]
def CalculateInteraction2(dict1={}, dict2={}): """ Calculate the two interaction features by combining two different features. Usage: res=CalculateInteraction(dict1,dict2) Input: dict1 is a dict form containing features. dict2 is a dict form containing features. Output: res is a dict form containing interaction features. """ res = {} for i in dict1: for j in dict2: res[i + "*" + j] = round(dict1[i] * dict2[j], 3) return res
def is_not_zero_divisor(var1): """ Check if the given input is zero.""" tmp = list(var1) # Is it neended? if tmp == ['0']: print("\t##Zero cannot be a divisor!") return False return True
def tablename_to_dict(table, separator="."): """Derive catalog, schema and table names from fully qualified table names""" catalog_name = None schema_name = None table_name = table s = table.split(separator) if len(s) == 2: schema_name = s[0] table_name = s[1] if len(s) > 2: catalog_name = s[0] schema_name = s[1] table_name = "_".join(s[2:]) return { "catalog_name": catalog_name, "schema_name": schema_name, "table_name": table_name, "temp_table_name": "{}_temp".format(table_name), }
def igetattr(obj, attr, *args): """ Indexed getattr function Examples: >>> model = Model() >>> igetattr(model, "weight[2]") """ if "[" in attr and "]" in attr: attr = "".join("\t".join(attr.split("[")).split("]")).split("\t") indexes = "[".join(attr[1:-1]).replace("[", "][") indexes = "[" + indexes + "]" if len(indexes) >= 1 else indexes return igetattr(obj, attr[0] + indexes)[int(attr[-1])] else: return getattr(obj, attr, *args)
def correct_grd_metadata_key(original_key: str) -> str: """ Change an upper case GRD key to it's SLC metadata equivalent. By default this is uppercasing all keys; otherwise if the value in the `special_keys` dict will be used. Args: original_key: input metadata key special_keys: dictionary of special keys that require more than just lower case Return: corrected_key: corrected key name """ special_keys = { "POSX": "posX", "POSY": "posY", "POSZ": "posZ", "VELX": "velX", "VELY": "velY", "VELZ": "velZ", } if original_key in special_keys: corrected_key = special_keys[original_key] else: corrected_key = original_key.lower() return corrected_key
def evaluate_bounding_box(ctrlpts): """ Evaluates the bounding box of a curve or a surface. :param ctrlpts: control points :type ctrlpts: list, tuple :return: bounding box :rtype: list """ # Estimate dimension from the first element of the control points dimension = len(ctrlpts[0]) # Evaluate bounding box bbmin = [float('inf') for _ in range(0, dimension)] bbmax = [0.0 for _ in range(0, dimension)] for cpt in ctrlpts: for i, arr in enumerate(zip(cpt, bbmin)): if arr[0] < arr[1]: bbmin[i] = arr[0] for i, arr in enumerate(zip(cpt, bbmax)): if arr[0] > arr[1]: bbmax[i] = arr[0] return [tuple(bbmin), tuple(bbmax)]
def nps_check(type, number): """ Check size of group and return 'GOOD' or 'BAD'. """ if type == 'promoters': if number >= 200: return 'GOOD' else: return 'BAD' if type == 'passives': if number >= 100: return 'GOOD' else: return 'BAD' if type == 'detractors': if number < 100: return 'GOOD' else: return 'BAD'
def complete(tab, opts): """ get options that start with tab :param tab: query string :param opts: list that needs to be completed :return: a string that start with tab """ msg = "({0})" if tab: opts = [m[len(tab):] for m in opts if m.startswith(tab)] if len(opts) == 1: return opts[0] if not len(opts): msg = "{0}" return msg.format("|".join(opts))
def enumerate_times(list): """Enumerates through list to create list based off index values This function takes a list of timestamp string values and creates a new list containing index labels to be displayed in the historical_ecg_label ECG combobox. Args: list (list): list of string values containing timestamp data Returns: list: list of strings with timestamps plus index # """ combo_list = [] if len(list) != 0: for index, value in enumerate(list): combo_list.append("#" + str(index+1) + ": " + value) return combo_list
def is_signed_int(num_str): """ Args: num_str (str): The string that is checked to see if it represents a number Returns: bool """ # if the num_str is a digit, that means that there are no special characters within the num_str # therefore making it a nonneg int # to check if it is a signed integer, the string is checked for one "-" and then the rest being the format of a nonneg int assert isinstance(num_str, str) return num_str.isdigit() or (num_str.startswith("-") and num_str[1:].isdigit())
def sum_1(strg): """Sums first 3 digits""" sum = 0 for i in strg[:3]: sum += int(i) if sum == 0: sum = 1 return sum
def update_repository_name(repository): """Update given repository name so it won't contain any prefix(es).""" lastSlash = repository.rfind("/") # make sure we use just the repo name if lastSlash >= 0 and lastSlash < len(repository) - 1: return repository[1 + lastSlash:] else: return repository
def parseBP(s): """ :param s: string :return: string converted to number, taking account for kb or mb """ if not s: return False if s.isnumeric(): return int(s) s = s.lower() if "kb" in s: n = s.split("kb")[0] if not n.isnumeric(): return False return int(n) * 1000 elif "mb" in s: n = s.split("mb")[0] if not n.isnumeric(): return False return int(n) * 1000000 return False
def float16(val): """Convert a 16-bit floating point value to a standard Python float.""" # Fraction is 10 LSB, Exponent middle 5, and Sign the MSB frac = val & 0x03ff exp = (val >> 10) & 0x1F sign = val >> 15 if exp: value = 2 ** (exp - 16) * (1 + float(frac) / 2**10) else: value = float(frac) / 2**9 if sign: value *= -1 return value
def parse_gbi_yiqtol(tag): """Parse a GBI yiqtol tag into cohortative and jussives.""" if tag.endswith('Jm'): return 'yqtl' elif tag.endswith('Jt'): return 'jussF' elif tag.endswith('Cm'): return 'yqtl' elif tag.endswith('Ct'): return 'cohoF'
def private_ip_addresses(server): """ Get all private IPv4 addresses from the addresses section of a server. :param dict server: A server body. :return: List of IP addresses as strings. """ return [addr['addr'] for addr in server['server']['addresses']['private'] if addr['version'] == 4]
def find_rds_instance(rds_list, db_name): """ :param rds_list: :param db_name: :return: """ db_info = None for db_instance in rds_list: if db_name == db_instance['db_name']: db_info = db_instance return db_info
def isbn_13_check_digit(twelve_digits): """Function to get the check digit for a 13-digit ISBN""" if len(twelve_digits) != 12: return None try: int(twelve_digits) except: return None thirteenth_digit = 10 - int(sum((i % 2 * 2 + 1) * int(x) for i, x in enumerate(twelve_digits)) % 10) if thirteenth_digit == 10: thirteenth_digit = '0' return str(thirteenth_digit)
def locale_to_lower_upper(locale): """ Take a locale, regardless of style, and format it like "en_US" """ if '-' in locale: lang, country = locale.split('-', 1) return '%s_%s' % (lang.lower(), country.upper()) elif '_' in locale: lang, country = locale.split('_', 1) return '%s_%s' % (lang.lower(), country.upper()) else: return locale.lower()
def ring_area_factor(theta, r_in, r_out): """Compute ring area factor. Parameters ---------- theta : float On region radius r_in : float Inner ring radius r_out : float Outer ring radius """ return (r_out ** 2 - r_in ** 2) / theta ** 2
def true_smile_tokenizer(line): """Return each character or atom as the token.""" line = line.strip().replace(" ", "") len_2_tokens = ["Cl", "Br"] idx = 0 tokens = [] while idx < len(line): if idx < len(line)-1 and line[idx:idx+2] in len_2_tokens: token = line[idx:idx+2] else: token = line[idx] tokens.append(token) idx += len(token) return tokens
def npv(rate, cashflows): """The total present value of a time series of cash flows. >>> npv(0.1, [-100.0, 60.0, 60.0, 60.0]) 49.211119459053322 """ total = 0.0 for i, cashflow in enumerate(cashflows): total += cashflow / (1 + rate)**i return total
def get_center_point(box_coordinates): """ Returns the center point coordinate of a rectangle. Args: box_coordinates (list): A list of four (int) coordinates, representing a rectangle "box". Returns: list: A list with two (int) coordinates, the center point of the coordinate, i.e.: the intersection between the rectangle's diagonals. """ x1, y1, x2, y2 = box_coordinates return [int((x1 + x2) / 2), int((y1 + y2) / 2)]
def get_rr_p_parameter_default(nn: int) -> float: """ Returns p for the default expression outlined in arXiv:2004:14766. Args: nn (int): number of features currently in chosen subset. Returns: float: the value for p. """ return max(0.1, 4.5 - 0.4 * nn ** 0.4)
def short_hostname(hostname): """The first part of the hostname.""" return hostname.split(".")[0]
def addAllnonempty(master, smaller): """ Retrieve Non-empty Groups """ for s in smaller: strim = s.strip() if (len(strim) > 0): master.append(strim) return master
def finditem(func, seq): """Finds and returns first item in iterable for which func(item) is True. """ return next((item for item in seq if func(item)))
def common_languages(programmers): """Receive a dict of keys -> names and values -> a sequence of of programming languages, return the common languages""" programmers_list = [set(v) for v in programmers.values()] result = programmers_list[0] for programmer in programmers_list[1:]: result &= programmer return sorted(list(result))
def dunder_get(_dict, key): """Returns value for a specified dunderkey A "dunderkey" is just a fieldname that may or may not contain double underscores (dunderscores!) for referrencing nested keys in a dict. eg:: >>> data = {'a': {'b': 1}} >>> nesget(data, 'a__b') 1 key 'b' can be referrenced as 'a__b' :param _dict : (dict) :param key : (str) that represents a first level or nested key in the dict :rtype : (mixed) value corresponding to the key """ parts = key.split('__', 1) key = parts[0] try: result = _dict[key] except KeyError: return None except TypeError: try: result = getattr(_dict, key) except AttributeError: return None return result if len(parts) == 1 else dunder_get(result, parts[1])
def num_neighbours(lag=1): """ Calculate number of neigbour pixels for a given lag. Parameters ---------- lag : int Lag distance, defaults to 1. Returns ------- int Number of neighbours """ win_size = 2*lag + 1 neighbours = win_size**2 - (2*(lag-1) + 1)**2 return neighbours
def interleaved_sum(n, odd_term, even_term): """Compute the sum odd_term(1) + even_term(2) + odd_term(3) + ..., up to n. >>> # 1 + 2^2 + 3 + 4^2 + 5 ... interleaved_sum(5, lambda x: x, lambda x: x*x) 29 """ if n == 1: return odd_term(1) return (odd_term(n) if n % 2 == 1 else even_term(n)) + interleaved_sum(n - 1, odd_term, even_term)
def create_generator_of_subgroup(discriminant): """'Generator' as per Chia VDF competition. See: https://www.chia.net/2018/11/07/chia-vdf-competition-guide.en.html Note: This element generates a cyclic subgroup for given discriminant, not per se the entire group. """ if (1 - discriminant) % 8 == 0: g = (2, 1, (1 - discriminant) // 8) else: g = None return g
def exponential_growth(level, constant=1): """ The number of samples in an exponentially growing 1D quadrature rule of a given level. Parameters ---------- level : integer The level of the quadrature rule Return ------ num_samples_1d : integer The number of samples in the quadrature rule """ if level == 0: return 1 return constant*2**(level+1)-1
def count_paragraphs(s): """Counts the number of paragraphs in the given string.""" last_line = "" count = 0 for line in s.split("\n"): if len(line) > 0 and (len(last_line) == 0 or last_line == "\n"): count += 1 last_line = line return count
def prefix(string1, string2): """Return the prefix, if any, that appears in both string1 and string2. In other words, return a string of the characters that appear at the beginning of both string1 and string2. For example, if string1 is "inconceivable" and string2 is "inconvenient", this function will return "incon". Parameters string1: a string of text string2: another string of text Return: a string """ # Convert both strings to lower case. string1 = string1.lower() string2 = string2.lower() # Start at the beginning of both strings. i = 0 # Repeat until the computer finds two # characters that are not the same. limit = min(len(string1), len(string2)) while i < limit: if string1[i] != string2[i]: break i += 1 # Extract a substring from string1 and return it. pre = string1[0: i] return pre
def interval(f,a,b,dx): """ This function creates an interval of form [f(a), f(a+dx), ..., f(b)] Arguments f- any function of a single variable a- left end point on [a,b] b- right end point in [a,b] dx- spacing between coordinates""" k = 0 inter = [] if dx==0 or (b-a)<dx: return inter while a+k*dx <= b: inter.append(f(a+k*dx)) k+=1 return inter
def intToColorHex(color_number: int) -> str: """Convert an integer to a hexadecimal string compatible with :class:`QColor` Args: color_number: integer value of a RGB color Returns: :class:`QColor` compatible hex string in format '#rrggbb' """ return '#%0.6x' % (color_number)
def mergeTwoDicts(x, y): """ Given two dicts, merge them into a new dict as a shallow copy Assumes different keys in both dictionaries Parameters ---------- x : dictionary y : dictionary Returns ------- mergedDict : dictionary """ mergedDict = x.copy() mergedDict.update(y) return mergedDict
def select_case(*args): """:yaql:selectCase Returns a zero-based index of the first predicate evaluated to true. If there is no such predicate, returns the count of arguments. All the predicates after the first one which was evaluated to true remain unevaluated. :signature: selectCase([args]) :arg [args]: predicates to check for true :argType [args]: chain of predicates :returnType: integer .. code:: yaql> selectCase("ab" > "abc", "ab" >= "abc", "ab" < "abc") 2 """ index = 0 for f in args: if f(): return index index += 1 return index
def flatten_results(results): """Results structures from nested Gibbs samplers sometimes need flattening for writing out purposes. """ lst = [] def recurse(r): for i in iter(r): if isinstance(i, list): for j in flatten_results(i): yield j else: yield i return [r for r in recurse(results)]
def levenshtein(a,b): """Computes the Levenshtein distance between a and b.""" n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a,b = b,a n,m = m,n current = range(n+1) for i in range(1,m+1): previous, current = current, [i]+[0]*n for j in range(1,n+1): add, delete = previous[j]+1, current[j-1]+1 change = previous[j-1] if a[j-1] != b[i-1]: change = change + 1 current[j] = min(add, delete, change) return current[n]
def set_prior_6(para): """ set prior before the first data came in doc details to be added """ n_shape = para['n_shape'] log_prob = [ [] for i_shape in range(n_shape) ] delta_mean = [ [] for i_shape in range(n_shape) ] delta_var = [ [] for i_shape in range(n_shape) ] time_since_last_cp = [ [] for i_shape in range(n_shape) ] return log_prob, delta_mean, delta_var, time_since_last_cp
def getRanges(scol) : """Get sequence of ranges equal elements in a sorted array.""" ranges = [] low = 0 val = scol[low] for i in range(0,len(scol)) : if scol[i] != val : ranges.append((low,i)) low = i val = scol[i] ranges.append((low,len(scol))) return ranges
def convert_size(size_bytes, to, bsize=1024): """A function to convert bytes to a human friendly string. """ a = {"KB": 1, "MB": 2, "GB": 3, "TB": 4, "PB": 5, "EB": 6} r = float(size_bytes) for _ in range(a[to]): r = r / bsize return r
def intStr(i, total=3): """ Return a sting of the integer i begin with 0. """ return '0'*(total-len(str(i)))+str(i)
def _build_where_clause(request): """builds the search mode query depending on if search is fuzzy or exact""" variables = [] conditions = [] def _add_clause(column, value): if request["search-mode"] == 'fuzzy': conditions.append(f'{column} ILIKE %s') variables.append(f'%{value}%') else: conditions.append(f'{column} = %s') variables.append(value) for index, search in enumerate(request["filters"]): if search: _add_clause(f'levels[{index + 1}]', search) if request['campaign_code']: _add_clause('campaign_code', request['campaign_code']) if conditions: return 'WHERE ' + ' AND '.join(conditions), variables else: return '', []
def _bisect( a, x ): """ Modified 'bisect_right' from Python standard library. """ hi = len( a ) lo = 0 while lo < hi: mid = ( lo + hi ) // 2 if x < a[ mid ][ 0 ]: hi = mid else: lo = mid + 1 return lo
def munge_field(arg): """ Take a naming field and remove extra white spaces. """ if arg: res = re.sub(r'\s+', r' ', arg).strip() else: res = '' return res
def numDifference(y): """Takes First Difference Between Adjacent Points""" diff = [] for i, yi in enumerate(y[:-1]): d = y[i+1] - yi diff.append(d) diff.append(0) return diff
def get_cooling_duty(heat_utilities, filter_savings=True): """Return the total cooling duty of all heat utilities in GJ/hr.""" return - sum([i.duty for i in heat_utilities if i.flow * i.duty < 0]) / 1e6
def most_frequent(word): """Write a function called most_frequent that takes a string and prints the letters in decreasing order of frequency""" d = dict() for letter in word: d[letter] = d.setdefault(letter, 0) + 1 a = [] for letter, freq in d.items(): a.append((freq, letter)) a.sort(reverse=True) res = [] for freq, letter in a: res.append(letter) return res
def getOverlap(a,b): """takes two arrays and return if they are overlapped This is a numerical computation. [1,2.2222] is overlaped with [2.2222,2.334]""" return max(0,min(a[1],b[1]) - max(a[0],b[0]))
def _has_valid_syntax(row): """ Check whether a given row in the CSV file has the required syntax, i.e. - lemma is an existing string object - example sentence is a string and contains at least one pair of lemma markers in the right order - score is one of the following strings: '0', '1', '2', '3', '4' :param row: a dictionary containing all values in a CSV row """ lemma = row['Lemma'] sentence = row['Example'] score = row['Score'] # check lemma if lemma is None or type(lemma) != str: return False # check sentence if sentence is None or type(sentence) != str or not sentence.__contains__('_&') or not sentence.__contains__('&_'): return False i = sentence.index('_&') j = sentence.index('&_') if i >= j: return False # check score valid_scores = ['0', '1', '2', '3', '4'] if score is None or type(score) != str or score not in valid_scores: return False return True
def keyword_filter(url, keywords=None): """return true if url contains all keywords, return false otherwise """ if not keywords: return True return all(keyword in url for keyword in keywords)
def get_sources_filters(provider, application): """ Return names to use to filer sources Args: provider (str): provider name. application (str): Application type. Returns: list of str: sources names """ provider = provider or '' return [key for key in ('common', provider.split(',')[0], application) if key]
def make_target(objtype, targetid): """Create a target to an object of type objtype and id targetid""" return "coq:{}.{}".format(objtype, targetid)
def _make_contact_point(dataset): """De estar presentes las claves necesarias, genera el diccionario "contactPoint" de un dataset.""" keys = [ k for k in ["contactPoint_fn", "contactPoint_hasEmail"] if k in dataset ] if keys: dataset["contactPoint"] = { key.replace("contactPoint_", ""): dataset.pop(key) for key in keys } return dataset
def _linear_matrix_index(ell, mp, m): """Index of array corresponding to matrix element This gives the index based at the first element of the matrix, so if the array is actually a series of matrices (linearized), then that initial index for this matrix must be added. This assumes that the input array corresponds to [[ell,mp,m] for ell in range(ell_min,ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] """ return (ell + m) + (ell + mp) * (2 * ell + 1)
def pack_namedtuple_base_class(name: str, index: int) -> str: """Generate a name for a namedtuple proxy base class.""" return "namedtuple_%s_%d" % (name, index)
def first_missing_positive(nums): """ Find the first missing positive integer in a list of integers. This algorithm sorts the array by making swaps and ignoring elements that are greater than the length of the array or negative. If the element is equal to the current index (start) then it is already in place. If the element is < 0 or > len() or a duplicate, then pull in the last element. Otherwise swap the current element into place with the element that is occupying it's appropriate place. Do this until the current value is the correct one for its place or the start and end have swapped. Args: nums: list of integers Returns: The first integer greater than 0 that is not present in the input list. """ start = 0 end = len(nums) - 1 while start <= end: i = nums[start] - 1 # if this element is in position if i == start: start += 1 # if the element is negative or out of bounds # or a duplicate that is already sorted swap the # current element into the oob and dec the end elif i < 0 or i > end or nums[start] == nums[i]: nums[start] = nums[end] end -= 1 # swap the element to where it should be else: nums[start], nums[i] = nums[i], nums[start] return start + 1
def is_iterable(variable): """ Returns True if variable is a list, tuple or any other iterable object """ return hasattr(variable, '__iter__')
def get_obj_from_list(identifer, obj_list, condition=lambda o: True): """ Return a dict the name of the object as its Key e.g. { "fn_mock_function_1": {...}, "fn_mock_function_2": {...} } :param identifer: The attribute of the object we use to identify it e.g. "programmatic_name" :type identifer: str :param obj_list: List of Resilient Objects :type obj_list: List :param condition: A lambda function to evaluate each object :type condition: function :return: Dictionary of each found object like the above example :rtype: Dict """ return dict((o[identifer].strip(), o) for o in obj_list if condition(o))
def get_overall_pixel_position(c): """ returns the pixel position in terms of its location in the new coordinate system, e.g., Top left == 'TL' """ if (c[1] >= 0.5): if (c[0] >= 0.5): return "TR" elif (c[0] <= -0.5): return "TL" else: return "T" elif (c[1] <= -0.5): if (c[0] >= 0.5): return "BR" elif (c[0] <= -0.5): return "BL" else: return "B" else: if (c[0] >= 0.5): return "R" elif (c[0] <= -0.5): return "L" else: return "M"
def id_for_label(value): """generate a test id for labels""" return f"labels->{value}"
def _makeFunctionStatement(function_name, inputs): """ :param function_name: string name of the function to be created :param inputs: list of column names that are input to the function :return: statements """ statement = "def %s(" % function_name statement += ", ".join(inputs) statement += "):" return statement
def TransformMap(r): """Applies the next transform in the sequence to each resource list item. Example: list_field.map().foo().bar() applies foo() to each item in list_field and then bar() to the resulting value. list_field.map().foo().map().bar() applies foo() to each item in list_field and then bar() to each item in the resulting list. Args: r: A resource. Returns: r. """ # This method is used as a decorator in transform expressions. It is # recognized at parse time and discarded. return r
def prepare_fractions_from_common_results_struct(results): """Prepare list of fraction values for passed/failed tests.""" correct = float(results["passed%"]) incorrect = float(results["failed%"]) return [correct, incorrect]
def hosts_contain_id(hosts_data, host_id): """ True if host_id is id of a host. :param hosts_data: list of hosts :param host_id: id of a host :return: True or False """ for host in hosts_data: if host_id == host['id']: return True return False
def printable_encode(bytez, replace='.'): """ Encodes bytes given into ascii characters while non-printable characters are replaced with <p>replace</p> """ chars = bytez.decode('ascii', 'replace').replace('\ufffD', replace) return ''.join([c if c.isprintable() else '.' for c in chars])
def ucfirst(s): """Return a copy of string s with its first letter converted to upper case. >>> ucfirst("this is a test") 'This is a test' >>> ucfirst("come on, Eileen") 'Come on, Eileen' """ return s[0].upper()+s[1:]
def isValidName(name): """ Determine if the given string is a valid name. i.e. does it conflict with any of the other entities which may be on the filesystem? @param name: a name which might be given to a calendar. """ return not name.startswith(".")
def delta_f(kA, kB, NA, NB): """ Difference of frequencies """ return kA / NA - kB / NB
def parse(entrypoint): """ Parse an entrypoint string Args: entrypoint (str): The entrypoint string to parse. Returns: name (str): The name of the entrypoint package (str): The package path to access the entrypoint function func (str): The name of the function """ equals = entrypoint.count('=') colons = entrypoint.count('=') assert equals == 1 and colons == 1, RuntimeError( 'Invalid entrypoint format: "{}" Expected: ' '"alias = package.module:function"' .format(entrypoint) ) name, path = map(str.strip, entrypoint.split('=')) package, func = path.split(':') return name, package, func
def get_dist_prob_suc(t1, t2, w1, w2, decay_factor): """ Get p_dist """ return 0.5 + 0.5 * w1 * w2 * decay_factor
def first_line(s: str) -> str: """Returns the first line of a multi-line string""" return s.splitlines()[0]
def pred_thinness(depth, cuts=[0.1,0.2,0.4]): """ Rates object thinness/thickness based on measured depth """ if depth <= cuts[0]: return 'flat' elif depth > cuts[0] and depth <= cuts[1]: return 'thin' elif depth > cuts[1] and depth <= cuts[2]: return 'thick' else: return 'bulky'
def get_position_of_target(tag_sequence: str, start: int, end: int): """get index of the word that match some regex""" # number of words befor matching string prefix = len(list(tag_sequence[:start].split())) # number of words in matching string length = len(list(tag_sequence[start:end].split())) return prefix, length
def analysis_vrn_usages(analysis): """ Returns a dictionary of Var usages by row. This index can be used to quicky find a Var usage by row. 'vrn' stands for 'var row name'. """ return analysis.get("vrn_usages", {})
def truncate(text, length=30, indicator='...', whole_word=False): """Truncate ``text`` with replacement characters. ``length`` The maximum length of ``text`` before replacement ``indicator`` If ``text`` exceeds the ``length``, this string will replace the end of the string ``whole_word`` If true, shorten the string further to avoid breaking a word in the middle. A word is defined as any string not containing whitespace. If the entire text before the break is a single word, it will have to be broken. Example:: >>> truncate('Once upon a time in a world far far away', 14) 'Once upon a...' """ if not text: return "" if len(text) <= length: return text short_length = length - len(indicator) if not whole_word: return text[:short_length] + indicator # Go back to end of previous word. i = short_length while i >= 0 and not text[i].isspace(): i -= 1 while i >= 0 and text[i].isspace(): i -= 1 #if i < short_length: # i += 1 # Set to one after the last char we want to keep. if i <= 0: # Entire text before break is one word, or we miscalculated. return text[:short_length] + indicator return text[:i+1] + indicator
def format_cursor(cursor): """Format cursor inside double quotations as required by API""" return '"{}"'.format(cursor)