content
stringlengths
42
6.51k
def parse_process_overviews(process_list): """ Extracts the two process list items that provide overview on OS and RDS processes as groups within the instance, so they can be used to create metrics under those two groups. :param process_list: The process list as delivered by CloudWatch Logs, ...
def convert(number): """ Convert a number to a string of raindrop sounds. param: int number return: str formatted string based on input """ if number % 7 == 0 and number % 5 == 0 and number % 3 == 0: return "PlingPlangPlong" if number % 7 == 0 and number % 5 == 0: return "P...
def entry_of_obj(entries, obj): """Returns the (first) entry withthe specified obj """ for e in entries: if e.obj == obj: return e return None
def get_blocks(message, block_size=256): """ Splits a message (bytes) into blocks of size block_size, then encodes each block as a base 256 integer. Can be reversed using get_bytes :param message: Message (bytes) :param block_size: Block size (int) :return: Blocks (list of int) """ blo...
def backends_mapping(custom_backend): """ Create backend with path "/bin" """ return {"/bin": custom_backend("backend_bin")}
def quote(s): """Generate a string form for Tcl, that doesn't evaluate. Use poke & peek to avoid this. But if you're generating code, you need it. """ return '"' + s.replace("\\", "\\\\").replace('[', '\\[').replace('$', '\\$').replace('"', '\\"') + '"'
def _make_name(*args, sep="_"): """ Combine elements of `args` into a new string """ _args = (arg for arg in args if arg != "") return sep.join(_args)
def validate_provider_name(name, supported_majors): """ Validates the provider name against the format in the specification: <protocol-version>.dnscrypt-cert.<zone> """ try: version, cert, _ = name.split('.', 2) return version in supported_majors and cert == 'dnscrypt-cert' exce...
def _filter_by_type( dict_interfaces: dict, # interfaecs dict type_interfaces: str, # string with type # Debug verbose: bool = False, ): """ Function that filters a `dict` by type of interface """ dict_filtered = {} for key in dict_interfaces: # Filter if type_inte...
def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5...
def trapezoid_area(base_minor, base_major, height): """Returns the area of a trapezoid""" return ((base_minor+base_major)/2)*height
def check_arguments(args, required_keys, optional_keys_take_lists=False, argument_name='arguments'): """Verifies that args adheres to the "arguments" format. The arguments format is the format expected by "arguments" in, for example, diogenes.modify.choose_cols_where, diogenes.modi...
def format_input (phrase): """Formats input to account for different symbolic conventions""" def insert_perc (phrase): """Inserts percentages in spaces between keywords""" reserved_chars = '()&|<>[]~{} ' while ' ' in phrase: phr...
def SearchBuilders(builders, spec): """Return a list of builders which match what is specified in 'spec'. 'spec' can be a hash with a key of either 'name', 'slavename', or 'either'. This allows for flexibility in how a frontend gets information from the user. """ if 'builder' in spec: return [b for b in ...
def _median(lst): """Returns the median of the input list. Args: lst: the input list. Returns: The median of the list, or None if the list is empty/None. """ sorted_lst = sorted(lst) length = len(sorted_lst) if length % 2: return sorted_lst[length // 2] return (sorted_lst[length // 2 - 1] ...
def point_on_line(point, seg_p1, seg_p2, tol=1e-6): """Determines whether a point lies on a line segment Allows for a small tolerance Args: point ([float, float]): the point to test seg_p1 ([float, float]): the beginning of the line segment seg_p2 ([float, float]): the end of the l...
def get_sm_from_descriptor(descr): """ This method returns a list of specific managers based on a received desriptor """ sm_dict = {} if 'service_specific_managers' in descr: sm_dict = {} for ssm in descr['service_specific_managers']: for option in ssm['options']: ...
def _ParseLogLines(log_file_lines): """Parses a merged cyglog produced by mergetraces.py. Args: log_file_lines: array of lines in log file produced by profiled run lib_name: library or executable containing symbols Below is an example of a small log file: 5086e000-52e92000 r-xp 00000000 b3:02 5127...
def d_theta(t, alpha): """ theta'(t) = t / (alpha + |t|) Also called phi' or psi'. Baus et al 2013, table 1, Theta_2. Nikolova et al 2013, table 1, f3. Nikolova et al 2014, table 1, theta_2. """ assert alpha > 0 return t / (abs(t) + alpha)
def children(level, idx): """ Return all the children of the Healpix pixel idx at level (in nested format) :param level: Resolution level :param idx: Pixel index :return: All the parents of the pixel """ chld = [] for ind in range(4): chld.append((level + 1, 4 * idx + ind)) ...
def is_ok(data): """check for ok indication in data""" return data[0] == 0
def format_float(value, rounding=2): """default formatting operation for establishing a consistent representation of floating point and numeric values returned by API.""" return float("{:.{}f}".format(round(float(value), rounding), rounding))
def normalizeShape(shape): """ Method used to convert shape to tuple Arguments: -shape: int, tuple, list, or anything convertible to tuple Raises: -TypeError: If conversion to tuple failed Returns: A tuple representing the shape """ if isins...
def remove_quoted_text(line): """get rid of content inside quotes and also removes the quotes from the input string""" while line.count("\"") % 2 == 0 and line.count("\"") > 0: first = line.find("\"") second = line.find("\"", first+1) line = line[0:first] + line[second+1:] while ...
def find_fusion_energy_per_reaction(reactants: str) -> float: """Finds the average fusion energy produced per fusion reaction in joules from the fuel type. Args: reactants: the isotopes that are combined in the fusion even. Options are "DD" or "DT" Returns: The average energy...
def is_numpy_convertable(a): """Evaluate whether an array can be converted to a numpy array.""" return hasattr(a, "__array__") or hasattr(a, "__array_interface__")
def cipher(text, shift, encrypt=True): """ Function Description: ---------- The Caesar cipher is one of the simplest and most widely known encryption techniques. In short, each letter is replaced by a letter some fixed number of positions down the alphabet. Parameters: ---------- ...
def denumerate(enum_list): """ denumerates a list of tuples into a word :param enum_list: list of tuples with the 1st index in the tuple being the position of the letter (the 2nd elem) :return: a word formed from the 'denumeration' or False if it does not start from 0 :rtype: str or bool """...
def consoliate_and_sort_taxonomy(genus_species_taxid): """Remove any redundant entries, returns new sorted list. Drops zero taxid entries if has matching non-zero entry. Drops genus only entries if have species level entries. Note ignoring the TaxID here - would need to know the parent/child relat...
def convert_to_list_dict(lst, label): """Convert a value or list into a list of dicts.""" if not lst: return None if not isinstance(lst, list): lst = [lst] return [{label: x} for x in lst]
def startswith_str(text, prefix, start=None, end=None): """ Determines if ``text`` starts with the specified prefix. The prefix can also be a tuple of prefixes to look for. With optional parameter ``start``, the test will begin at that position. With optional parameter ``end``, the test will ...
def function_f1a(x): """Function with one argument, returning one value. :type x: types.IntType :rtype: types.StringType """ return '{}'.format(x)
def _make_recur(obj, cls, make_fn, **options): """ :param obj: An original mapping object :param cls: Another mapping class to make/convert to :param make_fn: Function to make/convert to """ return cls((k, None if v is None else make_fn(v, **options)) for k, v in obj.items())
def encode_binary(x, width): """Convert integer x to binary with at least width digits.""" assert isinstance(x, int) xb = bin(x)[2:] if width == 0: assert x == 0 return '' else: assert len(xb) <= width pad = width - len(xb) return '0' * pad + xb
def hex_to_rgb(value): """Given a color in hex format, return it in RGB.""" values = value.lstrip('#') lv = len(values) rgb = list(int(values[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) return rgb
def valid_interface_data(samples): """Check if samples are valid InterfaceData.""" return (isinstance(samples, (tuple, list)) and len(samples) == 2 and all(isinstance(sample, (tuple, list, float, int)) for sample in samples) and (isinstance(samples[0], float) or len(samples[0...
def get_conversion(from_system: str, to_system: str) -> str: """Heuristic method to obtain conversion path.""" return f"{from_system}2{to_system}"
def dot_prod(a, b): """ two vector dot product a: list b: list return: float """ return sum([a[i]*b[i] for i in range(len(a))])
def largest_product(product_list): """Find the largest product from a given list.""" largest = 1 for products in product_list: if largest < max(products): largest = max(products) return largest
def numbers_are_equal(a,b,epsilon=1e-14): """ Compare two numbers a and b within epsilon. :param a: float, int or any scalar :param b: float, int or any scalar :param epsilon: threshold above which a is considered different from b :return: boolean """ return abs(a-b) < epsilon
def project(radius, ordinates, z): """ given two points (0,-radius), (ordinates, z) find the line that goes trough them and get the ordinate of it's intersection with the horizontal axis :param radius: :param ordinates: :param z: """ return radius * ordinates / (z + radius)
def containedStructure(containee, container): """ Checks weather the structure of the given containee is contained in the given container. This is similar to sameStructure with the difference that only a subset has to be matching. To the structure counts the type of the value except None which matc...
def collect_srv_data(srv_data, gromacs_config, cerise_config): """ Add all the relevant information for the job and service to the service dictionary """ # create a unique ID for the ligand srv_data['task_id'] = cerise_config['task_id'] srv_data['username'] = cerise_config['username'] sr...
def left_pad_with_zeros(text: str, zeros_count: int) -> str: """ Pads a string with zeros from the left """ return (zeros_count * "0") + text
def dictToStyleText(style_dict): """ Convert a dictionary into an SVG/CSS style attribute """ style = '' for key in style_dict: style += "%s:%s;" % (key, style_dict[key]) return style
def to_dero(value): """Convert number in smallest unit to number in dero""" return value/10**12
def trimmer( scores: list, counts: list, direction: int = 0, threshold: int = 3, frac_retain: float = 0.9, ) -> int: """ Trimmer takes scores and direction as input and returns the position where the sequence has to be trimmed in that direction Parameters --------- scores : ...
def parser(userinput): """ goal: convert userinput into tokens type: (string) -> [string] """ return userinput.strip().split()
def string_ellipse(string, maxlen): """Clamp the string to be no longer than the maximum length. If the string is too long, we write it as "... []" where "[]" is the final part of the string. :param string: The input string. :param maxlen: The maximum length of the string. """ if len(s...
def make_sentiment(value): """Return a sentiment, which represents a value that may not exist. >>> positive = make_sentiment(0.2) >>> neutral = make_sentiment(0) >>> unknown = make_sentiment(None) >>> has_sentiment(positive) True >>> has_sentiment(neutral) True >>> has_sentiment(unk...
def get_active_lines(lines, comment_char="#"): """ Returns lines, or parts of lines, from content that are not commented out or completely empty. The resulting lines are all individually stripped. This is useful for parsing many config files such as ifcfg. Parameters: lines (list): List o...
def wind_consistency(windspeed, winddirection, variablelimit): """ Test to compare windspeed to winddirection. :param windspeed: wind speed :param winddirection: wind direction in range 1-362 :param variablelimit: maximum wind speed consistent with variable wind direction :type windspeed: float...
def filter_files(input, endings = [".js"]): """Filters a list of files for specific endings Args: input: The depset or list of files endings: The list of endings that should be filtered for Returns: Returns the filtered list of files """ # Convert input into list regardles o...
def inject_namespace( name, content, namespace=None, managed=None, filename_token=None, namespace_token=None, namespaced_org=None, logger=None, ): """ Replaces %%%NAMESPACE%%% in file content and ___NAMESPACE___ in file name with either '' if no namespace is provided or 'name...
def _to_bool(s): """Convert a value into a CSV bool.""" if s.lower() == 'true': return True elif s.lower() == 'false': return False else: raise ValueError('String cannot be converted to bool')
def remove_folders(bookmarks, folders): """Function to remove top level folders from bookmarks.""" for i, item in enumerate(bookmarks['Data Science']): if type(item) is dict: folder_name = list(item.keys())[0] if folder_name in folders: del bookmarks['Data Sc...
def _scan_file(input_regx_list, input_file): """ This function gets the list of statements matching the regular expressions provided through input_regx_list :param input_regx_list: list of regular expressions used for extracting statements with import key words :param input_file: input file ...
def V(x): """ potential energy function use units such that m = 1 and omega_0 = 1 """ return 0.5 * pow(x, 2.0)
def base64_encode(string): """ Removes any `=` used as padding from the encoded string. """ import base64 encoded = base64.urlsafe_b64encode(string.encode('utf-8')).decode('utf-8') return encoded.rstrip("=")
def removeNoneValues(dict): """ If value = None in key/value pair, the pair is removed. Python >3 Args: dict: dictionary Returns: dictionary """ return {k:v for k,v in dict.items() if v is not None}
def to_conll_iob(annotated_sentence): """ `annotated_sentence` = list of triplets [(w1, t1, iob1), ...] Transform a pseudo-IOB notation: O, PERSON, PERSON, O, O, LOCATION, O to proper IOB notation: O, B-PERSON, I-PERSON, O, O, B-LOCATION, O """ proper_iob_tokens = [] for idx, annotated_token in enumerate(annotat...
def negate(signal): """ negate the signal """ negated_signal = signal * (-1) return negated_signal
def parse_float(a): """ Converts to a float value; raise TypeError. """ try: res = float(a) return res except: msg = 'Cannot convert value to a float.\nValue: %s' % a.__repr__() raise TypeError(msg)
def get_audio_version(version): """ Get audio version into a human easy readable format. Arguments: :param version: integer :return: string """ return "MPG-%i" %(version)
def generateMQConfig(old_conf): """This function generates configuration from old one""" conf = {} conf['Host'] = old_conf['mq_host'] conf['Port'] = old_conf['mq_port'] conf['QueuePath'] = old_conf['mq_queue'] conf['Username'] = old_conf['mq_user'] conf['Password'] = old_conf['mq_password'] ...
def AVG(*expression): """ Calculates and returns the average of numeric values. See https://docs.mongodb.com/manual/reference/operator/aggregation/avg/ for more details :param expression: expression or variables :return: Aggregation operator """ return {'$avg': list(expression)} if len(e...
def smf_bindmap(bones): """Construct the SMF bindmap from the given list of Blender bones""" # Create the bindmap (i.e. which bones get sent to the shader in SMF) # See smf_rig.update_bindmap (we only need the bindmap part here!) # Only consider Blender bones that map to SMF bones # Every SMF node t...
def map_or_apply(function, param): """ Map the function on ``param``, or apply it, depending whether ``param`` \ is a list or an item. :param function: The function to apply. :param param: The parameter to feed the function with (list or item). :returns: The computed value or ``None``. ...
def sequence_split(string): """ Split a string into a list of individual values import tools print tools.sequence_split('') #[] print tools.sequence_split('3') #[3] print tools.sequence_split('3,4,5') #[3, 4, 5] print tools.sequence_split('3-5,6,1-4') #[1, 2, 3, 4, 5, 6] ...
def quality (val=None): """ Set or get image quality compression """ global _quality if val is not None: _quality = val return _quality
def lowpass(f, fo, m): """return 1./(1+(f/fo)**m) """ return 1./(1+(f/fo)**m)
def _indent(s, width=4, skip_first_line=False): """_indent(s, [width=4]) -> 's' indented by 'width' spaces The optional "skip_first_line" argument is a boolean (default False) indicating if the first line should NOT be indented. """ lines = s.splitlines(1) indentstr = ' '*width if skip_firs...
def get_dimensions(line): """ Parse and extract X, Y and Z dimensions from string Parameters ---------- line: string line contains x, y, z dimensions returns: Tuple of (int, int, int) Dimensions of the 3ddose files """ split = line.split(" ") split = [x for x in s...
def mergesort(arr): """Sorts a unsorted array""" def move(left, right, arr): """Recursive call.""" arr = [0]*(len(left)+len(right)) i = j = 0 while i+j < len(arr): if j == len(right) or i < len(left) and left[i] < right[j]: arr[i+j] = left[i] ...
def _should_compress( num_rows, num_cols, matrix_approximation_rank, min_compression_rate ): """ Returns a recommendation as to whether the 2D tensor described by the arguments is worth compressing, including statistics describing the expected savings from compression. We consider a tensor worth co...
def _get_kth_bit(x: int, k: int) -> int: """Returns the kth bit in the mask from the right. """ mask = 1 << k return x & mask
def log_list(start, end, n): """ >>> log_list(1, 100, 7) #doctest: +NORMALIZE_WHITESPACE [1.0, 2.154434690031884, 4.641588833612778, 10.0, 21.544346900318832, 46.4158883361278, 100.0] >>> log_list(-1, -10, 11) #doctest: +NORMALIZE_WHITESPACE [-1.0, -1.2589254117941673, -1.5848931924611136,...
def _merge_batches(all_groups): """Merge batches with overlapping groups. Uses merge approach from: http://stackoverflow.com/a/4842897/252589 """ merged = [] while len(all_groups) > 0: first, rest = all_groups[0], all_groups[1:] first = set(first) lf = -1 while len(f...
def isBuildJob(outFiles): """ Check if the job is a build job (i.e. check if the job only has one output file that is a lib file) """ isABuildJob = False # outFiles only contains a single file for build jobs, the lib file if len(outFiles) == 1: # e.g. outFiles[0] = user.paulnilsson....
def main(): # noqa: D207 """<md>Main test. ### docstrings It works in docstrings. The start and end quotes must be on their own lines. Drawback: `simple` does not remove leading whitespace. """ print("Hello, world!") return 0
def additive_hash(input_string: str) -> int: """A stable hash function.""" value = 0 for character in input_string: value += ord(character) return value
def equal(lst, tol=1e-12): """Check if list (lst) is equal within the specified tolerance (tol)""" diff = abs(max(lst) - min(lst)) return diff < tol
def get_latest_value(record): """ Modify incoming record, and add { 'last': 1 } as a value to it {'received_timestamp': {'S': '09/28/2019, 21:12:38.687999'}, 'status': {'S': 'CLOSE'}, 'timestamp': {'S': '09/28/2019, 17:12:38.464863'}, 'last': {'N': 1}} """ print("New Record:" + str(record[...
def create_firewall(context): """Creates a VPC firewall config. The VPC firewall config depends on the VPC network having been completely instantiated, so it includes a dependsOn reference to the list of resources generated by the network sub-template. Args: context: the DM context object. Returns:...
def add_lines(ax, data, **kwargs): """ Function to add vertical and horizontal reference lines to matplotlib axis :param ax: matplotlib axis :param data: dict of plot data :param kwargs: matplotlib keywords arguments associated with vlines/hlines :return: """ for vline in dat...
def get_line_pixels(start, end): """Bresenham's Line Algorithm Produces a list of tuples from start and end >>> points1 = get_line((0, 0), (3, 4)) >>> points2 = get_line((3, 4), (0, 0)) >>> assert(set(points1) == set(points2)) >>> debuginfo(points1) [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)] ...
def all_of_type(elements, type_check): """ Checks if all elements of a list is of a specific type Parameters ---------- elements: list List of elements to check type_check: type Type to check against Returns ------- bool True if all elements in list are of t...
def three_stats(N, X): """ Return the mean, median, and mode of X """ # sort X into ascending first (could have writen a sort function, but not the focus here) X_sorted = sorted(X) # calculate mean by summarizing all numbers sum = 0 # use a dict to store number of appearance for each nu...
def get_comb_index(i, j): """Return the index of PMT pair combinations""" return i * 30 - i * (i + 1) // 2 + j - 1
def extract_longitude(input_string): """ Extracts the longitude from the provided text, value is all in degrees and negative if West of London. :param input_string: Text to extract the longitude from. :return: Longitude """ if "E" in input_string: find_me = "E" elif "W" in input...
def base_model(name, path): """Build the common base of a contents model""" model = {} model["name"] = name # path.rsplit('/', 1)[-1] model["path"] = path model["last_modified"] = "00-00-0000" model["created"] = "00-00-0000" model["content"] = None model["format"] = None model["mim...
def complex_product(a_re, a_im, b_re, b_im): """ Computes the complex product of a and b, given the real and imaginary components of both. :param a_re: real component of a :param a_im: imaginary component of a :param b_re: real component of a :param b_im: imaginary component of a :return: tu...
def get_everyone_answers(response: list) -> int: """ Track status with boolean. Iterate over input list and each item in list. :return: Count of positive answers :rtype: int """ in_all_lines = True questions = [] for char in response[0]: in_all_lines = True for line...
def inol_percent(int_reps, flt_inol): """ Gives percent max of a lift using INOl :param int_reps: number of reps :param flt_inol: INOL score :return: percent of max that should be used (float) """ return float(-(int_reps / flt_inol - 100)) / 100
def get_selection(selection): """Return a valid model selection.""" if not isinstance(selection, str) and not isinstance(selection, list): raise TypeError('The selection setting must be a string or a list.') if isinstance(selection, str): if selection.lower() == 'all' or selection == '': ...
def from_entry(entry, param, default="") -> str: """Validate and return str value from Mikrotik API dict""" if param not in entry: return default return entry[param]
def sol(arr): """ Time complexity n2 Space complexity 1 It uses two while loops, because you need diff. 'l' and 'r' for calculating palindromic string. Ex: aba, abba """ n = len(arr) l = 0 s = 0 maxlen = 1 for i in range(1, n): l = i-1 r = i whil...
def _bjorklund(subsequences): """ Distribute onsets as evenly as possible by modifying subsequences """ while True: remainder = subsequences[-1] distributed = [] while subsequences and subsequences[-1] == remainder: distributed.append(subsequences.pop()) if no...
def parse_dag_graph(graph): """ Return a list of steps in the dag, based on the DAG graph object; method inspired by Metaflow "show" client command. :param graph: Metaflow graph, which is the _graph properties of the DAG class :return: list of dictionaries, each one describing a step in the DAG ...
def update_window_based_cooc_matrix(cooc_mat, freq_words, sentence, window_size, directional): """ Updates the co-occurrence matrix with the current sentence :param cooc_mat: the co-occurrence matrix :param freq_words: the list of frequent words :param sentence: the current sentence :param windo...