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 except UnicodeEncodeError: return False
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, list): raise TypeError('Input must be type list') # Check that list has length if len(num_lst) == 0: raise ZeroDivisionError('Cannot calculate mean of empty list') try: ret = sum(num_lst) / len(num_lst) except TypeError: raise TypeError('Values of list must be type int or float') return ret
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_weight
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 return x,y else: return False
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{}={}".format(i, srx[i]) params += "&NUM_ORG={}".format(len(srx)) return params
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. """ # DEVNOTE: the same kind of test can be used for numpy numerical types. try: float(a_string) return True except ValueError: return False
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) and len(result) < width: result.extend(['0'] * (width - len(result))) result.reverse() return ''.join(result)
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_element = input_list[i] # Compare the current element with next one while (input_list[j] < next_element) and (j >= 0): input_list[j+1] = input_list[j] j = j-1 input_list[j+1] = next_element return input_list
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[j]) j += 1 return zs
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 \ all_protocols return (sgr1['ethertype'] == sgr2['ethertype'] and sgr1_protocols.issubset(sgr2_protocols) and sgr1.get('port_range_min', 0) >= sgr2.get('port_range_min', 0) and sgr1.get('port_range_max', 65535) <= sgr2.get('port_range_max', 65535) and (sgr2.get('ip_prefix') is None or sgr1.get('ip_prefix') == sgr2.get('prefix')) and (sgr2.get('profile_uuid') is None or sgr1.get('profile_uuid') == sgr2.get('profile_uuid')))
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 max) values, not necessarily 3 Args: sample_dict (dict): instructions to sample a value Returns: scalar: sampled value """ if not isinstance(sample_dict, dict) or "sample" not in sample_dict: return sample_dict
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 prevma -- previous average (n - 1) of the series. """ if bar <= 0: return series[0] return prevma + ((series[bar] - prevma) / (bar + 1.0))
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 :rtype: list of arrays (<info>, <value>, <color>) """ ret = [] l = len(pattern) c = 0 for info, value in data: ret.append((info, value, pattern[c])) c = (c + 1) % l return ret
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': # convert version 1.0 -> 1.1 # changes: # seperate voltage/current quantities instead of generic value version = '1.1' # assume old value quantity was referring to a voltage if 'Value' in dValue: dValue['Voltage'] = dValue.pop('Value') # replace 'Value' with 'Voltage' dQuantReplace['Value'] = 'Voltage' # return new version and data return (version, dValue, dOption, dQuantReplace)
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 neighbors clockwise starting by the one on the right if (((x < len(grid)-1) and search(x+1, y, grid)) or (y > 0 and search(x, y-1, grid)) or (x > 0 and search(x-1, y, grid)) or (y < len(grid)-1 and search(x, y+1, grid))): return True return False
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 test filenames must end in _rbac suffix"
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 zip(old, new): string = string.replace(i, j) return string
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_exercise_id: str :return: A string representing the status of the case :rtype: str """ return next( case_group["caseGroupStatus"] for case_group in case_groups if case_group["collectionExerciseId"] == collection_exercise_id )
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 to @return: Redistrbuted number eg [6,4] """ # Return the normalised list return [round(float(val) / sum(proportionList) * value, roundValue) for val in proportionList]
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", "release_time", "deadline", "duration", "setuptimes"] for pname in gezero: try: if params[pname] < 0: raise ValueError("Parameter: {} less than 0.".format(pname)) except TypeError: if params[pname][0] < 0: raise ValueError("Parameter: {} less than 0.".format(pname)) # greater than 0 geone = ["machines", "jobs", "lotsize", "operations", "allowed_machines"] for pname in geone: try: if params[pname] <= 0: raise ValueError("Parameter: {} less than 1.".format(pname)) except TypeError: if params[pname][0] <= 0: raise ValueError("Parameter: {} less than 1.".format(pname)) # greater or equal to previous value geprev = ["operations", "duration", "allowed_machines", "weight", "setuptimes", "deadline"] for pname in geprev: if params[pname][0] > params[pname][1]: raise ValueError("Parameter: {} has wrong ordered values." .format(pname)) # special requirements if params["allowed_machines"][1] > params["machines"]: raise ValueError( "Parameter: allowed_machines is greater than machines.") return True
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(arg, dict): return { k: nested_map(f, *[a[k] for a in args]) for k in arg } else: return f(*args)
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 ``replace_from``, ``replace_from`` items will be translated to corresponding ``replace_to``. A ``replace_to`` list must have the same length as ``replace_from`` If ``replace_to`` is a string, all ``replace_from`` occurence will be replaced by that string. ``replace_from`` can also be a str. If it is, every char in it will be translated as if ``replace_from`` would be a list of chars. If ``replace_to`` is a str and has the same length as ``replace_from``, it will be transformed into a list. """ if isinstance(replace_to, str) and (len(replace_from) != len(replace_to)): replace_to = [replace_to for r in replace_from] if len(replace_from) != len(replace_to): raise ValueError('len(replace_from) must be equal to len(replace_to)') replace = list(zip(replace_from, replace_to)) for r_from, r_to in [r for r in replace if r[0] in s]: s = s.replace(r_from, r_to) return s
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) # Get first iterable return next(it) except TypeError: # Fallback, val is scalar return 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 string. """ if s == "": return s if not s.startswith("$"): s = "$" + s if not s.endswith("$"): s = s + "$" return s
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 value in row: try: if value <= tolerance: continue total += value count += 1 except TypeError: continue return total / count
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 literal in map_: return map_[literal] else: return literal elif isinstance(literal, (bool,)) or literal is None: return literal else: # Raise error for non string objects raise TypeError("Literal not recognised")
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() samples.append(sample) return samples
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['group']['active']]
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": data_net, "time_column": "TimeGenerated", "source_columns": ["VMRegion", "AllExtIPs"], "color": "green", }, }
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%. if new_v < 0.9 * v: new_v += divisor return new_v
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.lower(), schema)
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 keys. The returned list is in the same order as the original records. """ filtered = [] for record in records: filtered.append({key: record[key] for key in keys if key in record}) return filtered
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] # if value has nothing in it, return None. if not value: value = None return name, value
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, value in sort_result}
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, madeof) return "hahah %s's face" % name return 'hahah your face'
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 is empty if not specified """ outdir = '' simupara = [] while line: line = fp.readline() if not line: break if line == '--\n': continue line = line.strip('\n') line = line.split(' ') if len(line) == 1: outdir = str(line[0]) else: simupara = line return outdir, simupara
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_without_domain.split('/') return (owner, project)
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.9') 3 >>> to_integer('invalid') 0 .. versionadded:: 4.0.0 """ try: # Convert to float first to handle converting floats as string since int('1.1') would fail # but this won't. num = int(float(obj)) except (ValueError, TypeError): num = 0 return num
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 = codecs.lookup(name) except LookupError: return name else: return codec.name
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 if algo not in ['SHA256', 'SHA512', 'MD5']: raise ValueError("unsupported hashing algorithm %s" % algo) with open(filePath, 'rb') as content: hash = hashlib.new(algo) while True: chunk = content.read(8192) if not chunk: break hash.update(chunk) return hash.hexdigest()
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 replacement applied.""" return [x if x != base else replacement for x in xs]
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[rule_id] = rule messages = messages_input.split('\n') return rules, messages
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 = list() for vars_line in trace_variables_contents: vars_list.append(vars_line.split("#")[0].strip()) return vars_list
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 'umbrella header "%s"' % basename
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_numbers[1]
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 the cycle # we count so we dont change a bond indice more than once. # If the cycle indice is at the end of the list, the bond indice should become the first element of the list since thats how cycles work. # theres probably a better way to have a list go back to the beginning for i, idx in enumerate(cycle): if (bond[0] == idx) and (count0 == 0): try: bond[0] = cycle[i+1] except: bond[0] = cycle[0] count0 += 1 if (bond[1] == idx) and (count1 == 0): try: bond[1] = cycle[i+1] except: bond[1] = cycle[0] count1 += 1 # sort if the permutation messed up the order. if you convert 1,2 to 2,1, for example bond.sort() return bond
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/en/1.6.0/faq.html return 10 - 10*(5 * e + w + r + c) / s
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 the goal) """ # game continues game_end = False # all states except cliff have -1 value reward = -1 # goal state if(state == 47): game_end = True reward = 10 # cliff if(state >= 37 and state <= 46): game_end = True # Penalize the agent if agent encounters a cliff reward = -100 return reward, game_end
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: return s
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/transformation of energy m (int):mass in kg s (int):distance in meter Returns: int: the value of acceleration in m/s2 """ a = w / (m * s) return a
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): return in_exp res = tuple() for e in in_exp: res += (replace_f_stop(e, f), ) if type(in_exp) == list: res = list(res) return res
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'+str(t) elif t >= 10 and t < 100: ypad = '00'+str(t) elif t >= 100 and t < 1000: ypad = '0'+str(t) else: ypad = str(t) return ypad
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']] return solid_objects
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-services/cassandra | data-services/cassandra | | /production/cassandra | /production/cassandra | """ return dcos_service_name.lstrip("/") == sdk_service_name.lstrip("/")
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: messages_str += "{}: {}\n".format(i[0], i[1]) return messages_str.strip("\n\t ")
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 deltaGcat <= 0: return(kd*(mreq-qcat)/mreq) elif deltaGcat > 0: return(kd) else: return(0)
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])}``. Returns ------- ret : list or list(list) Each list element is of the following format: PV name (str), PV properties (dict), PV tags (list(str)) Note ---- If the input *raw_data* is a single dict, the returned on is a single list. See Also -------- get_data_from_tb, get_data_from_db, get_data_from_cf """ if isinstance(raw_data, dict): retval = [ raw_data['name'], {p['name']: p['value'] for p in raw_data['properties']}, [t['name'] for t in raw_data['tags']] ] else: retval = [] for r in raw_data: new_rec = [ r['name'], {p['name']: p['value'] for p in r['properties']}, [t['name'] for t in r['tags']] ] retval.append(new_rec) return retval
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 fock_rep = n ^ (n << 1) #print(f'{n} = {n:b}: {fock_rep:04b} {mask:04b}') return fock_rep & mask
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(redirect) if "issosession" not in cherrypy.request.cookie: if not redirect: return None if redirect is True: redirect = cherrypy.url(qs=cherrypy.request.query_string) raise cherrypy.HTTPRedirect(cfg_urlSSO + urllib2.quote(redirect, safe=":/")) sso = urllib2.unquote(cherrypy.request.cookie["issosession"].value) session = map(base64.b64decode, string.split(sso, "-")) return session[0]