content
stringlengths
42
6.51k
def get_dir_edges_from_c_to_tars(c_to_tars): """ Returns tuple of all allowed directed edges (c, t) where c control and t target. Parameters ---------- c_to_tars : dict[int, list[int]] a dictionary mapping j in range(num_qbits) to a list, possibly empty, of the physically allowe...
def list_to_lowercase(_list): """Takes in a list of strings and returns the list where each item is now lowercase: :param: _list : list which you would like to change """ _list = list(map(lambda x: x.lower(), _list)) return _list
def get_attrname(name): """Return the mangled name of the attribute's underlying storage.""" # FIXME(danms): This is just until we use o.vo's class properties # and object base. return '_obj_' + name
def obtain_name_parts(n): """ Parse the name. List of processor names + list of factor names :param n: :return: """ r = n.split(":") if len(r) > 1: full_p_name = r[0] full_f_name = r[1] else: full_p_name = r[0] full_f_name = "" p_ = full_p_name.split("...
def filter_hosts(host_specs, host_filters): """Filter out host_specs that don't match all filters in host_filters""" return sorted( ( host_spec for host_spec in host_specs if all( # Get the value for the given key, or just use filter_value ...
def convert_header_name(django_header): """Converts header name from django settings to real header name. For example: 'HTTP_CUSTOM_CSRF' -> 'custom-csrf' """ return django_header.lower().replace('_', '-').split('http-')[-1]
def tricks_to_result(tricks: int, level: int): """ Convert tricks made to a result, e.g. 8 tricks in a 4-level contract becomes -2 """ return tricks - (level + 6)
def get_absolute_pos(x, y, base): """ Returns the absolute mouse position based on the mouse position of the joystick :param x: The new x :param y: The new y :param base: A tuple containing the base position """ # give a small d...
def fold(header, namelen=0, linesep=b'\r\n'): """Fold a header line into multiple crlf-separated lines of text at column 72. The crlf does not count for line length. >>> text(fold(b'foo')) 'foo' >>> text(fold(b'foo '+b'foo'*24).splitlines()[0]) 'foo ' >>> text(fold(b'foo'*25).splitlines(...
def remove_chars(text: str, chars: str = r"\\`*_{}[]()>#+-.!$", new: str = "") -> str: """Remove characters from a string.""" for ch in chars: if ch in text: text = text.replace(ch, new) return text
def export_file(record_id: str, field_name: str, event: str, repeat_instance: str, data_format: str = 'json', *args, **kwargs): """ This method allows you to download a document that has been attached to an individual record for a File Upload field. Please note that this method may also be u...
def maybe_scream(text, do_scream=False): """Returns given text input as caps lock text, if do_scream is true. Args: text (str): Some input text do_scream (bool): Decide, whether to scream or not Returns: str: May be in caps lock """ if do_scream: text = text.up...
def extract_shape(descriptor, key): """ Work around bug in https://github.com/bluesky/ophyd/pull/746 """ # Ideally this code would just be # descriptor['data_keys'][key]['shape'] # but we have to do some heuristics to make up for errors in the reporting. # Broken ophyd reports (x, y, 0). We...
def annotate_variant(variant, var_obj=None): """Annotate a cyvcf variant with observations Args: variant(cyvcf2.variant) var_obj(dict) Returns: variant(cyvcf2.variant): Annotated variant """ if var_obj: variant.INFO["Obs"] = var_obj["observations"] if var_o...
def byname(nlist): """Convert a list of named objects into a map indexed by name""" return dict([(x.name, x) for x in nlist])
def group_supercategories(categories): """ Group supercategories by categories """ cat_to_super = {} for category in categories: cat_to_super[category['name']] = category['supercategory'] return cat_to_super
def GetMaxValue(list): """Get the max value in a list. Args: list: a value list. Returns: the max value in the list. """ maxv = list[0] for x in list: if x > maxv: maxv = x return maxv
def print_pos_neg(num): """Print if positive or negative in polarity level >>> print_pos_neg(0.8) 'positive' >>> print_pos_neg(-0.5) 'negative' """ if num > 0: return "positive" elif num == 0: return "neutral" else: return "negative"
def is_valid_product(the_list): """ :param: the_list: :type: list :return: list of illegal products :rtype: list """ illegal_list = [] for product in the_list: length_of_name = len(product) > 2 only_letters = str(product).isalpha() if not length_of_name and not on...
def default_objective(processed_data, **aux_params): """ Takes the processed data to calculate the objective to minimize Parameters ---------- processed_data : list A list of [(params, process_data(**params)), ...] that are the result of applying the process_data method across all p...
def by_name(uniprot_name): """ Return the protein name for a UniProt name with a '<name>_<species>' format. Parameters ---------- uniprot_name : str Protein name with a '<name>_<species>' format. Returns ------- str Uniprot name for specified gene. """ ...
def massString(mass): """ HELPER FUNCTION. Turns a float mass into a string with the correct units after (between mg and kg) Arguments: mass: [float] the mass to be converted Returns: mass_str: [string] the mass as a string with the proper units """ # make mass into str ...
def freshness_label(freshness_percentage): """Give freshness label""" if freshness_percentage > 90: return "Segar" elif freshness_percentage > 65: return "Baik" elif freshness_percentage > 50: return "Cukup Baik" elif freshness_percentage > 0: return "Tidak Baik" ...
def _flatten_lists(lol): """Flatten list of lists.""" flat = [] for sublist in lol: flat.extend(sublist) return flat
def enough_time(dates, day_delta): """Change detection requires a minimum amount of time (as specified by day_delta). This function, like `enough_samples` improves readability of logic that performs this check. Args: dates: list of ordinal day numbers relative to some epoch, th...
def split_currency_pair(pair): """ Example: 'btc_usd' -> 'btc', 'usd' :param pair: a string with pair of currencies :return: currency names """ splitted = pair.split('_') return splitted[0], splitted[1]
def first_item(iterable, default=None): """ Returns the first item of given iterable. Parameters ---------- iterable : iterable Iterable default : object Default value if the iterable is empty. Returns ------- object First iterable item. """ if not ...
def _norm_siteconfig_value(siteconfig, key): """Normalize site configuration values to strip extra quotation marks.""" value = siteconfig.get(key) # To work around rb-site requiring values in previous releases for these, # people would try empty quotes. We want to convert those to actual # empty st...
def _CreateDescription(agent_rules, description): """Create description in guest policy. Args: agent_rules: agent rules in ops agent policy. description: description in ops agent policy. Returns: description in guest policy. """ description_template = ('{"type": "ops-agents", "description": "%s"...
def normalize_name(s): """Normalizes the name of a file. Used to avoid characters errors and/or to get the name of the dataset from a config filename. Args: s (str): The name of the file. Returns: new_s (str): The normalized name. """ if not isinstance(s, str): raise Va...
def edge_to_agg_links(k): """ Generate the links between the edge and aggregation switches in each pod. Consists of k^3 links. :param k: k of the k-fat-tree (i.e., number of pods) :return: Edge-to-aggregation links """ links = [] for pod in range(k): for edge in range(int(k/2))...
def output_to_str(outp, split=True): """ helper to convert shell output into strings/lists """ outp = outp.decode('utf-8').strip() if split: outp = [x.strip() for x in outp.split() if x.strip()] return outp
def binary_measures(confusion_matrix, output=False): """ Calculates statistical measures from a confusion matrix Args: confusion_matrix: A 2D array of the form [ [TP FP], [TN, FN] ] output: True to print statistical measures Returns: A tuple consisting of the F1 score, precision an...
def time_spent_number(calls): """Return a dictionary with time spent for each number. Args: calls: list of calls Returns: dictionary with time spent for each number """ time_spent = {} for call in calls: caller = call[0] receiver = call[1] duration = call[...
def not_expr(term): """Creates an SMTLIB not statement formatted string Parameters ---------- terms: A list of float values to include in the expression """ return "(not " + term + ")"
def _extract_words_users(history): """Returns the set of words and the set of users in the dataset """ vocabulary = set() users = set() for t, doc, u, q in history: for word in doc.split(): vocabulary.add(word) users.add(u) return vocabulary, users
def sep_float(x): """para pasar posibles string-listas-float a listas-float""" if (isinstance(x, str)) and ("[" in x): lista = x.replace("'", "").strip("][").split(", ") return [float(x_n) for x_n in lista] elif isinstance(x,list): return [float(x_n) for x_n in x] else: ...
def safenum(v): """Return v as an int if possible, then as a float, otherwise return it as is""" try: return int(v) except (ValueError, TypeError): pass try: return float(v) except (ValueError, TypeError): pass return v
def has_variable_scope(obj): """Determines whether the given object has a variable scope.""" return hasattr(obj, "variable_scope") or "variable_scope" in dir(obj)
def _avatar_url_from_info(oauth_type, info): """Returns a URL for the user avatar, depending on oauth_type""" if oauth_type == 'facebook': return 'https://graph.facebook.com/{}/picture?type=square'.format( info['id']) elif oauth_type == 'google': return info.get('picture') re...
def calculate_Debye_frequency(sigma, eps_fluid): """ The Debye frequency is the inverse of the Debye layer charging time (Adjari, 2006). units: Hz Notes: Adjari, 2006 - minimum frequency the Debye layer can fully charge --> Any driving frequency should be well below this. In...
def to_dist(data): """ Probability distribution must sum to 1.0""" return [x / sum(data) for x in data]
def get_word(symbol, line, position): """Searches for the end of a literal. Args: symbol (str): The literal symbol that started the str. line (str): The line in which the symbol was found. position (int): The starting position of the literal symbol. Returns: str: The word f...
def tail(f, lines=10): """ Get the n last lines from file f """ if lines == 0: return "" BUFSIZ = 1024 f.seek(0, 2) bytes = f.tell() size = lines + 1 block = -1 data = [] while size > 0 and bytes > 0: if bytes - BUFSIZ > 0: # Seek back one whole BUFSIZ ...
def _str(val): """Ensure that the val is the default str() type for python2 or 3.""" if str == bytes: if isinstance(val, str): return val else: return str(val) else: if isinstance(val, str): return val else: return str(val, 'asc...
def _round_to_integer(x: float) -> int: """Utility function to round a float to integer, or 1 if it would be 0.""" assert x > 0 x = int(x) if x == 0: return 1 else: return x
def parse_genes(genes): """Parse various gene information including: 1. Species name (taxonomy name) 2. Entrez gene ID 3. Official symbol 4. RefSeq IDs 5. Offical full name Basically, just to go through the parsed xml data.... A big headache to figure it out... Return a list of dictio...
def dict_diff(old_one, new_one): """ diff two dict and fill the result """ result = {'created': [], 'deleted': [], 'modified': [], 'unchanged': []} old_dict = dict(old_one) new_dict = dict(new_one) for old_key, old_value in old_one.items(): for new_key, new_value in new_one.items()...
def sum_divisible_by(n: int, limit: int) -> int: """Computes the sum of all the multiples of n up to the given limit. :param n: Multiples of this value will be summed. :param limit: Limit of the values to sum (inclusive). :return: Sum of all the multiples of n up to the given limit. """ p = lim...
def get_last_usable_skill(skill_dict): """Return the last usable skill contained by the input dictionary. Args: skill_dict: an ordered dictionary with scox.value.Skill objects as values. Returns: the last usable skill in skill_dict. """ usable = [] for s in skill_dict.keys(): ...
def compute_arithmetic_mean(data): """ Calculate arithmetic mean value for a given byte array. In a truly random data blob the result of arithmetic mean should lay around value of 127.5. Keyword arguments: data -- data bytes """ return sum(data) / float(len(data))
def insert_charachter(mylist, charachter='&'): """ inserts a charachter element between each list element :param mylist: :param charachter: :return: """ n_insertion = len(mylist)-2 n = len(mylist) new_list = [] for i in range(n): for j in range(n_insertion): w =...
def isEven(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number %...
def trunc32( w ): """ Return the bottom 32 bits of w as a Python int. This may create a long temporarily, but returns an int. """ w = int( ( w & 0x7fffFFFF ) | ( - ( w & 0x80000000 ) ) ) assert type(w) == int return w
def survey(p): """ You do not need to understand this code. >>> survey(passphrase) '3d2eea56786a3d9e503a4c07dd667867ef3d92bfccd68b2aa0900ead' """ import hashlib return hashlib.sha224(p.encode('utf-8')).hexdigest()
def _parse_boundary_params(in_val, varname): """Parse boundary_discontinuity or pad parameters""" if isinstance(in_val, dict): try: is_valued = in_val[varname] except KeyError: # Set defaults is_valued = None else: is_valued = in_val return is_...
def absolute_error(fa, fn): """ calculates the relative error """ e = abs( fa - fn ) return e
def keywords_parser(keywords): """ EM : Converts the string input from the GUI to a list object of strings. """ # Remove spaces kwrds = keywords.replace(' ','') # Split at ',' to separate time windows, then keep non-empty words kwrds = [x for x in kwrds.split(',') if x] if kwrds: ...
def _GetGitKey(obj): """Hash the Git specification for the given RepoSync|RootSync object.""" repo = obj['spec']['git']['repo'] branch = 'main' if 'branch' in obj['spec']['git']: branch = obj['spec']['git']['branch'] directory = '.' if 'dir' in obj['spec']['git']: directory = obj['spec']['git']['dir...
def get_ip_ur(ur_number, offline_simulation=False): """ Function that gets the ip of the robot Args: ur_number: ID of robot (1,2 or 3) Returns: ip: string. """ subnet = '192.168.10.' if not offline_simulation: ip = subnet + str(ur_number + 9) else: ip = ...
def average_price(offers): """Returns the average price of a set of items. The first item is ignored as this is hopefully underpriced. The last item is ignored as it is often greatly overpriced. IMPORTANT: It is important to only trade items with are represented on the market in great numbers. ...
def findYDeltaFromDirection(direction): """ Returns delta Y for jumping, when given a direction value """ if direction in (8, 2): return 2 elif direction in (4, 6): return -2 else: error_template = "Unexpected direction value of: {0}" raise ValueError(error_template.forma...
def get_changed_params(new_space, last_space): """ Get changed param :param new_space: :param last_space: :return: """ # Empty last space if len(last_space.keys()) == 0: return new_space.keys() # end if # Changed params changed_params = list() # For each param i...
def tanh_grad(z): """ Tanh derivative. g'(z) = 1 - g^2(z). """ return 1 - z**2
def balance_samples(ls, key_func): """ Remove elements from ls so that number of elements for each key (extracted by key_func) is same for all keys. """ key_count = {} for entry in ls: k = key_func(entry) key_count[k] = key_count.get(k, 0) + 1 n_per_key = min(key_count.va...
def get_id_token(responses): """ Find the id_tokens issued, last one first in the list :param responses: A list of Response instance, text message tuples :return: list of IdTokens instances """ res = [] for resp, txt in responses: try: res.insert(0, resp["id_token"]) ...
def unitstep(t): """Returns the unit step function: ``u(t) = 1.0 if t>=0 else 0``""" return 1.0 if t >= 0 else 0.0
def get_vms_last_n_cpu_util(ceilo, vms, last_n_vm_cpu=1, integer=False): """Get last n cpu usage values for each vm in vms. :param ceilo: A Ceilo client. :type ceilo: * :param vms: A set of vms :type vms: list(str) :param last_n_vm_cpu: Number of last cpu values to recover :type last_n...
def list_strip_all_blank(list_item: list) -> list: """ Strips all items from a list which are '' or empty: :param list_item: The list object to be stripped of all empty values. :return list: A cleaned list object. """ _output = list() for _item in list_item: if _item and _item != ''...
def check_do_not_grow(particles): """ Test if all particles have grown fully """ do_not_grow = True for p in particles: do_not_grow = do_not_grow and p.do_not_grow return do_not_grow
def newton(number): """ Newton's method for square root """ x = number / 2 while True: y = (x + number / x) / 2 if y == x: return y x = y
def points_bounds(points): """Return bounding rect of 2D point list (as 4-tuple of min X, min Y, max X, max Y).""" min_x, min_y, max_x, max_y = ( points[0][0], points[0][1], points[0][0], points[0][1], ) for point in points[1:]: min_x = min(min_x, point[0]) ...
def sumValues(map: dict) -> int: """ Sums dict's values """ total: int = 0 for v in map.values(): total += v return total
def claims_match(value, claimspec): """ Implements matching according to section 5.5.1 of http://openid.net/specs/openid-connect-core-1_0.html The lack of value is not checked here. Also the text doesn't prohibit having both 'value' and 'values'. :param value: single value :param claimspec:...
def readFloat(f): """ Read a row from file, f, and return a list of floats. """ return list(map(float, f.readline().split()))
def _filter_vocab(vocab, min_fs): """Filter down the vocab based on rules in the vectorizers. :param vocab: `dict[Counter]`: A dict of vocabs. :param min_fs: `dict[int]: A dict of cutoffs. Note: Any key in the min_fs dict should appear in the vocab dict. :returns: `dict[dict]`: A dict of ...
def is_power_of_two(n): """ @brief Test if number is a power of two @return True|False """ return n != 0 and ((n & (n - 1)) == 0)
def populate_metadata(case, config): """ Provide some top level information for the summary """ return {"Type": "Summary", "Title": "Verification", "Headers": ["Bit for Bit", "Configurations", "Std. Out Files"]}
def get_switchport_config_commands(name, existing, proposed, module): """Gets commands required to config a given switchport interface """ proposed_mode = proposed.get("mode") existing_mode = existing.get("mode") commands = [] command = None if proposed_mode != existing_mode: if prop...
def number_compare(a, b): """Report on whether a>b, b>a, or b==a >>> number_compare(1, 1) 'Numbers are equal' >>> number_compare(-1, 1) 'Second is greater' >>> number_compare(1, -2) 'First is greater' """ retval = "" if (a == b): retval = 'Numb...
def binary_search(seq, target): """ :param seq: ascending sequence :param target: target num that in search :ret: index if found or None if not found """ head, tail = 0, len(seq) - 1 while head <= tail: # for cython, use # mid = head + ((tail - head) / 2) mid = (head ...
def speedup(i): """ Input: { samples1 - list of original empirical results samples2 - list of new empirical results (lower than original is better) (key1) - prefix for min/max/mean in return dict (key2) - prefix for min/max/mean in return dict ...
def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ result = [] for index in range(len(list1)): if list1[index] not in result: ...
def _hashSymOpList(symops): """Return hash value for a sequence of `SymOp` objects. The symops are sorted so the results is independent of symops order. Parameters ---------- symops : sequence The sequence of `SymOp` objects to be hashed Returns ------- int The hash va...
def searchInsertE(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ num=[i for i in nums if i<target] return len(num)
def schedule_parser(time_list: str) -> tuple: """ Module translate string-list of the hours/minutes to the tuple of the seconds. :arg string like "00:01; 03:51". ';' it`s separate between some delta-time. ':' it`s separate between hours (first) and minute (second). :return tuple like (60, 13...
def sort_by_announcement(courses): """ Sorts a list of courses by their announcement date. If the date is not available, sort them by their start date. """ # Sort courses by how far are they from they start day key = lambda course: course.sorting_score courses = sorted(courses, key=key) ...
def get_first_letter_frequency(words): """Add the frequency of first letters e.g. [C]at, [C]law, c = 2. Args: words (list): A list of words Returns: dict: The data and summary results. """ letters = {} # populate keys for name in words: letters[name[0]] = 0 # ad...
def tolist(x): """Convert a python object to a singleton list if not already a list""" if type(x) is list: return x else: return [x]
def get_parent_unit(xblock): """ Finds xblock's parent unit if it exists. To find an xblock's parent unit, we traverse up the xblock's family tree until we find an xblock whose parent is a sequential xblock, which guarantees that the xblock is a unit. The `get_parent()` call on both the xblock ...
def _best_permutation(grid): """ Given a square matrix of errors comparing actual value vs. expected value, finds the permutation which associates actual vs expected with the least error. Be careful running this on of large grids, as the runtime is expotential O(a^n). Sample run times on deskto...
def url_concat(*args: str) -> str: """ Joining arguments into a url Examples: >>> url_concat("https://example.com", "apitoken/", "/path_to_thing/", "file.exe") 'https://example.com/apitoken/path_to_thing/file.exe' Args: *args: str representing url paths Returns: url ...
def is_non_neg_int(val): """Check if value is non negative integer""" return isinstance(val, int) and val >= 0
def canonical_filetype(filetype: str): """Canonicalize an old-style file type (P4 older than 2000) to the new format. This should match the map of the file types in the docs. See: https://www.perforce.com/manuals/cmdref/Content/CmdRef/file.types.usage.html """ keyword_to_filetype = { "text":...
def get_extension(language): """ returns the extension of a given language. language: str low-level target language used in the conversion """ if language == "fortran": return "f90" else: raise ValueError("Only fortran is available")
def validate_cities(raw_cities: str) -> bool: """Returns True if given cities match 'city,city,...' pattern.""" for city in raw_cities.split(','): if not city.isalpha(): return False return True
def snake_to_camel(name: str) -> str: """ Change snake style name to camel style name. Parameters ---------- name : str Snake style name Returns ------- str Camel style name Examples -------- >>> from dtoolkit.util import snake_to_camel >>> snake_to_cam...
def is_up(host) -> bool: """ Check if a host is up and running. :param host: hostname :return: whether the host is reachable """ from os import system return True if system("ping -c 1 " + host + ' > /dev/null 2>&1') == 0 else False
def list_unique(hasDupes): """Return the sorted unique values from a list""" # order preserving from operator import itemgetter d = dict((x, i) for i, x in enumerate(hasDupes)) return [k for k, _ in sorted(d.items(), key=itemgetter(1))]
def convert_iobes_to_iob(row): """Convert IOBES tags into IOB in-place on the fly S-TAG => B-TAG E-TAG => I-TAG Relevant keys: TOKEN *NE-COARSE-LIT *NE-COARSE-METO *NE-FINE-LIT *NE-FINE-METO *NE-FINE-COMP *NE-NESTED NEL-LIT NEL-METO MISC """ s_tags = 0 e_tags = 0 for k in row: ...