content
stringlengths
42
6.51k
def nCkarray(*k_values): """Calculate nCk on a series of k values.""" result = 1 for i, j in enumerate((m for k in k_values for m in range(1, k+1)), 1): result = (result * i) // j return result
def mag_squared(x): """ Return the squared magnitude of ``x``. .. note:: If ``x`` is an uncertain number, the magnitude squared is returned as an uncertain real number, otherwise :func:``abs(x)**2`` is returned. """ try: return x._mag_squared() except ...
def url_param_dict_to_list(url_items_dict): """Turn this dictionary into a param list for the URL""" params_list = "" for key, value in url_items_dict: if key != "page": params_list += "&%s=%s" % (key, value) return params_list
def macAddressToString(mac, separator=':'): """ Converts a MAC address from bytes into a string. :param mac: bytes :param separator: str :return: str """ return separator.join('%02X' % b for b in mac)
def impact(data, impact): """Obtain impact metrics, prioritising CVSS3 if available. Args: data (dict): Empty CVE entry object created using createCVEEntry impact (dict): Impact Object parsed from NVD JSON Returns: dict: Data object with fields filled in using CVE Object """ ...
def parse_command(line): """Parse a command from line.""" args = [] kwargs = {} command, *parts = line.split(' ') for part in parts: if '=' in part: k, v = part.split('=') kwargs[k] = v else: args.append(part) return command, args, kwargs
def get_undo_pod(module, array): """Return Undo Pod or None""" try: return array.get_pod(module.params['name'] + '.undo-demote', pending_only=True) except Exception: return None
def cleanup(code): """Remove anything that is not a brainfuck command from a string.""" return ''.join( filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'], code))
def application_layer(data, parse = False): """Adds application layer header, return': test()s header. Uses telnet protocol """ if parse == False: return 'telnet' + '||' + data else: temp = data.split('||') print("Application Layer: " + str(temp[0])) ...
def pattern_to_regex(pattern): """Takes a string containing regular UNIX path wildcards and returns a string suitable for matching with regex.""" pattern = pattern.replace('.', r'\.') pattern = pattern.replace('?', r'.') pattern = pattern.replace('*', r'.*') if pattern.endswith('/'): ...
def _is_response(duck): """ Returns True if ``duck`` has the attributes of a Requests response instance that this module uses, otherwise False. """ return hasattr(duck, 'status_code') and hasattr(duck, 'reason')
def bani(registers, opcodes): """bani (bitwise AND immediate) stores into register C the result of the bitwise AND of register A and value B.""" test_result = registers[opcodes[1]] & opcodes[2] return test_result
def average_gateset_infidelity(model_a, model_b): """ Average model infidelity Parameters ---------- model_a : Model The first model. model_b : Model The second model. Returns ------- float """ # B is target model usually but must be "model_b" b/c of decora...
def generate_queries_union(uterance_vector): """ Performs a union of the current query with each of the previous turns separately uterance_vector - list, queries in the order they were made returns - list of queries in union """ if len(uterance_vector) > 1: generate_queries = [utterance ...
def get_flattened_qconfig_dict(qconfig_dict): """ flatten the global, object_type and module_name qconfig to the same qconfig_dict so that it can be used by propagate_qconfig_ function. "module_name_regex" is ignored for now since it's not supported in propagate_qconfig_, but it can be fixed later. ...
def check_new_str(methods, new_dict_def, new_dict_att, old_dict_def, old_dict_att): """ Check if there is new strategy produced by different method. :param methods: different meta-strategy solver. :param new_dict_def: defender's current str dict. :param new_dict_att: attacker's current str dict. ...
def mix(c1, c2, r=0.5): """ Mixes two colors """ def _mix(m1, m2): return m1 * r + m2 * (1-r) return tuple(map(lambda x: int(_mix(*x)), zip(c1, c2)))
def GetFirstWord(buff, sep=None):#{{{ """ Get the first word string delimited by the supplied separator """ try: return buff.split(sep, 1)[0] except IndexError: return ""
def value2str(value): """ format a parameter value to string to be inserted into a workflow Parameters ---------- value: bool, int, float, list Returns ------- str the string representation of the value """ if isinstance(value, bool): strval = str(value).low...
def stripString(inputString): """ imported from /astro/sos/da/scisoft/das/daLog/MakeDaDataCheckLogDefs.py """ delimString ="'" delimList = [] for index in range(len(inputString)): if inputString[index] == delimString: delimList.append(index) outFull = inputString[delimList[0]+1:...
def measurement_time_convert(time_parameter: str) -> str: """ Converts time to ISO 8601 standard: "20200614094518" -> "2020-06-14T09:45:18Z". Parameters: time_parameter (str): measurement time received via MQTT Returns: measurement time on ISO 8601 standard """ # Gets "202...
def _clean_header_str(value: bytes) -> str: """Null-terminates, strips, and removes trailing underscores.""" return value.split(b'\x00')[0].decode().strip().rstrip('_')
def hk_sp_enabled(bits: list) -> bytes: """ First bit should be on the left, bitfield is read from left to right """ enabled_bits = 0 bits.reverse() for i in range(len(bits)): enabled_bits |= bits[i] << i return enabled_bits.to_bytes(2, byteorder='big')
def displayCommands(data): """ Description : Read Command List and print out all Available functions/parameters """ cmds=list(data.keys()) for cmd in cmds: x=data[cmd] if type(x)==str: print(f"{cmd} : {x}") else: funcp=(next(iter(x))) ...
def eval_token(token): """Converts string token to int, float or str. """ if token.isnumeric(): return int(token) try: return float(token) except TypeError: return token
def get_books_by_years(start_year, end_year, books_list): """ Get a dictionary of books and their published based on a range of year Parameters: start_year: The lower bound of the search range. end_year: The upper bound of the search range. books_list: The list of books to search in Returns: bo...
def is_permutation(inputs): """Return True if strings in list are permutations of each other.""" if len(inputs) < 2: return False identity_of_inputs = set() for item in inputs: item = str(item) if len(item) < 2: return False item = sorted(list(item)) ...
def to_string(x, maxsize=None): """Convert given value to a string. Args: x (Any): The value to convert maxsize (int, optional): The maximum length of the string. Defaults to None. Raises: ValueError: String longer than specified maximum length. Returns: st...
def find_minimum(diff): """ Find unaccessed track which is at minimum distance from head """ index = -1 minimum = 999999999 for i in range(len(diff)): if (not diff[i][1] and minimum > diff[i][0]): minimum = diff[i][0] index = i return inde...
def _safe_decr(line_num): """ Return @line_num decremented by 1, if @line_num is non None, else None. """ if line_num is not None: return line_num - 1
def is_int_type_suspicious_score(confidence_score, params): """ determine if integer type confidence score is suspicious in reputation_params """ return params['override_confidence_score_suspicious_threshold'] and isinstance(confidence_score, int) and int( params['override_confidence_score_s...
def _structure_attachments_to_add(_attachment_count): """This function formats the JSON for the ``attachments_to_add`` field when updating existing messages. .. versionadded:: 2.8.0 :param _attachment_count: The number of attachments being added :type _attachment_count: int :returns: The properly ...
def adj_r2(r2, n, p): """ Calculates the adjusted R^2 regression metric Params: r2: The unadjusted r2 n: Number of data points p: number of features """ adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1) return adj_r2
def validate_strip_right_slash(value): """Strips the right slash""" if value: return None, value.rstrip("/") return None, value
def seg(h,m,s): """Pasa una cantidad de horas minutos y segundos solo a segundos""" h1 = h * 3600 m1 = m * 60 return h1 + m1 + s
def one_hot(length, current): """ Standard one hot encoding. >>> one_hot(length=3,current=1) [0, 1, 0] """ assert length > current assert current > -1 code = [0] * length code[current] = 1 return code
def newton_raphson( fp , fpp , xi , epsilon=1e-5 , max=100 ): """ newton_raphson( fp , fpp , xi , epsilon , max ). This is a root-finding method that finds the minimum of a function (f) using newton-raphson method. Parameters: fp (function): the first derivative of the function to minimize ...
def IsDisk( htypeText ): """Simple function to take morphological type code from Buta+2015 and determine if it refers to a disk galaxy (no Sm or Im) """ # simple way to get only proper disks: anything with "I" or "m" in text if (htypeText.find("I") >= 0) or (htypeText.find("m") >=0): return False else: return...
def collide ( ri, vi, rj, vj, box ): """Implements collision dynamics, updating the velocities.""" import numpy as np # The colliding pair (i,j) is assumed to be in contact already rij = ri - rj rij = rij - np.rint ( rij ) # Separation vector rij = rij * box # Now in sigma...
def vtoz(v,w,g,n): """ Calculates the dimensionless radius Input: v - Dimensionless velocity w - Ambient density power law index g - Adiabatic index n - Geometry (1 - plane, 2 - cylinderical, 3 - spherical) """ return (4.**(1./(2. + n - w))*((-1. + g)/(1. + g))**((-1. + g)/(2. - n + g*(-2. + \ w)))*(2. + n...
def StringToRawPercent(string): """Convert a string to a raw percentage value. Args: string: the percentage, with '%' on the end. Returns: A floating-point number, holding the percentage value. Raises: ValueError, if the string can't be read as a percentage. """ if len(string) <= 1: rais...
def parse_num_seq(string): """Convert the number sequence to list of numbers. Args: string (str): The input string to be parsed. Returns: list: A list of integer numbers. """ lst = [] g1 = string.strip().split(',') for rec in g1: rec = rec.strip() if '-' in...
def deparameterize(dataset): """Delete all variables and formulas from the dataset.""" if 'parameters' in dataset: dataset['parameters'] = [] for exc in dataset['exchanges']: for field in ('formula', 'variable'): if field in exc: del exc[field] if 'pro...
def type_name(value): """return pretty-printed string containing name of value's type""" cls = value.__class__ if cls.__module__ and cls.__module__ not in ["__builtin__", "builtins"]: return "%s.%s" % (cls.__module__, cls.__name__) elif value is None: return 'None' else: retu...
def all_keys_true(d, keys): """Check for values set to True in a dict""" if isinstance(keys, str): keys = (keys,) for k in keys: if d.get(k, None) is not True: return False return True
def nu_factor(nu, nu_pivot, alpha): """ Frequency rescaling factor, depending on the spectral index. Parameters ---------- nu : frequency [GHz] nu_pivot : pivot (i.e. reference) frequency [GHz] alpha : spectral index """ return (nu/nu_pivot)**-alpha
def tarjan(nodes, edge_functor): """ Returns a set of "Starting" non terminals which have atleast one production containing left recursion. """ def strongconnect(currNode, index, indexes, lowlink, stack): indexes[currNode] = index lowlink[currNode] = index index = index + 1 ...
def new_polygon(biggon, ratio): """ Given a polygon (biggon), this function returns the coordinates of the smaller polygon whose corners split the edges of the biggon by the given ratio. """ smallgon = [] L = len(biggon) for i in range(L): new_vertex = (biggon[i][0] *ratio +...
def rgba2hex(rgba): """ Convert rgba tuple (e.g. (0.5, 0.4, 0.2, 1.0)) to hex code """ hx = '' for f in rgba[:3]: s = hex(int(f*255))[2:] if len(s)<2: s = '0'+s hx += s return "#"+hx
def isnumber(x): """Is x a number?""" return hasattr(x, '__int__')
def ipAddrToDecimal(ipAddrStr: str) -> int: """ Convert IP address string to number. """ if ":" in ipAddrStr: """ IPv6 """ pos = ipAddrStr.find("/") if pos >= 0: ipv6AddrStr = ipAddrStr[:pos] else: ipv6AddrStr = ipAddrStr h...
def verMod11(cprNumbStr): """Perform modulus 11 check for validity of CPR-number. Input: cprNumbStr, str[10], holds a full CPR number Output: True/False, logical, returns failure or succes of check """ if len(cprNumbStr) != 10: raise ValueError("CPR-number to be va...
def unique(values): """Returns list of unique entries in values.""" unique = [] for value in values: if not value in unique: unique.append(value) return unique
def select_utxo(utxos, sum): """Return a list of utxo sum up to the specified amount. Args: utxos: A list of dict with following format. [{ txid: '' value: 0, vout: 0, scriptPubKey: '', ...
def max_sequence_length_from_log(log): """ Returns length of the longest sequence in the event log. :param log: event log. :return: max_seq_length. """ max_seq_length = 0 for sequence in log: max_seq_length_temp = 0 for activity_ in sequence: max_seq_length_temp...
def insert_interval(intervals, new_interval): """Return a mutually exclusive list of intervals after inserting new_interval Params: intervals: List(Intervals) new_interval: Interval Return: List(Interval) """ length = len(intervals) if length < 1: return [new_in...
def total_intersection_size(fabric_cuts): """ Determine the total size of the intersection of a list of fabric cuts. :param fabric_cuts: the list of fabric cuts :return: the total size of the intersection >>> fabric_cuts = [FabricCut('#1 @ 1,3: 4x4'), FabricCut('#2 @ 3,1: 4x4'), FabricCut('#3 @ 5,5...
def pade_21_lsq(params, k, ksq, lmbda, sigma): """ model to fit f(k[i]) to lmbda[i] ksq = k**2 is computed only once params: [lambda0, alpha, beta] returns model(k) - lbs For details see DOI: 10.1140/epjd/e2016-70133-6 """ l0, a, b = params A, B = a**2, b**2 TA = 2*A A2B = A*...
def str_dist(new, original, lowerize=True): """Measures difference between two strings""" if lowerize: new = new.lower() original = original.lower() len_diff = abs(len(new) - len(original)) length = min(len(new), len(original)) for i in range(length): len_diff += not(new[i] =...
def unlist(value): """ If given value is a list, it returns the first list entry, otherwise it returns the value. """ return value[0] if isinstance(value, list) else value
def get_mention(user): """ Formateo para las menciones. """ return '<@{user}>'.format(user=user)
def single_letter_count(word, letter): """How many times does letter appear in word (case-insensitively)? """ return word.count(letter)
def func_name(x, short=False): """Return function name of `x` (if defined) else the `type(x)`. If short is True and there is a shorter alias for the result, return the alias. Examples ======== >>> from sympy.utilities.misc import func_name >>> from sympy import Matrix >>> from sympy.ab...
def count_unique (items): """This takes a list and returns a sorted list of tuples with a count of each unique item in the list. Example 1: count_unique(['a','b','c','a','c','c','a','c','c']) returns: [(5,'c'), (3,'a'), (1,'b')] Example 2 -- get the most frequent item in a list: ...
def str2bool(v): """ Convert a string into a boolean """ return v and str(v.lower()) == "true"
def update_parameters(params, grads, alpha): """ Updates model parameters using gradient descent. Arguments: params -- dictionary containing model parameters grads -- dictionary with gradients, output of L_model_backward() Returns: params -- dictionary with updated parameters ...
def validate_project_element_name(name, isdir=False): """"Validate name for a test, page or suite (or folders). `name` must be a relative dot path from the base element folder. """ errors = [] parts = name.split('.') last_part = parts.pop() for part in parts: if len(part) == 0: ...
def sum(arg): """ sum() takes an iterable (a list, tuple, or set) and adds the values together: """ total = 0 for val in arg: total += val return total
def init_field(height=20, width=20): """Creates a field by filling a nested list with zeros.""" field = [] for y in range(height): row = [] for x in range(width): row.append(0) field.append(row) return field
def words_to_word_ids(data=[], word_to_id={}, unk_key = 'UNK'): """Given a context (words) in list format and the vocabulary, Returns a list of IDs to represent the context. Parameters ---------- data : a list of string or byte the context in list format word_to_id : a dictionary ...
def _get_linkage_function(linkage): """ >>> "f_linkage" in str(_get_linkage_function(0.5)) True >>> "i_linkage" in str(_get_linkage_function(2)) True >>> any is _get_linkage_function('single') True >>> all is _get_linkage_function('complete') True >>> ff = _get_linkage_function(0...
def msg_get_hw_id(raw_json): """ extract hardware ID from JSON """ return raw_json['hardware_serial']
def custom_metric(metric_type): """Generate custom metric name. :param metric_type: name of the metric. :type metric_type: str :returns: Stacdriver Monitoring custome metric name. :rtype: str """ return "custom.googleapis.com/{}".format(metric_type)
def checkForUppercase(alphabet): """This method takes specified alphabet and checks if it supports upper case. Args: alphabet (list): List of chars from specified alphabet. Returns: bool: True if alphabet supports upper case, otherwise False. """ for char in alphabet: if c...
def perpetuity(A, r): """ A = annual payment r = discount rate returns present value """ return(A/r)
def flatten_list_of_lists(some_list, remove_duplicates=False, sort=False): """ Convert a list of lists into a list of all values :param some_list: a list such that each value is a list :type some_list: list :param remove_duplicates: if True, return a unique list, otherwise keep duplicated values ...
def is_position_valid(position, password): """Check if position is valid for password.""" return 0 <= position < len(password) and password[position] is None
def is_in(elt, seq): """Similar to (elt in seq), but compares with 'is', not '=='.""" return any(x is elt for x in seq)
def valid_blockname(name): """Tests if a 5-character string is a valid blockname. Allows names with the first three characters either letters, numbers, spaces or punctuation, the fourth character a digit or a space and the last character a digit. """ from string import ascii_letters, digits, pu...
def kumaraswamy(a,b,x): """ CDF of the Kumaraswamy distribution """ return 1.0-(1.0-x**a)**b
def metrics2str(mean_scores: dict, scores: dict, labels: list): """ Converts given metrics to a string for display """ metric_keys = list(scores.keys()) mean_keys = list(mean_scores.keys()) # output format out_str = "" for mean_metrics, metric in zip(mean_keys, metric_keys): out...
def numara_aparitii(opt, patt, repw, teorema): """Contorizeaza, modifica teorema, retine aparitiile.""" contor = 0 i = 0 copie = str(teorema) linii = [] liniecurenta = 0 inceplinie = 0 while i+len(patt) <= len(copie): turn = 0 if copie[i] == '\n': liniecurenta...
def flatten(lol): """ See http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python e.g. [['image00', 'image01'], ['image10'], []] -> ['image00', 'image01', 'image10'] """ import itertools chain = list(itertools.chain(*lol)) return chain
def rev_grey_code(g): """ Decode grey code : Enter a number @g, return the vaule before encode to grey code. """ n = 0 while g: n ^= g g >>= 1 return n
def efficientnet_params(model_name): """Get efficientnet params based on model name.""" params_dict = { # (width_coefficient, depth_coefficient, resolution, dropout_rate) 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, 0.3)...
def rivers_with_station(stations): """Returns a set with the names of rivers that have a monitoring station """ rivers = set() for station in stations: if station.river != None: rivers.add(station.river) return rivers
def random_map(nmers, vocabulary): """ Totally random map, totally unconstrained, totally boring. """ forward_mapping = dict(zip(nmers, vocabulary)) backward_mapping = dict(zip(vocabulary, nmers)) return forward_mapping, backward_mapping
def stations_by_river(stations): """This function returns a dictionary that maps river names to a list of stations on that river""" rivers = {} for station in stations: river = station.river if river not in rivers: rivers[river] = [] rivers[river].append(stati...
def get_trig_val(abs_val: int, max_unit: int, abs_limit: int) -> int: """Get the corresponding trigger value to a specific limit. This evenly devides the value so that the more you press the trigger, the higher the output value. abs_val - The current trigger value max_unit - The maximum value to re...
def op_encode(opcode, pads, operand): """encode a lut instruction code""" return ((opcode & 0x3f) << 10) | ((pads & 0x3) << 8) | (operand & 0xff)
def task5(b: float) -> str: """ Function that calculates area of an equilateral triangle. Suare root of 3 is 1.732. It returns the area as string that has two numbers after comma. Input: N -> float number Output: area of triangle as string such as: "1.23" """ pole = (1.732/2) * b ** 2 p...
def bytesto(bytes, to, bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 } r = float(bytes) for i in rang...
def q_max_ntu(c_min, temp_hot_in, temp_cold_in): """Computes the maximum q value for the NTU method Args: c_min (int, float): minimum C value for NTU calculations. temp_hot_in (int, float): Hot side inlet temeprature. temp_cold_in (int, float): Cold side inlet temeprature. ...
def db_to_linear_gain(db_value): """ Parameters ---------- db_value : float Decibel value Examples -------- >>> db_to_linear_gain(db_value=-3) 0.5011872336272722 >>> db_to_linear_gain(db_value=10) 10.0 """ return 10 ** (db_value / 10)
def old_filter_nodes(nodes_list, ids=None, subtree=True): """Filters the contents of a nodes_list. If any of the nodes is in the ids list, the rest of nodes are removed. If none is in the ids list we include or exclude the nodes depending on the subtree flag. """ if not nodes_list: re...
def collapse(board_u): """ takes a row/column of the board and collapses it to the left """ i = 1 limit = 0 while i < 4: if board_u[i]==0: i += 1 continue up_index = i-1 curr_index = i while up_index>=0 and board_u[up_index]==0: ...
def check_8_v1(oe_repos, srcoe_repos): """ All repositories' must have protected_branches """ print("All repositories' must have protected_branches") errors_found = 0 for repos, prefix in [(oe_repos, "openeuler/"), (srcoe_repos, "src-openeuler/")]: for repo in repos: branch...
def _handle_string(val): """ Replace Comments: and any newline found. Input is a cell of type 'string'. """ return val.replace('Comments: ', '').replace('\r\n', ' ')
def array_to_concatenated_string(array): """DO NOT MODIFY THIS FUNCTION. Turns an array of integers into a concatenated string of integers separated by commas. (Inverse of concatenated_string_to_array). """ return ",".join(str(x) for x in array)
def increment_year_month(year, month): """Add one month to the received year/month.""" month += 1 if month == 13: year += 1 month = 1 return year, month