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 (str1[i - 1] == str2[j - 1]): d = 0 else: d = 1 matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + d) # return matrix if rate: return matrix[len(str1)][len(str2)] / max([len(str1), len(str2)]) return matrix[len(str1)][len(str2)]
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 and res < 3: stack.pop(-1) else: return False if len(stack) != 0: return False else: return True
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' is a false value on input, 'x' otherwise the result of calling f(x). """ return f(x) if x else 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(')', ') ') elt_list = [elt for elt in str_line_report.split(' ') if elt != ''] elt_list_0 = elt_list[0][2:] if elt_list_0 == '': elt_list = elt_list[1:] else: elt_list[0] = elt_list_0 elt_list[-1] = elt_list[-1][0:-1] return elt_list
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_string) is int: return cmc_string # Convert string to integer cmc cmc = 0 digit_string = "" letters = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") digits = set("1234567890") for c in cmc_string: if c in letters: cmc += 1 else: digit_string += c if len(digit_string) > 0: cmc += int(digit_string) return cmc
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 = {} for k, v in d.items(): k = prefix + sep + str(k) if prefix else str(k) if isinstance(v, dict): new_d.update(flat_mapping_of_dict(v, sep=sep, prefix=k)) else: new_d[k] = v return 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), 'private': lambda k: (k.startswith('_') and not k.startswith('__') and k not in keys_to_skip), 'both': lambda k: (not k.startswith('__') and k not in keys_to_skip), 'all': lambda k: (k not in keys_to_skip), } if not mode in test: print('Wrong mode! Accepted modes: public, private, both, all.') return None check = test[mode] out = [] for k in dir(obj): if k in keys_to_skip: continue try: if check(k) and attr_type(getattr(obj, k)): out.append(k) except: pass out.sort() return out #return sorted([k for k in dir(obj) if (check(k) and # attr_type(getattr(obj, k)))])
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 = Style.RESET_ALL except: startcolor = stopcolor = "" output = "OK" if supported else "NOT OK" return f"{startcolor}{output}{stopcolor}"
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 :param cast_type: The type to be used to cast the retrieved value (this should be a valid type, with constructor). :type default_value: Object :param default_value: The default value to be used when something wrong (exception raised) occurs. :rtype: Object :return: The value casted to the defined type. """ # in case the value is none it's a special # case (type) and must return immediately if value == None: return value try: # retrieves the value type, so that an evaluation # of the requirement to proceed with the cast may # be done and decision may be taken value_type = type(value) # in case the value type is the same as the cast # type there's no need to cast the value otherwise # runs the cast operation by calling the type with # the string value to be casted if value_type == cast_type: value_casted = value else: value_casted = cast_type(value) # returns the value casted to the caller method as # expected by the cast safe operation return value_casted except Exception: # returns the default value, this is the fallback # operation because it was not possible to cast # the value properly (safe operation) return default_value
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 for the package to be None, in which case you can infer what the default package should be. """ parts = link_body.split(':') if len(parts) == 1: return None, link_body.rstrip(), link_body.rstrip() if len(parts) >= 3: pkg = parts[0] topic = parts[1] text = ":".join(parts[2:]) else: return (None, None, None) pkg = pkg or None topic = topic or text return (pkg, topic.strip(), text.strip())
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 return False
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(".", "\\.") for f in potent])
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(' `~!@#$%^&*()-+=[]\{\}|\\;:\'",.<>/?', '_' * 34) if name[0].isdigit(): name = '_'+name return name.translate(__illegal)
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 range(-maxdist, maxdist + 1) if i != 0 and 0 <= index + i <= npoints - 1]
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 article content\n<br/>\n' '<img src="../images/test-image.png"/>\n' ), }
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: return line[:line.find("#")] else: return 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] not in stats: stats[dp[0]] = [1, dp[1], dp[1]] else: stats[dp[0]][0] += 1 stats[dp[0]][1] = min(stats[dp[0]][1], dp[1]) stats[dp[0]][2] = max(stats[dp[0]][2], dp[1]) return stats
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): if obj.get(path[0]) in ["255.255.255.255", "0.0.0.0", ""]: return None else: return obj.get(path[0]) else: if obj in ["255.255.255.255", "0.0.0.0", ""]: return None else: return obj else: if isinstance(obj, list): return [find_element_by_key(i.get(path[0]), path[1]) for i in obj] elif isinstance(obj, dict): return find_element_by_key(obj.get(path[0]), path[1]) else: if obj in ["255.255.255.255", "0.0.0.0", ""]: return None else: return obj
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 character between the integral value and the unit specifier :param lim_k: any value above this limit is a candidate for KiB conversion. :param lim_m: any value above this limit is a candidate for MiB conversion. :param plural: whether to append a final 's' to byte(s) :param floor: how to behave when exact conversion cannot be achieved: take the closest, smaller value or fallback to the next unit that allows the exact representation of the input value :return: the prettyfied size """ size = int(size) if size > lim_m: ssize = size >> 20 if floor or (ssize << 20) == size: return '%d%sMiB' % (ssize, sep) if size > lim_k: ssize = size >> 10 if floor or (ssize << 10) == size: return '%d%sKiB' % (ssize, sep) return '%d%sbyte%s' % (size, sep, (plural and 's' or ''))
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 range(0, 8): if grid[(c_y[n]+y) % 8][(c_x[n]+x) % 8] > 0: neighbors += 1 return neighbors
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', 'libgl1-mesa-glx', 'libgles1-mesa', 'libgles2-mesa', 'libglx-mesa0', 'mesa-opencl-icd', 'mesa-va-drivers', 'mesa-vdpau-drivers', 'mesa-vulkan-drivers', # Provided by host system alongside Mesa if needed 'libtxc-dxtn-s2tc0', # Actually a virtual package 'libcggl', # Experimental 'libcasefold-dev', )
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 Raises: tbd """ # return username in query #fails! Jake is returned regardless of who's logging in unless whole password is entered correctly! return "Welcome" in query # should say: # "Welcome jake you are now logged in! # Log out" # if succesful
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 risk == 1.0: _index = 2 elif risk == 1.1: _index = 3 return _index
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 size') return False return True
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. Parameters ---------- psm : dict A dict, as yielded by :py:func:`read`. prefix : str, optional A prefix used to mark decoy proteins. Default is `'DECOY_'`. Returns ------- out : bool """ return all(protein['protein'].startswith(prefix) for protein in psm['search_hit'][0]['proteins'])
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 item
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) - :func:`is_plain_object` (alias) .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0 Added :func:`is_dict` as main definition and made :func:`is_plain_object` an alias. """ return isinstance(value, dict)
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 conjunctions """ text = '' if not items: text = '' elif len(items) == 1: text = items[0] elif len(items) == 2: text = '{} {} {}'.format(items[0], conjunction, items[1]) else: text = ', '.join(items[:-1]) text += ', {} {}'.format(conjunction, items[-1]) return text
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") if pos['y'] == 0: adjacent.append("up") if pos['y'] == height - 1: adjacent.append("down") return adjacent
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. """ command_chars = [chr(unicode) for unicode in tuple(range(0, 32)) + (127,)] special_chars = ([chr(unicode) for unicode in tuple(range(33, 48)) + tuple(range(58, 65)) + tuple(range(91, 95)) + (96,) + tuple(range(123, 127))], ('\\', '/', ':', '*', '?', '"', '<', '>', '|')) res = text for cm in command_chars: res = res.replace(cm, '_') for sp in special_chars[char_set]: res = res.replace(sp, '_') while res.startswith('_'): res = res[1:] while res.endswith('_'): res = res[:-1] return res
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) elif variable > 2.0: rep = '{:.3}'.format(variable) return rep
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 ---------- hours: int Difference of hours between start and end time minutes: int Difference of minutes between start and end time seconds: int Difference of seconds between start and end time """ hours = int((end_time - start_time) / 3600) minutes = int((end_time - start_time) / 60) - (hours * 60) seconds = round((end_time - start_time) % 60) return (hours, minutes, seconds)
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 should not matter as integrator change them. """ frame_padding = 4 frame_end_str_len = len(str(frame_end)) if frame_end_str_len > frame_padding: frame_padding = frame_end_str_len ext = ext or ".png" filename_prefix = filename_prefix or "" return "{}{{frame:0>{}}}{}".format(filename_prefix, frame_padding, ext)
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 examples below for details). Since this function is only meant to be used in conjuction with the _decompress() function this behaviour does not make any difference as _decompress() always returns a list of floats. :param array: The uncompressed list :type array: 1d numpy array or list of int or float :returns: The compressed representation of the array as explained in the module docstring. :rtype: str Examples: >>> _compress([3.0, 3.0, 4.2, 2.0, 2.0, 2.0]) '2x3.0 1x4.2 3x2.0' >>> _compress([0, 0, 0, 5, 5, 4, 4, 4]) '3x0 2x5 3x4' >>> _compress([0, 0.0, 0, 5, 5, 4, 4, 4]) '3x0 2x5 3x4' >>> _compress([0.0, 0, 0, 5, 5, 4, 4, 4]) '3x0.0 2x5 3x4' """ indices = "" start = array[0] counter = 1 for _ in range(1, len(array)): if array[_] == start: counter += 1 else: indices += str(counter) + "x"+str(start) + " " start = array[_] counter = 1 indices += str(counter) + "x"+str(start) return indices
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_keys will appear in key_mapping as key_mapping[key]['texkey'] = key """ return { key: {'texkey': key} for key in missing_keys }
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 in settings: value = settings[key] if isinstance(value, str): # string replacements for placeholder, replacement in [("$CR", "\x0D"), ("$LF", "\x0A"), ("$ACK", "\x06"), ("$ENQ", "\x05")]: if placeholder in value: value = value.replace(placeholder, replacement) settings[key] = value return settings
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 definition, following the BIDS schema object rules. Returns ------- :obj:`str` A sentence describing valid values for the object. """ description = "" if "anyOf" in definition.keys(): return description if definition["type"] == "boolean": description = 'Must be one of: `"true"`, `"false"`.' elif definition["type"] == "string": if "enum" in definition.keys(): # Allow enums to be "objects" (dicts) or strings enum_values = [ list(v.keys())[0] if isinstance(v, dict) else v for v in definition["enum"] ] enum_values = [f'`"{v}"`' for v in enum_values] description = f"Must be one of: {', '.join(enum_values)}." elif definition["type"] in ("integer", "number"): if "minimum" in definition.keys(): minstr = f"greater than or equal to {definition['minimum']}" elif "exclusiveMinimum" in definition.keys(): minstr = f"greater than {definition['exclusiveMinimum']}" else: minstr = "" if "maximum" in definition.keys(): maxstr = f"less than or equal to {definition['maximum']}" elif "exclusiveMaximum" in definition.keys(): maxstr = f"less than {definition['exclusiveMaximum']}" else: maxstr = "" if minstr and maxstr: minmaxstr = f"{minstr} and {maxstr}" elif minstr: minmaxstr = minstr elif maxstr: minmaxstr = maxstr else: minmaxstr = "" if minmaxstr: description = f"Must be a number {minmaxstr}." else: description = "" return description
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 + text[pos])[-order:] pos = pos + 1 if ngram in frequency: frequency[ngram] = frequency[ngram] + 1 else: frequency[ngram] = 1 return frequency
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: True if the ranges intersect False otherwise. Raises: ValueError: if the ranges are invalid. """ if range1[0] > range1[1]: raise ValueError('range1 is inverted.') if range2[0] > range2[1]: raise ValueError('range2 is inverted.') return not (range1[1] <= range2[0] or range1[0] >= range2[1])
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 = ("\\", '"', "+", ",", ";", "<", "=", ">") for char in chars_to_escape: attrval = attrval.replace(char, "\\{0}".format(char)) if attrval[0] == "#" or attrval[0] == " ": attrval = "".join(("\\", attrval)) if attrval[-1] == " ": attrval = "".join((attrval[:-1], "\\ ")) attrval = attrval.replace("\0", "\\0") return attrval
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: b.append(a_) return(b) else: return(a)
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 The refinement factor between the coarse and the fine grid. p : float The apparent order of convergence. Returns ------- float The asymptotic ratio of convergence. """ return r21**p * (gci21 / gci32)
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 {"user": user, "msg": message} except IndexError: return None
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]: return list_val[len(list_val)-1] else: i = 0 while list_time[i+1] < time: i += 1 d1 = time - list_time[i] d2 = list_time[i+1]-time return (d2 * list_val[i]+d1 * list_val[i+1])/(d1+d2)
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: break # Apply scaling & pick prefix nv = value / v np = prefixes[i] # Return tuple return (nv, np)
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 models that should not be in the target list. """ missing = [] source_ids = {m["id"]: True for m in source_list} target_ids = {m["id"]: True for m in target_list} for model in source_list: if model["id"] not in target_ids: missing.append(model) unexpected = [model for model in target_list if model["id"] not in source_ids] return (missing, unexpected)
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: return return_list if not magic_class.console.IsLoaded(): return return_list registry_helper = magic_class.console.current_helper current_key = registry_helper.GetCurrentRegistryKey() for key in current_key.GetSubkeys(): return_list.append(key.name) return return_list
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 [['a', 'b', 'c'], [1, 2, 3], ['John', 'Alice', 'Bob']] """ combined_list = [] [combined_list.append(e) for e in lsts] return combined_list
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