content
stringlengths
42
6.51k
def get_broker_leader_counts(brokers): """Get a list containing the number of leaders of each broker""" return [broker.count_preferred_replica() for broker in brokers]
def edit_distance(str1, str2, rate=True): """ Given two sequences, return the edit distance normalized by the max length. """ matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)] for i in range(1, len(str1) + 1): for j in range(1, len(str2) + 1): if (str...
def isValid(s): """ :type s: str :rtype: bool """ stack = [] for i in s: if i in [ "(", "[", "{" ]: stack.append(ord(i)) if i in [ ")", "]", "}" ]: if len(stack) == 0: return False res = ord(i) - stack[-1] if res > 0...
def bind(x, f): """ A monadic bind operation similar to Haskell's Maybe type. Used to enable function composition where a function returning a false-like value indicates failure. :param x: The input value passed to callable f is not None. :param f: A callable which is passed 'x' :return: If 'x'...
def mdotadd(a, b): """mdotadd(a, b): a[..] + b[..] for matrices""" return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
def extract_element_from_inline_bytes(line_report): """ This function is useful to extract element from a report line Args: line_report (bytes): a line array of report Returns: (list): string list of line_report elements """ str_line_report = str(line_report).replace(')', ')...
def dummy_predictor(X): """just predicts always no surge""" return [False] * len(X)
def int_if_not_none(value): """ Returns an int(value) if the value is not None. :param value: None or a value that can be converted to an int. :return: None or int(value) """ return None if value is None else int(value)
def fmt_incl_reg(chain_id, incl_regions): """Format force-include regions for optimised cesar wrapper.""" ret = [] for (start, end) in incl_regions: item = f"{chain_id} {start} {end}" ret.append(item) return ret
def cmc_from_string(cmc_string): """ Return an integer converted mana cost from cmc_string. Each character adds 1 to cmc. :param cmc_string: String or integer representation of cmc. Example: "1UBR". :returns: Integer cmc. Example: 4. """ # If int, we are done if type(cmc_stri...
def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not line.startswith("#")
def float_or_string(arg): """Tries to convert the string to float, otherwise returns the string.""" try: return float(arg) except (ValueError, TypeError): return arg
def flat_mapping_of_dict(d, sep='_', prefix=''): """ Return a copy of d, recursively unpacking all dicts. Note: This assumes all keys are strings! :param d: a dict :param sep: the prefix to a key :param prefix: the prefix to keys in this dict :return: a new dict """ new_d = {} ...
def __object_attr(obj, mode, keys_to_skip, attr_type): """list object attributes of a given type""" #print('keys_to_skip=%s' % keys_to_skip) keys_to_skip = [] if keys_to_skip is None else keys_to_skip test = { 'public': lambda k: (not k.startswith('_') and k not in keys_to_skip), 'priva...
def find_max(items: list): """From a list of items, return the max.""" max_ = None for x in items: if not max_: max_ = x continue if max_ < x: max_ = x return max_
def pga_signature(b): """0(...+)""" return 0 if b == 0 else 1
def Verbatim_f(val): """ :param val: The value of this Verbatim """ return '\\begin{verbatim}\n \\item ' + val + '\n\\end{verbatim}\n'
def show_supported(supported): """ Returns OK (in green) if supported evaluates to True, otherwise NOT OK (in red). """ try: from colorama import Fore, Back, Style from colorama import init init() startcolor = Fore.GREEN if supported else Fore.RED stopcolor = Sty...
def _cast_safe(self, value, cast_type = str, default_value = None): """ Casts the given value to the given type. The cast is made in safe mode, if an exception occurs the default value is returned. :type value: Object :param value: The value to be casted. :type cast_type: Type ...
def fix_typo(name: str) -> str: """Helper function. Fix typo in one of the tags""" return 'jednostkaAdministracyjna' if name == 'jednostkaAdmnistracyjna' else name
def isInactive(edge): """Return 1 if edge is active, else return 0.""" if edge[2] >= len(edge[4]): return 1 return 0
def bufsize(w, h, bits, indexed=False): """this function determines required buffer size depending on the color depth""" size = (w * bits // 8 + 1) * h if indexed: # + 4 bytes per palette color size += 4 * (2**bits) return size
def escape(v): """ Escapes values so they can be used as query parameters :param v: The raw value. May be None. :return: The escaped value. """ if v is None: return None elif isinstance(v, bool): return str(v).lower() else: return str(v)
def _quote_arg(arg): """ Quote the argument for safe use in a shell command line. """ # If there is a quote in the string, assume relevants parts of the # string are already quoted (e.g. '-I"C:\\Program Files\\..."') if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg
def boolean_yes_no(string): """Convert `"yes"`, `"no"` to boolean `True`, `False`.""" return string == 'yes'
def str_append (s: str, c: str, i: int) -> str: """ appends a character to a string at an index. This method *returns a value*, it does not set the value automatically""" L = list (s) L.insert (i, c) value = "" for a in L: value += str(a) return value
def count_digits (val): """ Counts the number of digits in a string. Args: val (str): The string to count digits in. Returns: int: The number of digits in the string. """ return sum(1 for c in val if c.isdigit())
def parse_link_body(link_body): """ Given the body of a link, parse it to determine what package and topic ID the link will navigate to as well as what the visual link text should be. This always returns a 3-tuple, though the value of the link text will be None if the parse failed. It's possible fo...
def is_data_true(data): """ Function takes dictionary and finds out, it contains any valid non-empty, no False, no zero value """ if not data: return False if not isinstance(data, dict): return True for _k in data: if is_data_true(data[_k]): return True ...
def sum_of_squares(v): """computes the sum of squared elements in v""" return sum(v_i ** 2 for v_i in v)
def optional(**kwargs) -> dict: """Given a dictionary, this filters out all values that are ``None``. Useful for routes where certain parameters are optional. """ return { key: value for key, value in kwargs.items() if value is not None }
def agent_name_matches(agent): """Return a sorted, normalized bag of words as the name.""" if agent is None: return None bw = '_'.join(sorted(list(set(agent.name.lower().split())))) return bw
def findingsfilter_action(action): """ Property: FindingsFilter.Action """ valid_actions = ["ARCHIVE", "NOOP"] if action not in valid_actions: raise ValueError('Action must be one of: "%s"' % (", ".join(valid_actions))) return action
def join_field(path): """ RETURN field SEQUENCE AS STRING """ output = ".".join([f.replace(".", "\\.") for f in path if f != None]) return output if output else "." # potent = [f for f in path if f != "."] # if not potent: # return "." # return ".".join([f.replace(".", "\\.") fo...
def precision(target, prediction): """Precision = TP/(TP + FP)""" if len(prediction) == 0: return 0 tp = sum(1 for p in prediction if p in target) return tp / len(prediction)
def any_in_any(a, b): """return true if any item of 'a' is found inside 'b' else return false """ if len([x for x in a if x in b]) > 0: return True else: return False
def valid_python(name): """ Converts all illegal characters for python object names to underscore. Also adds underscore prefix if the name starts with a number. :param name: input string :type name: str :return: corrected string :rtype: str """ __illegal = str.maketrans(' `~!@#$%^&*...
def restring(rec): """(Re-)serialize str or JSON-like obj in compact (minified) form""" import json if isinstance(rec, str): rec = json.loads(rec) return json.dumps(rec, separators=(",", ":"))
def has_ldflags(argv): """Check if any linker flags are present in argv.""" link_flags = set(('-ldflags', '-linkmode', '-extld', '-extldflags')) if set(argv) & link_flags: return True for arg in argv: if arg.startswith('-ldflags=') or arg.startswith('-linkmode='): return True return False
def normalize(x): """ Normalizes a vector so that it sums up to 1. """ s = sum(x) n = len(x) return [1.0/n for _ in range(n)] if s == 0 else [_/s for _ in x]
def neighborhood(index, npoints, maxdist=1): """ Returns the neighbourhood of the current index, = all points of the grid separated by up to *maxdist* from current point. @type index: int @type npoints: int @type maxdist int @rtype: list of int """ return [index + i for i in ran...
def gen_article(n): """Create article fields using a number.""" return { 'id': n, 'filename': 'test{}.html'.format(n), 'url_name': 'test-{}-url-name'.format(n), 'title': 'Test {} Title'.format(n), 'summary': 'Test {} Summary'.format(n), 'body': ( 'Test...
def __get_page_component_filename_from_page_data(page_data): """Return a generated page component filename from json page data.""" return "{}_{}.js".format(page_data["style"], str(page_data["id"]).zfill(2))
def _odds_ratio(a_n, a_p, b_n, b_p): """ doc it """ a_ratio = float(a_n) / a_p b_ratio = float(b_n) / b_p return a_ratio / b_ratio
def parity(v): """ Count number of '1' (modulo 2) in binary representation of 'v' """ return bin(v).count('1') & 1
def strip_comments(line): """Removes all text after a # the passed in string >>> strip_comments("Test string") 'Test string' >>> strip_comments("Test #comment") 'Test ' >>> strip_comments("#hashtag") '' >>> strip_comments("Test#comment") 'Test' """ if "#" in line: ...
def analyze_data(data_points:list) -> dict: """ Extracting the amount of data points for one type of data and extracts the minimum and the maximum for each type of data :param data_points: All the data points :return: The analysis """ stats = {} for dp in data_points: if dp[0] no...
def find_element_by_key(obj, key): """ Recursively finds element or elements in dict. """ path = key.split(".", 1) if len(path) == 1: if isinstance(obj, list): return [i.get(path[0]) for i in obj if i not in ["255.255.255.255", "0.0.0.0", ""]] elif isinstance(obj, dict):...
def pretty_size(size, sep: str = ' ', lim_k: int = 1 << 10, lim_m: int = 10 << 20, plural: bool = True, floor: bool = True) -> str: """Convert a size into a more readable unit-indexed size (KiB, MiB) :param size: integral value to convert :param sep: the separator char...
def get_event_type(event): """Gets the event type `event` can either be a StripeEvent object or just a JSON dictionary """ if type(event) == dict: event_type = event.get('type', None) else: event_type = event.type return event_type
def check_neighbors(x, y, grid): """ check the count of neighbors :param x: row of live cell :param y: col of live cell :param grid: grid at the time :return: number of neighbors """ neighbors = 0 c_y = [-1, -1, -1, 1, 1, 1, 0, 0] c_x = [-1, 1, 0, -1, 1, 0, -1, 1] for n in ra...
def ignore_metapackage_dependency(name): """ Return True if @name should not be installed in Steam Runtime tarballs, even if it's depended on by the metapackage. """ return name in ( # Must be provided by host system 'libc6', 'libegl-mesa0', 'libegl1-mesa', 'libegl1-mesa-drivers', 'libgl1-mesa-dri', ...
def readQuery(query): """ reads the html returned by the query and determines if login was successful Args: query: String html result of a form submission -- from sqlzoo.net/hack username: String username of login attempt Returns: boolean true iff login was successful ...
def _set_traceability_risk_icon(risk): """ Function to find the index risk level icon for requirements traceability risk. :param float risk: the Software requirements traceability risk factor. :return: _index :rtype: int """ _index = 0 if risk == 0.9: _index = 1 elif r...
def floatToString5(f: float) -> str: """Return float f as a string with five decimal places without trailing zeros and dot. Intended for places where five decimals are needed, e.g. transformations. """ return f"{f:.5f}".rstrip("0").rstrip(".")
def argument_checker(Rin, Rout): """Reads the 2 arguments in from the command line and checks if they're of the correct format""" if not (Rin < 64000 and Rin > 1024): print('ERROR: Ports of wrong size') return False if not (Rout < 64000 and Rout > 1024): print('ERROR: Ports of wrong...
def _is_decoy_prefix(psm, prefix='DECOY_'): """Given a PSM dict, return :py:const:`True` if all protein names for the PSM start with ``prefix``, and :py:const:`False` otherwise. This function might not work for some pepXML flavours. Use the source to get the idea and suit it to your needs. Paramete...
def strip_whitespace(s): """Remove trailing/leading whitespace if a string was passed. This utility is useful in cases where you might get None or non-string values such as WTForms filters. """ if isinstance(s, str): s = s.strip() return s
def trim_members_all(tap_stream_id): """ E.g. returns groups for groups_all """ return tap_stream_id.split('_')[0]
def mapCodeToString(code): """ Map the integer returned by connect() to a debug-friendly string """ return ["ERR_AUTH", "ERR_CONNECTION", "ERR_TIMEOUT", "ERR_SSH", "ERR_UNKNOWN", None, None, None, "ERR_KEYBOARD_INTERRUPT"][code]
def key_from_configdict(d): """Return key (the most inner first item) of a config dictionnary""" if not isinstance(d, dict): raise TypeError('Params of key_from_configdict() must be a dictionnary.') try: item = [k for k, v in d.items()][0] except IndexError: item = '' return ...
def is_dict(value): """Checks if `value` is a ``dict``. Args: value (mixed): Value to check. Returns: bool: Whether `value` is a ``dict``. Example: >>> is_dict({}) True >>> is_dict([]) False See Also: - :func:`is_dict` (main definition) ...
def concatenate_items(items, conjunction='and'): """Format a human-readable description of an iterable. Arguments: items (iterable): list of items to format conjunction (str): a conjunction for use in combining items Return: A text description of items, with appropriate comma and c...
def auto_incrementNumber(number): """ increments grants index """ number=number+1 return number
def isSPRelative(uri : str) -> bool: """ Check whether a URI is SP-Relative. """ return uri is not None and len(uri) >= 2 and uri[0] == "/" and uri [1] != "/"
def getAtomNumb(line): """ reads the numb from the pdbline """ if line == None: return 0 else: return int( line[ 6:11].strip() )
def emailuser(user): """Return the user portion of an email address.""" f = user.find('@') if f >= 0: user = user[:f] f = user.find('<') if f >= 0: user = user[f + 1:] return user
def against_wall(data, pos): """ Get a list of the directions of walls that the snake is adjacent to. """ width = data['board']['width'] height = data['board']['height'] adjacent = [] if pos['x'] == 0: adjacent.append("left") if pos['x'] == width - 1: adjacent.append("right") ...
def escape(s): """Return a string with Texinfo command characters escaped.""" s = s.replace('@', '@@') s = s.replace('{', '@{') s = s.replace('}', '@}') # Prevent "--" from being converted to an "em dash" # s = s.replace('-', '@w{-}') return s
def remove_special_chars(text: str, char_set=0) -> str: """Removes special characters from a text. :param text: String to be cleaned. :param char_set: 0 -> remove all ASCII special chars except for '_' & 'space'; 1 -> remove invalid chars from file names :return: Clean text. ""...
def pp(variable): """Short method for formatting output in the way I like it using duck typing""" rep = variable if isinstance(variable, int): rep = '{:,}'.format(variable) elif isinstance(variable, float): if 2.0 > variable > .00001: rep = '{:%}'.format(variable) eli...
def imt_check(grade_v, grade_i, grade_j): """ A check used in imt table generation """ return (grade_v == abs(grade_i - grade_j)) and (grade_i != 0) and (grade_j != 0)
def get_time_diff(start_time, end_time): """ Helper function to calculate time difference Args ---------- start_time: float Start time in seconds since January 1, 1970, 00:00:00 (UTC) end_time: float End time in seconds since January 1, 1970, 00:00:00 (UTC) Returns ----...
def get_frame_filename_template(frame_end, filename_prefix=None, ext=None): """Get file template with frame key for rendered files. This is simple template contains `{frame}{ext}` for sequential outputs and `single_file{ext}` for single file output. Output is rendered to temporary folder so filename sh...
def log2(x): """returns ceil(log2(x)))""" y = 0 while((1<<y) < x): y = y + 1 return y
def get_wage(x): """extracts the hourly wage from the returned HTML; verbose because John sucks at regular expressions """ return float(x.split(">")[1].split("<")[0].replace("$","").replace("/hr",""))
def _compress(array): """ Convert a list or array into a str representing the sequence of elements. If the list contains integer and float values the compressed array may be expressed in terms of integers or floats depending on the type of the first occurence of a number (see the last two exampl...
def full_rgiid(rgiid, region_id): """ return the full rgiid from region and rgi_id """ full_id = f"RGI60-{region_id}.{rgiid}" return full_id
def missing_key_dummy_mapping(missing_keys): """Create a dummy key_mapping for INSPIRE texkeys Parameters ---------- missing_keys: array of string The keys from cite_keys which are INSPIRE keys but were not found in bib_dbs. Returns ------- key_mapping: dict Each key in missing...
def luminance(pixel): """Calculates the luminance of an (R,G,B) color.""" return 0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2]
def format_commands(settings): """ format string commands Replace special characters ["$CR", "$LF", "$ACK", "$ENQ"] in settings['cmd', 'ack', 'enq']. args: settings dict() of settings return: modified settings """ for key in ['cmd', 'ack', 'enq']: if key ...
def describe_valid_values(definition): """Build a sentence describing valid values for an object from its definition. This only covers booleans, enums, integers, and numbers. Currently uncovered are anyOfs, arrays, and objects. Parameters ---------- definition : :obj:`dict` An object d...
def analyseFrequencies(text, order=1): """ Return a frequency analysis of the input text. """ if order < 1: raise(Exception) frequency = {} textlen = len(text) if textlen < order: return frequency ngram = text[0:order-1] pos = order - 1 while pos < textlen: ngram = (ngram...
def mkint48(N): """Generates a 48-bit number from four integers. Used for encoding conversion for legacy rannyu library.""" return N[3] + (N[2] << 12) + (N[1] << 24) + (N[0] << 36)
def _Intersects(range1, range2): """Tells if two number ranges intersect. Args: range1: (tuple(num, num)) tuple representing a range. The first number must be <= the second number. range2: (tuple(num, num)) tuple representing a range. The first number must be <= the second number. Returns: ...
def escape_attribute_value(attrval: str): """ Escapes the special character in an attribute value based on RFC 4514. :param str attrval: the attribute value. :return: The escaped attribute value. :rtype: str """ # Order matters. chars_to_escape = ("\\", '"', "+", ",", ";", "<", "=",...
def sec_to_jd(seconds): """seconds since J2000 to jd""" return 2451545.0 + seconds / 86400.0
def flatten(a): """recursively flatten n-nested array example: >>> flatten([[1,2],[3,4],[5,6,[7,8],]]) [1, 2, 3, 4, 5, 6, 7, 8] """ if isinstance(a, list): b = list() for a_ in a: if isinstance(a_, list): b.extend(flatten(a_)) else: ...
def asymptotic_ratio( gci21: float, gci32: float, r21: float, p: float ) -> float: """Calculate the ratio between succesive solutions. If the ratio is close to the unit, then the grids are within the asymptotic range. Parameters ---------- gci21 : float gci32 : float r21 : float ...
def average(numbers: list): """ Get the average of a list of numbers Arguments: numbers {list} -- Number list """ total_sum = 0 divisor = 0 for number in numbers: total_sum += number divisor += 1 return total_sum / divisor
def skin_base_url(skin, variables): """ Returns the skin_base_url associated to the skin. """ return variables \ .get('skins', {}) \ .get(skin, {}) \ .get('base_url', '')
def get_unique_checks(enabled): """ Gets the query the enable / disable UNIQUE_CHECKS. :type bool :param enabled: Whether or not to enable :rtype str :return A query """ return 'SET UNIQUE_CHECKS={0:d}'.format(enabled)
def _safe_parse(msg): """Parse an irc message. Args: msg (str): raw message Return: dict: {'user': user, 'msg': message} """ if "PRIVMSG" in msg: try: user = msg.split(":")[1].split("!")[0] message = msg.split(":")[2].strip() return {"use...
def interp(time, list_val, list_time): """ Return the interpolation between the time and list_time for list_val. If outside of list_time, return the first or last element of list_val """ if time <= list_time[0]: return list_val[0] elif time >= list_time[len(list_time)-1]: ...
def _apply_prefix( value, base, prefixes ): """ Test what's the maximum prefix we can apply to the specified value with the specified base """ nv = value np = "" # Test given prefixes for i in range(1, len(prefixes)): v = pow(base, i) if v >= 1: if v > value: break else: if v < value: brea...
def get_model_list_diff(source_list, target_list): """ Args: source_list (list): List of models to compare. target_list (list): List of models for which we want a diff. Returns: tuple: Two lists, one containing the missing models in the target list and one containing the mod...
def CommandCompleterCd(console, unused_core_completer): """Command completer function for cd. Args: console: IPython shell object (instance of InteractiveShellEmbed). """ return_list = [] namespace = getattr(console, 'user_ns', {}) magic_class = namespace.get('PregMagics', None) if not magic_class:...
def long_to_hex(long_num): """Convert long number to hex.""" return "%x" % long_num
def combine_arrays(*lsts: list): """Appends each given list to larger array, returning a list of lists for the final value Examples: >>> lst_abc = ['a','b','c']\n >>> lst_123 = [1,2,3]\n >>> lst_names = ['John','Alice','Bob']\n >>> combine_arrays(lst_abc,lst_123,lst_names)\n ...
def str2bool(val): """ Helper method to convert string to bool """ if val is None: return False val = val.lower().strip() if val in ['true', 't', 'yes', 'y', '1', 'on']: return True elif val in ['false', 'f', 'no', 'n', '0', 'off']: return False