content
stringlengths
42
6.51k
def messages_contains_prefix(prefix, messages): """ REturns true if any of the keys of message start with prefix. :param prefix: :param messages: :return: """ return any(map(lambda x: x.startswith(prefix), messages.keys()))
def is_prime(n): """ judege n is prime or not. :param n: a number :return: a boolean """ if n < 2: return False if n == 2: return True for m in range(2, int(n ** 0.5) + 1): if (n % m) == 0: return False else: return True
def from_ms(time: int) -> str: """ Convert millisconds into a string in format mm:ss.ms """ minute = time // 60_000 second = time // 1000 - minute * 60 millisecond = time - minute * 60_000 - second * 1000 if second < 10: second = "0" + str(second) else: second = str(se...
def square_digits(num): """Function takes an integer and returns an integer.""" temp = [int(x) ** 2 for x in list(str(num))] return int(''.join(map(str, temp)))
def package_name(s): """Validate a package name for argparse.""" if s[0] == '-': raise ValueError return s
def __get_windazimuth(winddirection): """Get an estimate wind azimuth using the winddirection string.""" if not winddirection: return None dirs = {'N': 0, 'NNO': 22.5, 'NO': 45, 'ONO': 67.5, 'O': 90, 'OZO': 112.5, 'ZO': 135, 'ZZO': 157.5, 'Z': 180, 'ZZW': 202.5, 'ZW': 225, '...
def get_position(row_index, col_index, board_size): """ (int, int, int) -> int Precondition: 0 < row_index <= board_size and 0 < col_index <= board_size and 1 <= board_size <= 9 Return the str_index of the cell in the string representation of the game board...
def subs_tvars(obj, params, argitems): """If obj is a generic alias, substitute type variables params with substitutions argitems. For example, if obj is list[T], params is (T, S), and argitems is (str, int), return list[str]. If obj doesn't have a __parameters__ attribute or that's not a non-empty tup...
def join_ingredients(ingredients_listlist): """Join multiple lists of ingredients with ' , '.""" return [' , '.join(i) for i in ingredients_listlist]
def filter_hostname(host: str): """Remove unused characters and split by address and port.""" host = host.replace('http://', '').replace('https://', '').replace('/', '') port = 443 if ':' in host: host, port = host.split(':') return host, port
def versiontuple(v): """utility for compare dot separate versions. Fills with zeros to proper number comparison""" filled = [] for point in v.split("."): filled.append(point.zfill(8)) return tuple(filled)
def pytest_make_parametrize_id(config, val, argname): """Pytest hook for user-friendly test name representation""" def get_dict_values(d): """Unwrap dictionary to get all values of nested dictionaries""" if isinstance(d, dict): for v in d.values(): yield from get_dic...
def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = "&><\"'" to_symbols = ("&" + s + ";" for s in "amp gt lt quot apos".split()) for from_, to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) re...
def safe(val): """Be careful """ if val is None: return None return float(val)
def if_init(net, name, dat_name, dat_layout, mode=None): """Return value for interface parameter / variable. Parameters: ----------- net : dict Complete network dictionary containing all nps, sps, plasts, ifs. name : str The unique string identifier for the interface. ident : in...
def camelcase_text(text: str): """Converts text that may be underscored into a camelcase format""" return text[0] + "".join(text.title().split('_'))[1:]
def keypad(coords): """ Takes a tuple of coordinates (x,y) and returns corresponding keypad number """ x = coords[0] y = coords[1] key = [ ["N", "N", 1, "N", "N"], ["N", 2, 3, 4, "N"], [5, 6, 7, 8, 9], ["N", "A", "B", "C", "N"], ["N", "N", "D", "N", "N"]] return key[x][y]
def generate_roman_number(n: int) -> str: """ Allowed roman numbers: IV, VI, IX, XI, XC, LC, XXXIX, XLI Disallowed: IIV, VIIII, XXXX, IXL, XIL """ if n > 4000: raise ValueError(f'Input too big: {n}') number_list = [ (1000, 'M'), (900, 'CM'), (500, 'D'), ...
def get_car_changing_properties(car): """ Gets cars properties that change during a trip :param car: car info in original system JSON-dict format :return: dict with keys mapped to common electric2go format """ return { 'lat': car['Lat'], 'lng': car['Lon'], 'address': car...
def binomial(n, k): """ Binomial coefficients, thanks to Andrew Dalke. """ if 0 <= k <= n: n_tok = 1 k_tok = 1 for t in range(1, min(k, n - k) + 1): n_tok *= n k_tok *= t n -= 1 return n_tok // k_tok else: return 0
def is_command(text: str) -> bool: """ Checks if `text` is a command. Telegram chat commands start with the '/' character. :param text: Text to check. :return: True if `text` is a command, else False. """ if text is None: return False return text.startswith('/')
def _slice_list(obj): """ Return list of all the slices. Example ------- >>> _slice_list((slice(1,2), slice(1,3), 2, slice(2,4), 8)) [slice(1, 2, None), slice(1, 3, None), slice(2, 3, None), slice(2, 4, None), slice(8, 9, None)] """ result = [] if not isinstance(obj, (tuple, list)):...
def inc_statement(revenue, cogs, sg_a, d_and_a, int_exp, tax, other_revenue = 0): """ Computes the main income statement items. Parameters ---------- revenue : int or float Revenue for the period cogs : int or float Cost of goods sold sg_a : int or float Selling, gen...
def list_to_string(inlist, endsep="and", addquote=False): """ This pretty-formats a list as string output, adding an optional alternative separator to the second to last entry. If `addquote` is `True`, the outgoing strings will be surrounded by quotes. Args: inlist (list): The list to print...
def vote_smart_state_filter(one_state): """ Filter down the complete dict from Vote Smart to just the fields we use locally :param one_state: :return: """ one_state_filtered = { 'stateId': one_state['stateId'], 'name': one_state['name'], } return one_state_filtered
def get_percentage(numerator, denominator, precision = 2): """ Return a percentage value with the specified precision. """ return round(float(numerator) / float(denominator) * 100, precision)
def _compute_metrics(tp, fp, fn): """Computes precision, recall and f1-score from count of TP, TN and FN. Args: tp (int): The number of true positives. fp (int): The number of false positives. fn (int): The number of false negatives. Returns: dict (str -> float)...
def convert_to_demisto_sensitivity(dg_classification: str) -> str: """ Convert dg_classification to demisto sensitivity :param dg_classification: :return: """ demisto_sensitivity = 'none' if dg_classification: if dg_classification[-3:] == 'ext': demisto_sensitivity = 'Cr...
def treat_category(category: str) -> str: """ Treats a list of string Args: category (str): the category of an url Returns: str: the category treated """ return category.lower().strip()
def BuildAdGroupCriterionOperations(adgroid, keywo): """Builds the operations adding a Keyword Criterion to each AdGroup. Args: adgroup_operations: a list containing the operations that will add AdGroups. number_of_keywords: an int defining the number of Keywords to be created. Returns: a li...
def args2dict(args): """ Transform string with arguments into dictionary with them. :param args: input string. :return: dictionary with parsed arguments """ arg_dict = {} for argument in args: key, value = argument.split('=') if value.startswith('\\'): arg_dict[k...
def getGlobalParams(config): """Try to parse out global parameters from the places it could be""" globalParams = None try: globalParams = config["GlobalParameters"] except (TypeError, LookupError): pass return globalParams
def low_dim_sim_keops_dist(x, a, b, squared=False): """ Smooth function from distances to low-dimensional simiarlity. Compatible with keops :param x: keops.LazyTensor pairwise distances :param a: float shape parameter a :param b: float shape parameter b :param squared: bool whether input distanc...
def _get_effect_strings(*args): """ Given *args[0], figure out which parameters should be printed. 'basic' = fundamental parameters of the model or effect described by args[0] 'additional' = any additional fundamental parameters (an extension of 'basic') 'alternate' = possible subst...
def _seed_npy_before_worker_init(worker_id, seed, worker_init_fn=None): """ Wrapper Function to wrap the existing worker_init_fn and seed numpy before calling the actual ``worker_init_fn`` Parameters ---------- worker_id : int the number of the worker seed : int32 the base s...
def check_accelerator(msgid, msgstr, line_warns): """check if accelrator &x is the same in both strings""" msgid = msgid.lower() msgstr = msgstr.lower() p1 = msgid.find('&') if p1 >= 0: a1 = msgid[p1:p1 + 2] p2 = msgstr.find('&') if p2 < 0 and len(a1) > 1: if a1[-1] in msgstr: # warn if ther...
def first_item_split_on_space(x): """ Brute force extract the first part of a string before a space. """ return str(x).split()[0]
def update_q(reward, gamma, alpha, oldQ, nextQ): """ Where nextQ is determined by the epsilon greedy choice that has already been made. """ newQ = oldQ + alpha * (reward + ((gamma*nextQ) - oldQ)) return newQ
def kind(n, ranks): """Return the first rank that this hand has exactly n of. Return None if there no n-of-a-kind in the hand.""" # Solution for r in ranks: if ranks.count(r) == n: return r return None # # Your code here. # n_of_kind = ranks[0:n] # if len(ran...
def first_and_last(a): """ Finds first and last elements in a list Args: a: the list Returns: The first and last elements in the list Raises: IndexError: if passed an empty list TypeError: if passed an object which is not a list """ if not isinstance(a, lis...
def probe_set_name_starts_with_one_of(gene_prefixes): """Returns a string that can be used with pandas.DataFrame.query""" return " | ".join( f"`Probe.Set.Name`.str.startswith('{prefix}', na=False)" for prefix in gene_prefixes )
def d_y_diffr_dx(x, y): """ derivative of d(y/r)/dx equivalent to second order derivatives dr_dxy :param x: :param y: :return: """ return -x*y / (x**2 + y**2)**(3/2.)
def generate_vm_name_str(vms): """ Generate a str with concatenation of given list of vm name """ # vms is a list of vm_name # example: vms=["vm1", "vm2"] # the return value is a string like this "vm1,vm2"" res = "" for vm in vms: # vm[0] is vm_uuid, vm has format (vm_uuid) res =...
def divided_and_show_pct(a, b): """ Two period of data change in pecentage (without %) """ return round((float(a) / float(b)) * 100, 2)
def problem3(number): """Prime Factorization""" i = 2 while i * i < number: while number % i == 0: number /= i i += 1 return int(number)
def ignore(*args): """ Calls function passed as argument zero and ignores any exceptions raised by it """ try: return args[0](*args[1:]) except Exception: pass
def class_names(obj): """Format class attribute value. :param obj: class names object :type obj: iterable or dict :returns: class attribute value :rtype: str """ try: class_items = obj.items() except AttributeError: class_list = obj else: class_list = (clas...
def str2bool(val): """ convert string to bool (used to pass arguments with argparse) """ dict = {'True': True, 'False': False, 'true': True, 'false': False, '1': True, '0': False} return dict[val]
def str_to_c2count(string): """ :param string: a str :return: a dict mapping from each one-character substring of the argument to the count of occurrences of that character """ count = {} for character in string: if character in count: count[character] += 1 else: ...
def _check_histogram(hist, value): """ Obtains a score of a value according to an histogram, between 0.0 and 1.0 """ i = 0 while i < len(hist[1]) and value > hist[1][i]: i += 1 if i == 0 or i == len(hist[1]): return 0.0 else: return hist[0][i - 1]
def _get_obj_id_from_binding(router_id, prefix): """Return the id part of the router-binding router-id field""" return router_id[len(prefix):]
def binary_search(arr, target): """ Searches for first occurance of the provided target in the given array. If target found then returns index of it, else None Time Complexity = O(log n) Space Complexity = O(1) """ first = 0; last = len(arr) - 1 while first <= last: # calculate m...
def ensure_bytes(s): """ Turn string or bytes to bytes >>> ensure_bytes(u'123') '123' >>> ensure_bytes('123') '123' >>> ensure_bytes(b'123') '123' """ if isinstance(s, bytes): return s if hasattr(s, 'encode'): return s.encode() msg = "Object %s is neither a b...
def ensureUtf(s, encoding='utf8'): """Converts input to unicode if necessary. If `s` is bytes, it will be decoded using the `encoding` parameters. This function is used for preprocessing /source/ and /filename/ arguments to the builtin function `compile`. """ # In Python2, str == bytes. # In...
def paperwork(n, m): """ Your classmates asked you to copy some paperwork for them. You know that there are 'n' classmates and the paperwork has 'm' pages. :param n: integer value. :param m: integer value. :return: calculate how many blank pages do you need. """ return 0 if n < 0 or m < ...
def nonalphanum_boundaries_re(regex): """Wrap regex to require non-alphanumeric characters on left and right.""" return rf"(?:^|[^a-zA-Z0-9])({regex})(?:[^a-zA-Z0-9]|$)"
def cli_table_to_recs(table_string): """Takes a table string (like that from a CLI command) and returns a list of records matching the header to values.""" lines = table_string.split('\n') # Take the first line as the header header_line = lines.pop(0).split() route_recs = [] for line ...
def append_entry(data, name, path): """Append an entry if it doesn't have it. Returns true if an entry was appened, false otherwise. """ found = False for entry in data: if path == entry[1]: found = True break if not found: data.append((name, path)) re...
def div_up(a, b): """Return the upper bound of a divide operation.""" return (a + b - 1) // b
def terms_of_order_n(n, p): """ Parameters ---------- n Order p Dimension of the problem (number of input pi number in the pyVPLM case) Returns The number of terms specifically at order n (not counting the ones below n) ------- """ if n == 0: return 1 if p ...
def build_written_line_entry(line_list): """ Remove start and end points from all line entries before writing to file. """ def _build_written_line_entry(coords): entry = \ { "geometry": { "coordinates": coords, ...
def getSize(picture): """Return the size of a given picture.""" return picture[0], picture[1]
def create_global_ctu_function_map(func_map_lines): """ Takes iterator of individual function maps and creates a global map keeping only unique names. We leave conflicting names out of CTU. A function map contains the id of a function (mangled name) and the originating source (the corresponding AST file...
def sort_dict(unsorted_dict, descending=False): """ Sorts a dictionary in ascending order (if descending = False) or descending order (if descending = True) """ if not isinstance(descending, bool): raise ValueError('`descending` must be a boolean') return sorted(unsorted_dict.items(), ...
def _repair_options(version, ks='', cf=None, sequential=True): """ Function for assembling appropriate repair CLI options, based on C* version, as defaults have changed. @param ks The keyspace to repair @param cf The table to repair @param sequential If the repair should be a sequential repair [...
def ordinal(n: int): """Utility function that gives the correct string ordinal given a number. For example, 1 gives 1st, 2 give 2nd, 14 gives 14th etc... From: https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement :param int n: integer that the user wants to convert to an ordinal string ...
def project_length_in_ns(projnum): """Returns a float with the project length in nanoseconds (ns)""" w = {} # 7 fragment hits w[14346] = 1.0 # RL w[14348] = 10.0 # L # 100 ligands w[14337] = 1.0 # RL w[14339] = 10.0 # L # 72 series for i in range(14600, 14613): ...
def format_list_items(items, format_string, *args, **kwargs): """ Apply formatting to each item in an iterable. Returns a list. Each item is made available in the format_string as the 'item' keyword argument. example usage: ['png','svg','pdf']|format_list_items('{0}. {item}', [1,2,3]) -> ['1. png', '2. ...
def row_major_gamma(idx, shape): """ As defined in 3.30 """ assert len(idx) == len(shape) if not idx: return 0 assert idx < shape return idx[-1] + (shape[-1] * row_major_gamma(idx[:-1], shape[:-1]))
def dict_to_str(props): """Returns the given dictionary as a string of space separated key/value pairs sorted by keys. """ ret = [] for k in sorted(props.keys()): ret += [k,props[k]] return " ".join(ret)
def encrypt(name, shift): """Encrypt a name using a Caesar cipher""" encrypted_name = "" for letter in name: if letter.isalpha(): encrypted_name += chr(ord(letter) + shift) else: encrypted_name += letter return encrypted_name
def is_invalid_dessert_key(dessert_key, dessert_json): """ Returns true if key is not blank or an empty string. :param dessert_key: :param dessert_json: :return: """ prefix = 'strIngredient' return str(dessert_key).startswith(prefix) and dessert_json[dessert_key] not in (' ', '')
def triple_step_combinations(step): """Find number of step combinations for maximum of three steps at a time :param step Number of steps left :return Number of step combinations """ if step < 0: return 0 elif step == 0: return 1 return triple_step_combinations(step - 3)...
def make_metadata_sos(): """ aux data for sos kernel """ return { "celltoolbar": "Create Assignment", "kernelspec": { "display_name": "SoS", "language": "sos", "name": "sos" }, "language_info": { "codemirror_mode": "sos", ...
def _get_output_filename(dataset_dir, split_name): """Creates the output filename. Args: dataset_dir: The dataset directory where the dataset is stored. split_name: The name of the train/test split. Returns: An absolute file path. """ return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name)
def bib_keys(config): """Return all citation keys.""" if "bib_data" not in config: return set() return {entry["ID"] for entry in config["bib_data"]}
def _stability_filter(concept, stability_thresh): """Criteria by which to filter concepts from the lattice""" # stabilities larger then stability_thresh keep_concept = \ concept[2] > stability_thresh[0]\ or concept[3] > stability_thresh[1] return keep_concept
def _py_list_pop(list_, i): """Overload of list_pop that executes a Python list append.""" if i is None: x = list_.pop() else: x = list_.pop(i) return list_, x
def sortMapping(streamPair): """ Sort mapping by complexity :param streamPair: :return: """ modifiedMapping = streamPair[5] possibleMapping = [] for x in modifiedMapping: modifiedMapping[x] = list(modifiedMapping[x]) modifiedMapping[x].sort(key=lambda x:x.__len__(), rever...
def break_by_minus1(idata): """helper for ``read_nsm_nx``""" i1 = 0 i = 0 i2 = None packs = [] for idatai in idata: #print('data[i:] = ', data[i:]) if idatai == -1: i2 = i packs.append((i1, i2)) i1 = i2 + 1 i += 1 contin...
def merge_dicts_by_key_and_value(*dict_args, max_turns=None): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = dict_args[0] for dictionary in dict_args[1:]: for sample_id, oracle_outputs_per_turn in di...
def showDifferences(seq1, seq2) : """Returns a string highligthing differences between seq1 and seq2: * Matches by '-' * Differences : 'A|T' * Exceeded length : '#' """ ret = [] for i in range(max(len(seq1), len(seq2))) : if i >= len(seq1) : c1 = '#' else : c1 = seq1[i] if i >= len(seq2) : ...
def get_instances_ids_and_names(instances): """ Get the instances IDs and names according to nodes dictionary Args: instances (list): Nodes dictionaries, returned by 'oc get node -o yaml' Returns: dict: The ID keys and the name values of the instances """ return { 'i-'...
def GetRecursionFunctor(depth): """Returns functor that unfolds recursion. Example: P_r0 := P_recursive_head(P_recursive: nil); P_r1 := P_recursive_head(P_recursive: P_r0); P_r2 := P_recursive_head(P_recursive: P_r1); P_r3 := P_recursive_head(P_recursive: P_r2); P := P_r3(); """ result_lines = ['P_r0...
def isTrue(value): """ Helper to check for string representation of a boolean True. """ return value.lower() in ('true', 'yes', '1')
def zip_dicts(dict_a, dict_b): """Zip the arrays associated with the keys in two dictionaries""" combined = {} combined.update(dict_a) combined.update(dict_b) zipped_vals = zip(*combined.values()) keys = list(combined.keys()) out = [] for i, zv in enumerate(zipped_vals): obj...
def victoire_diagonale(plateau, joueur): """ Teste si le plateau admet une victoire en diagonale pour le joueur. """ if (all(plateau[2 - i][i] == joueur for i in range(3)) or all(plateau[i][i] == joueur for i in range(3))): return True return False
def clamp(x, min_val, max_val): """ Clamp value between min_val and max_val """ return max(min(x,max_val),min_val)
def compute_deriv(poly): """ Computes and returns the derivative of a polynomial function. If the derivative is 0, returns (0.0,). Example: >>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x^4 + 3x^3 + 17.5x^2 - 13.39 >>> print compute_deriv(poly) # 4x^3 + 9x^2 + 35^x (0.0, 35.0, 9.0, 4...
def bufferParser(readbuffer, burst=16): """ Parse concatenated frames from a burst """ out = b'' offset = 1 while len(readbuffer) > 0: length = readbuffer[2] if readbuffer[4] == offset: out += readbuffer[5:3+length] offset += 1 readbuffer = readbuffe...
def library_path(hsm): """Provide a library_path property to the template if it exists""" try: return hsm.relation.plugin_data['library_path'] except Exception: return ''
def is_continuation(val): """Any subsequent byte is a continuation byte if the MSB is set.""" return val & 0b10000000 == 0b10000000
def file_hash(text): """ Removes the last updated ... line from html file and the data line from svg and then computes a hash. :param text: :return: """ text = text.split('\n') text = [t for t in text if not any(t.startswith(prefix) for prefix in (' This website is built ', ' <dc:date>')...
def hoop_pressure_thick(t, D_o, P_o, sig): """Return the internal pressure [Pa] that induces a stress, sig, in a thick walled pipe of thickness t - PD8010-2 Equation (5). :param float t: Wall thickness [m] :param float D_o: Outside diamter [m] :param float P_o: External pressure [Pa] :param flo...
def merge_dicts_lists(parent_dict, merge_dict): """ Function to add two dictionaries by adding lists of matching keys :param parent_dict: The Dict to which the second dict should be merged with :param merge_dict: Dict to be merge with the parent :return: Dict having the two inputs merged """ ...
def numeric_type(param): """ Checks parameter type True for float; int or null data; false otherwise :param param: input param to check """ if ((type(param) == float or type(param) == int or param == None)): return True return False
def overlap(document_tokens, target_length): """ pseudo-paginate a document by creating lists of tokens of length `target-length` that overlap at 50% return a list of `target_length`-length lists of tokens, overlapping by 50% representing all the tokens in the document """ overlapped = [] cursor ...
def collatz_len_fast(n, cache): """Slightly more clever way to find the collatz length. A dictionary is used as a cache of previous results, and since the dictionary passed in is mutable, our changes will reflect in the caller. """ if n == 1: return 1 if n in cache: return cache[n] if n % 2 ==...
def check_ratio_sum(ratio): """ Check the given ratio is valid or not. Sum of ratio should be 100 """ train_ratio = int(ratio[0]) val_ratio = int(ratio[1]) test_ratio = int(ratio[2]) qa_ratio = int(ratio[3]) total = train_ratio + test_ratio + val_ratio + qa_ratio if total != 100: raise ValueError("Sum of al...
def _re_word_boundary(r): """ Adds word boundary characters to the start and end of an expression to require that the match occur as a whole word, but do so respecting the fact that strings starting or ending with non-word characters will change word boundaries. """ # we can't use \b as it c...