content
stringlengths
42
6.51k
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode("ascii") return True...
def mean(num_lst): """ Calculate the mean of a list of numbers Parameters ---------- num_lst : list The list to take the average of Returns ------- ret: float The mean of a list Examples -------- >>> mean([1,2,3,4,5]) 3.0 """ # check that user apsses list if not isinstance(num_lst, li...
def s2b(s): """ naive string-to-boolean converter helper """ if s.lower() in ["true", "1", "yes", "enabled", "on"]: return True return False
def weighter(folders: list) -> dict: """ Returns the proportionality coefficients of the sizes of the folders. The largest one's weight is set on 1. """ maximum = max(folders) class_weight = {} for i, el in enumerate(folders): class_weight[i] = float(maximum) / float(el) return class...
def intersection(L1, L2): """ from https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines """ D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * L2[2] - L1[2] * L2[0] if D != 0: x = Dx / D y = Dy / D r...
def _add_eq_menus(srx): """ (PRIVATE) Construct the part of EQ_MENUs in the base url. Input must be srx. """ if type(srx) == str: srx = srx.strip().split(',') params = "&EQ_MENU={}".format(srx[0]) if len(srx) > 1: for i in range(1, len(srx)): params += "&EQ_MENU{}={}"...
def _normalize_dictionary(dictionary): """Wraps every value of dictionary in a list if it isn't one already.""" for key, value in dictionary.items(): if type(value) != type([]): dictionary[key] = [value] return dictionary
def int_or_none(value): """Casts to integer if the value is not None """ if value is not None: return int(value) return None
def is_number(a_string: str) -> bool: """Checks if string represents an int or float. Supports leading/trailing whitespaces, scientific notation. Reference: https://stackoverflow.com/a/23639915/8116031 :param a_string: a string :return: True if string represents int or float, False otherwise. """ ...
def bitstr(n, width=None): """Return the binary representation of n as a string and optionally zero-fill (pad) it to a given length ex: >>> bitstr(123) >>> '1111011' """ result = list() while n: result.append(str(n % 2)) n = int(n / 2) if (width is not None) a...
def unique_list(values): """ Remove all duplicate chars in a list :param values: :return: """ exists = set() return [v for v in values if v not in exists and not exists.add(v)]
def list_descendant(input_list): """Function that orders a list on descendant order using insertion sort Args: input_list ([type]): List with the values that we want to order Returns: list: The ordered list """ for i in range(1, len(input_list)): j = i-1 next_elemen...
def merge(xs, ys): """ Merges two sorted sequences of numbers into one sorted sequence. """ zs = [] i = 0 j = 0 for k in range(len(xs) + len(ys)): if j >= len(ys) or i < len(xs) and xs[i] <= ys[j]: zs.append(xs[i]) i += 1 else: zs.append(ys...
def is_sg_rule_subset(sgr1, sgr2): """ determine if security group rule sgr1 is a strict subset of sgr2 """ all_protocols = set(range(256)) sgr1_protocols = {sgr1['protocol']} if 'protocol' in sgr1 else \ all_protocols sgr2_protocols = {sgr2['protocol']} if 'protocol' in sgr2 else \ ...
def sample_param(sample_dict): """sample a value (hyperparameter) from the instruction in the sample dict: { "sample": "range | list", "from": [min, max, step] | [v0, v1, v2 etc.] } if range, as np.arange is used, "from" MUST be a list, but may contain only 1 (=min) or 2 (min and...
def bpm_to_mspt(bpm, res=480): """ Coverts an integer value of beats per minute to miliseconds per quarter note """ return 60000 / res / bpm
def cumulative_sma(bar, series, prevma): """ Returns the cumulative or unweighted simple moving average. Avoids sum of series per call. Keyword arguments: bar -- current index or location of the value in the series series -- list or tuple of data to average ...
def _step_id(step): """Return the 'ID' of a deploy step. The ID is a string, <interface>.<step>. :param step: the step dictionary. :return: the step's ID string. """ return '.'.join([step['interface'], step['step']])
def vcolor(data, pattern): """ Color a graph line by line :param data: the data :type data: list of tuples (info, value) :param pattern: list of colors, this list defines the pattern to color each line of the graph. :type pattern: list of 'colors' (str) :return: the colored graph :rty...
def upgradeDriverCfg(version, dValue={}, dOption=[]): """Upgrade the config given by the dict dValue and dict dOption to the latest version.""" # the dQuantUpdate dict contains rules for replacing missing quantities dQuantReplace = {} # update quantities depending on version if version == '1.0':...
def _get_column_index(rows, column_id): """ Internal function that return column index for column_id. """ headers = rows[0] if column_id in headers: return headers.index(column_id) else: return None # add an exeption if not found?
def make_formal_args(members): """Comma-separated type name pair used in formal arguments int i, char j """ return ", ".join("{} {}".format(type.as_argument, name) for type, name in members)
def search(x, y, grid): """ Tests for connecivity between cell (x,y) and the end cell in a given grid """ if grid[x][y] == 2: return True if grid[x][y] == 1: return False if grid[x][y] == 3: return False # mark as visited grid[x][y] = 3 # explore neighbor...
def no_rbac_suffix_in_test_filename(filename): """Check that RBAC filenames end with "_rbac" suffix. P101 """ if "patrole_tempest_plugin/tests/api" in filename: if filename.endswith('rbac_base.py'): return if not filename.endswith('_rbac.py'): return 0, "RBAC t...
def pi_list_to_str(pi_list): """ Parameters ---------- pi_list List of pi expression Returns A string representation ------- """ wrt = "" if len(pi_list) > 0: for eq in pi_list: wrt += eq + "\n" return wrt[:-1] return "None"
def multi_replace(string, old=[], new=[]): """ Replace multiple strings at once :param string: :param old: :param new: :return: """ if type(new) is str: new = [new] if type(old) is str: old = [old] if len(new) == 1: new = new * len(old) for i, j in zi...
def get_case_group_status_by_collection_exercise(case_groups, collection_exercise_id): """ Gets the response status of a case for a collection exercise :param case_groups: A list of case_groups :type case_groups: list :param collection_exercise_id: A collection exercise uuid :type collection_ex...
def calculate_proportions(proportionList, value, roundValue=3): """ Calculate proportion of a value according to the list of number as weight @param proportionList: List of number eg [3,2] @param value: The value that needs to be proportioned eg 10 @param roundValue: What value should it rounded off...
def getEdgesBetweenThem(nodes,edges): """return all edges which are coming from one of the nodes to out of these nodes""" edg = set([]) for (n1,n2) in edges: if (n1 in nodes and n2 in nodes): edg.add((n1,n2)) return edg
def B(s): """string to byte-string in Python 2 (including old versions that don't support b"") and Python 3""" if type(s)==type(u""): return s.encode('utf-8') # Python 3 return s
def eliminate_prefix(u, v): """ If v = uw (u=prefix, w=suffix), w = u-1 v Returns suffix after eliminating prefix :param str: An input word / sub-word :return inv_str: An inversed string """ w = u.lstrip(v) return(w)
def validate(params): """validates the correctness of the parameter dictionary. :params: the parameter dictionary, that is read from a yaml file. :returns: a boolean value. True if all parameters are set and are in their limits, False otherwise. """ # greater or equal 0 gezero = ["weight",...
def time2sec(timestr): """ Conver time specs to seconds """ if timestr[-1] == "s": return int(timestr[0:-1]) elif timestr[-1] == "m": return int(timestr[0:-1]) * 60 elif timestr[-1] == "h": return int(timestr[0:-1]) * 60 * 60 else: return int(timestr)
def serialise_ctx(ctx): """ Convert context to serialisable list """ ctx_list = [] if type(ctx) is not list: ctx = [ctx] for c in ctx: ctx_list.append((c.device_id, c.device_typeid)) return ctx_list
def nested_map(f, *args): """ Recursively transpose a nested structure of tuples, lists, and dicts """ assert len(args) > 0, 'Must have at least one argument.' arg = args[0] if isinstance(arg, tuple) or isinstance(arg, list): return [nested_map(f, *a) for a in zip(*args)] elif isinstance(ar...
def multi_replace(s, replace_from, replace_to=''): """A function like str.replace() with multiple replacements. ``replace_from`` is a list of things you want to replace. Ex: ['a','bc','d'] ``replace_to`` is a list of what you want to replace to. If ``replace_to`` is a list and has the same length as ``...
def sec2days(seconds): """Converst seconds to days.""" return seconds / (60.0**2 * 24.0)
def as_scalar(val): """ If val is iterable, this function returns the first entry else returns val. Handles strings as scalars :param val: A scalar or iterable :return: """ # Check string if val == str(val): return val try: # Check iterable it = iter(val) # ...
def make_valid_latex_string(s: str) -> str: """ Take a string and make it a valid latex math string by wrapping it with "$"" when necessary. Of course, strings are only wrapped with the "$" if they are not already present. Args: s: The input string. Returns: The properly formatted stri...
def get_list_uniques(_list): """ This function returns the unique/s value/s of a given list. :param _list: List :return: List containing unique values. """ ret = [] for it in _list: if it not in ret: ret.append(it) return ret
def average_tol_try_except(values, tolerance): """Compute the mean of values where value is > tolerance :param values: Range of values to compute average over :param tolerance: Only values greater than tolerance will be considered """ total = 0.0 count = 0 for row in values: for val...
def convert_literal(literal): """Convert JSON literals to Python ones.""" # Map for the literals map_ = { "true": True, "false": False, "null": None } # Check if literal is in string format if type(literal) == str: # Check if the literal is valid if litera...
def calc_propositions(word_list): """ Returns the number of propositions in the given list of words. """ props = 0 for word in word_list: if word.isprop: props += 1 return props
def sort_by_points(hn_list): """Sorts the given list of dictionaries by the score category.""" # Reversed so that the list is in descending order return sorted(hn_list, key=lambda x: x["score"], reverse=True)
def count_probes(probes): """ Counts the amount of probes in probes array :param probes: array of probes :return: float count """ count = 0 for n in probes: count += n return float(count)
def only_letter(s: str) -> str: """Filter out letters in the string.""" return ''.join([c for c in s if c.isalpha()])
def load_samples(sample_file_paths): """Read in processed sample files, returning flat list.""" samples = [] for sample_file_path in sample_file_paths: with open(sample_file_path, "r") as sample_file: for sample in sample_file: sample = sample.strip() samp...
def extract_active_ids(group_status): """Extracts all server IDs from a scaling group's status report. :param dict group_status: The successful result from ``get_scaling_group_state``. :result: A list of server IDs known to the scaling group. """ return [obj['id'] for obj in group_status['g...
def data_dict(data, data_net): """Return timeline dict parameter.""" return { "Primary": { "data": data, "time_column": "TimeGenerated", "source_columns": ["Computer", "NewProcessName"], "color": "navy", }, "Secondary": { "data"...
def combin(n, k): """Nombre de combinaisons de n objets pris k a k""" if k > n//2: k = n-k x = 1 y = 1 i = n-k+1 while i <= n: x = (x*i)//y y += 1 i += 1 return x
def _make_divisible(v, divisor, min_value=None): """ Adapted from torchvision.models.mobilenet._make_divisible. """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. ...
def _create_statement(name, colnames): """create table if not exists foo (...) Note: Every type is numeric. Table name and column names are all lower cased """ schema = ', '.join([col.lower() + ' ' + 'numeric' for col in colnames]) return "create table if not exists %s (%s)" % (name...
def select_keys(records, keys): """Filter the records extracting only the selected fields. Args: records (list(dict)): the list of dicts to be filtered. keys (list(str)): the keys to select from the records. Returns: list(dict): the list of records containing only the specified key...
def parse_kv_pair(pair): """ Parse a single key/value pair separated by = and return the key and value components. Assumes that the key component does not include = which is valid for CIM names. If the value component is empty, returns value None """ name, value = pair.partition("=")[::2] ...
def nextmonth(yr, mo): """get next month from yr/mo pair""" return (yr+mo / 12, mo % 12+1)
def sort_frequency_table(freq_table): """Sort a frequency table by its values Ref: https://docs.python.org/3/howto/sorting.html """ sort_result = sorted(freq_table.items(), key=lambda filetypes: filetypes[1], reverse=True) return {key: value for key...
def permute(v): """ permute 16 bits values (Vol 6, Part B, 4.5.8.3.2) """ b0 = int(bin((v&0xff00)>>8)[2:].rjust(8,'0')[::-1], 2) b1 = int(bin((v&0x00ff))[2:].rjust(8,'0')[::-1], 2) return (b0<<8) | b1
def face(self, channel, nick, host, *args): """you need help with your face?""" if args: args = ' '.join(args).split('+') name = args[0].strip() if len(args) > 1: madeof = ' and '.join(x.strip() for x in args[1:]) return "hahaha %s's face is made of %s" % (name, m...
def get_outdir_simupara(fp, line): """ get output directory and simulation parameters (in format: time steps) :param fp: opened file :param line: current line :return: output directory and simulation parameters Note: output directory is '' if not specified and list of simulation parameters...
def package_name_from_repo(repository): """ Owner and project from repository. >>> package_name_from_repo('https://github.com/NoRedInk/noredink.git') ('NoRedInk', 'noredink') """ repo_without_domain = repository.split('https://github.com/')[1].split('.git')[0] (owner, project) = repo_witho...
def get_monitoring_status(proxy): """Return status page for monitoring""" return {"status": "200", "message": "OK"}
def num2nwc(x: int) -> str: """ Convers Number to NumComma """ return "{:,}".format(int(x))
def to_integer(obj): """ Converts `obj` to an integer. Args: obj (str|int|float): Object to convert. Returns: int: Converted integer or ``0`` if it can't be converted. Example: >>> to_integer(3.2) 3 >>> to_integer('3.2') 3 >>> to_integer('3...
def get_canonical_encoding_name(name): # type: (str) -> str """ Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str """ import codecs try: codec = ...
def inverse_BERV(w1, Berv): """Obtain un-BERV corrected wavelengths.""" c = 299792.458 # km/s return w1 * (1 - Berv / c)
def convert_celcius_to_farenheit(temp): """Convert the temperature from Celcius to Farenheit scale. :param float temp: The temperature in degrees Celcius. :returns: The temperature in degrees Farenheit. :rtype: float """ return ((temp * 9) / 5) + 32
def computeChecksum(algo, filePath): """Compute digest of ``filePath`` using ``algo``. Supported hashing algorithms are SHA256, SHA512, and MD5. It internally reads the file by chunk of 8192 bytes. :raises ValueError: if algo is unknown. :raises IOError: if filePath does not exist. """ import hashlib ...
def replace(xs, base, replacement): """Replaces every 'base' in 'xs' with 'replacement'. Non destructive. Args: xs: Initial list of elements. base: Element to be replaced in the new list. replacement: Element to replace that value with. Returns: A new list with the replaceme...
def atoi(text): """ Checks if the file names contain numbers. Parameters ---------- text This parameter could be a str or int. Returns ------- flow : int, str """ flow = int(text) if text.isdigit() else text return flow
def getUpdateTime(monster): """Retourne le temps auquel les monstres doivent bouger""" return monster["updateTime"]
def highest_weight(edges): """ Get edges based on highest weight first """ return list(reversed(sorted(edges, key=lambda data: data[2]["weight"])))
def extract_hashtags(text, tags_to_append=[]): """Extracts distinct sorted hashtag collection from a string, complemented with tags_to_append items.""" return sorted(set([item.strip("#.,-\"\'&*^!") for item in text.split() if (item.startswith("#") and len(item) < 256)] + tags_to_append))
def extract(input_data: str) -> tuple: """take input data and return the appropriate data structure""" rules = dict() messages = list() rules_input, messages_input = input_data.split('\n\n')[0:2] for rule_input in rules_input.split('\n'): rule_id, rule = rule_input.split(': ') rules...
def read(trace_variables_contents: list) -> list: """Read the list of trace variables to be extracted from xtv/dmx file :param vars_filename: (str) the list of TRACE graphic variables to be extracted, fullname :returns: (list) the list of TRACE graphic variables in string """ vars_list = li...
def average(iterable): """ Gives the average of the values in the provided iterable. """ return sum(iterable) / max(len(iterable), 1)
def _get_umbrella_header_declaration(basename): """Returns the module map line that references an umbrella header. Args: basename: The basename of the umbrella header file to be referenced in the module map. Returns: The module map line that references the umbrella header. """ return 'umbrell...
def in_between(one_number, two_numbers): """(int,list) => bool Return true if a number is in between two other numbers. Return False otherwise. """ if two_numbers[0] < two_numbers[1]: pass else: two_numbers = sorted(two_numbers) return two_numbers[0] <= one_number <= two_numb...
def permute_bond(bond, cycle): """ Permutes a bond inidice if the bond indice is affected by the permutation cycle. There is certainly a better way to code this. Yikes. """ count0 = 0 count1 = 0 # if the bond indice matches the cycle indice, set the bond indice equal to the next indice in th...
def get_score(stats): """Compute score.""" if 'statement' not in stats or stats['statement'] == 0: return None s = stats.get('statement') e = stats.get('error', 0) w = stats.get('warning', 0) r = stats.get('refactor', 0) c = stats.get('convention', 0) # https://docs.pylint.org/...
def get_reward(state): """ Function returns reward in the given state Args: state -- type(int) state value between [0,47] Returns: reward -- type(int) Reward in the corresponding state game_end -- type(bool) Flag indicates game end (falling out of cliff / reaching...
def to_int(s): """Convert a column to ints usage: new_var = data.apply(lambda f : to_int(f['COLNAME']) , axis = 1) """ try: s1 = int(s) return s1 except ValueError: try: s1 = int(round(float(s))) return s1 except ValueError: retu...
def acceleration(w, m, s): """ Calculate and return the value of acceleration using given values of the params How to Use: Give arguments for w,m and s params *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: w (int):work...
def replace_f_stop(in_exp, f): """Like replace_f, but the function returns None when no replacement needs to be made. If it returns something we replace it and stop.""" modified_in_exp = f(in_exp) if modified_in_exp is not None: return modified_in_exp if type(in_exp) not in (tuple, list)...
def year_fix(t): """ pad the year with leading zeros for file I/O """ # Originator: Greg Hakim # University of Washington # March 2015 # # revised 16 June 2015 (GJH) # make sure t is an integer t = int(t) if t < 10: ypad = '000'+...
def InternalArgNameFrom(arg_external_name): """Converts a user-visible arg name into its corresponding internal name.""" return arg_external_name.replace('-', '_')
def strToFloat(val, defaultValue = None): """ convert string value to float value """ val = str(val).strip() try: return float(val) except ValueError: return defaultValue
def get_solids_from_entities_dict(entities_dict): """ Return a list of solids from entities dictionary. :param entities_dict: entities dictionary :return: [solid object 1, ..., solid object n] """ solid_objects = [solid_dict_list['geometric object'] for solid_dict_list in entities_dict['solids'...
def service_names_match(sdk_service_name: str, dcos_service_name: str) -> bool: """Handles a case where DC/OS service names sometimes don't contain the first slash. e.g.: | SDK service name | DC/OS service name | |--------------------------+-------------------------| | /data-ser...
def get_messages_str(messages): """ From messeges list returns a string with all conversation between client and server Arguments: messages {list} -- list of messages from get_messages Returns: str -- string of conversation """ messages_str = "" for i in messages: ...
def MakeRTFStrike(str_val): """Add strikethrough rtf format to dictionary values""" formatted_val = '\strike\strikec0' + str_val + '\strike0\striked0 ' return formatted_val
def int_to_bytes(i: int, b_len: int) -> bytes: """ Convert an non-negative int to big-endian unsigned bytes. :param i: The non-negative int. :param b_len: The length of bytes converted into. :return: The bytes. """ return i.to_bytes(length=b_len, byteorder='big', signed=False)
def c_all(iterable): """ Implements python 2.5's all() """ for element in iterable: if not element: return False return True
def direct_format_text(text): """Transform special chars in text to have only one line.""" return text.replace('\n','\\n').replace('\r','\\r')
def Decay(mreq,qcat,deltaGcat,kd): """ Computes the decay rate of the bacterial computation (maybe a problem, can go over 1) mreq is the maintenance energy rate requirement qcat is catabolic reaction rate deltaGcat is catabolic reaction energy yield kd is decay rate trait **REF** """ if mreq > qcat and deltaGc...
def simplify_data(raw_data): """Convert CFS formatted data into simple tuple. Parameters ---------- raw_data : dict or list(dict) Each dict element is of the following format: ``{'name': PV name (str), 'owner': str, 'properties': PV properties (list[dict]), 'tags': PV tags (list[dict])}...
def parse(arg, t: type = str): """Convert a series of zero or more arguments to a tuple""" return tuple(map(t, arg.split()))
def import_module(module): """L{import_module} is a shortcut that will import and return L{module} if it is a I{str}. If not, then it is assumed that L{module} is an actual module, and it is returned.""" if isinstance(module, str): return __import__(module, {}, {}, ['']) return module
def sign(number): """Returns the sign of a number: +1 or -1. """ return int(int((number) > 0) - int((number) < 0))
def fock_representation(n, N): """ Converts from the parity representation to the Fock representation. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: the integer representing the Fock mapped value """ mask = 2 ** (N) - 1 ...
def getSSOUsername(redirect=True): """ """ return 'testuser' if cherrypy.request.base != cfg_urlEditBase: if not redirect: return None if redirect is True: redirect = getCurrentEditableUrl() elif redirect is False: raise cherrypy.HTTPRedirect(redir...