content
stringlengths
42
6.51k
def mp2d_coeff_formatter(dashlvl, dashcoeff): """Return strings for MP2D program parameter file. Parameters ---------- dashlvl : {'dmp2'} Level of dispersion correction. dashcoeff : dict Dictionary fully specifying non-fixed parameters for `dashlvl` to drive MP2D. Returns -...
def get_data_type(azdat): """ Get the radar file type (radial or raster). Args: azdat: Boolean. Returns: Radial or raster. """ if azdat: return "radial" return "raster"
def duration(seconds): """Return a string of the form "1 hr 2 min 3 sec" representing the given number of seconds.""" if seconds < 1: return 'less than 1 sec' seconds = int(round(seconds)) components = [] for magnitude, label in ((3600, 'hr'), (60, 'min'), (1, 'sec')): if seconds...
def get_peptide_quant(quantdata, quanttype): """Parses lists of quantdata and returns maxvalue from them. Strips NA""" parsefnx = {'precur': max} quantfloats = [] for q in quantdata: try: quantfloats.append(float(q)) except(TypeError, ValueError): pass if not ...
def string_is_yes(string, default=None): """ Mapping of a given string to a boolean. If it is empty or None (evaluates to False), and `default` is set, `default` is returned. If the lowercase of the string is any of ['y', '1', 'yes', 'true', 'ja'], it will return `True`. Else it will return `False`...
def get_headers(context_data) -> list: """ Arrange the headers by importance - 'name' and 'id' will appear first Args: context_data: list or dict containing the context data Returns: headers arrange by importance """ if isinstance(context_data, dict): context_data = [context_da...
def VolumeDensitySlope(r, rs, alpha, beta, gamma): """ The slope of the density profile of a generalised Hernquist model. INPUTS r : radial variable (requires unit) rs : scale radius of model (requires unit) alpha : sharpness of transition between inner and outer bet...
def arn_to_name(arn: str): """Get queue name from given SQS ARN""" arr = arn.split(':') if isinstance(arr, list): return arr[-1] return None
def build_window_title(paused: bool, current_file) -> str: """ Returns a neatly formatted window title. :param bool paused: whether the VM is currently paused :param current_file: the name of the file to display :return str: a neatly formatted window title """ return f"EightDAD {'(PAUSED)' ...
def head(seq): """Returns the first element in a sequence. >>> first('ABC') 'A' """ return next(iter(seq))
def get_order(round, players, offset): """Returns an order of players.""" new_order = [] new_order.extend(players[offset + round - 1:]) new_order.extend(players[:offset + round - 1]) return new_order
def hex_to_rgb(value: str) -> tuple: """ This function converts hex color to rgb color. :param value: color in hex :return: tuple of rgb color """ if (not value.startswith("#")) or (len(value) != 7): raise ValueError(f"value {value} is not a valid hex") try: return...
def sums(n, k): """ Implement sums, which takes two positive integers n and k. It returns a list of lists containing all the ways that a list of k positive integers can sum to n. Results can appear in any order. Return the ways in which K positive integers can sum to N. >>> sums(2, 2) [[1, 1]] ...
def least_common_multiple_slow(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> least_common_multiple_slow(5, 2) 10 >>> least_common_multiple_slow(12, 76) 228 """ ...
def tryattrs(obj, *attrs): """Return the first value of the named attributes found of the given object.""" for attr in attrs: try: return getattr(obj, attr) except AttributeError: pass obj_name = obj.__name__ raise AttributeError("'{}' object has no attribute in {...
def bprop_scalar_usub(x, out, dout): """Backpropagator for primitive `scalar_usub`.""" return (-dout,)
def build_types(data): """ Extract datetypes from model-types.json API: /v1/catalog/model/types Data Structure: { "types: { "<class>: [ {"type": "<type>"} ] }} data = json.load(open("model-types.json")) build_types(data) """ deprecated = {"ipynb", "mi...
def transduce(transformer, reducer, seed, iterable): """ transformer is (a -> b) reducer is (b -> a -> b) seed is b iterable is [a] """ transformedReducer = transformer(reducer) accumulation = seed for value in iterable: accumulation = transformedReducer(accumulation, value) ...
def stripOrderPrefix(filename): """returns the file name without any order prefix (i.e. a number followed by '_'. """ n = filename.find("_") if n > 0: try: int(filename[:n]) return filename[n+1:] except ValueError: pass return filename
def reverse_via_join(string): """Utilizes the join and reversed methods to reverse a string. :param string: The string to be reversed :type string: str :return: string reversed :rtype: str """ reverse_string = "".join(reversed(string)) return reverse_string
def custom_bisect_left(a, x, lo=0, hi=None, getter=0): """Same as bisect.bisect_left, but compares only index "getter" See bisect_left source for more info. """ if lo < 0: raise ValueError("lo must be non-negative") if hi is None: hi = len(a) while lo < hi: mid = (lo + h...
def GetInt(parameter, default_val, base=10): """Convert parameter into an integer using the provided base and default.""" try: return int(str(parameter), base) except ValueError: return default_val
def largest_helper(n, max_): """ :param n: : int (positive), to find the largest digit :param max_: int (ones digit), largest ones digit in n :return: max_, int (ones digit), largest ones digit in n """ if n % 10 > max_: # if last ones digit > max_, replace max_ max_ = n % 10 if n//10 == 0: # base ca...
def get(obj, attr_name): """Returns the attr value for the given object. Example usage: {{ object|get:"pk" }} or {{ object|get:attr_name }} """ if isinstance(obj, dict): return obj.get(attr_name, "") elif isinstance(obj, (list, tuple))\ and (isinstance(attr_name, int)\ or attr...
def get_acc_datetime(date, time): """ Builds datetime in a form of dictionary based on date and time of accident. :param date - Date in format "DD/MM/YYYY" :param time - Time in format "HH:mm" """ datetime = {} # Date format is "DD/MM/YYYY" day = int(date[:2]) month = int(date[3...
def white_grey(w,h): """ retorna una imatge en blanc en escala de grisos >>> white_grey(2,2) ('L', [[255, 255], [255, 255]]) >>> white_grey(1,1) ('L', [[255]]) """ i=0 l=[] while i<(h): j=0 l_2=[] while j<(w): l_2+=[(255)] ...
def is_iso_control_character(c): """ A character is considered to be an ISO control character if its code is in the range '\u0000' through '\u001F' or in the range '\u007F' through '\u009F'. http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isISOControl(int) """ return u'\u0000' ...
def get_mse_sorted_norm_missing(series1, series2): """ sorted and normalized, breaks if in any of the two series are no more data left series length must not differ in more than 10 percent """ mse = 0.0 max_v = max(series1) if max_v == 0.0: # difference is equa series2 re...
def html_email(email, title=None): """ >>> html_email('username@example.com') '<a href="mailto:username@example.com">username@example.com</a>' """ if not title: title = email return '<a href="mailto:{email}">{title}</a>'.format(email=email, title=title)
def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ no_of_steps = 1 print(n) while n != 1: if n % 2 == 0: n = n / 2 print(n) elif ...
def is_valid_dict(val): """ Validates if the value passed is of dict type or not. Args: val (any type): value to be tested Returns: bool: True if dict else False """ return type(val) is dict
def check(gradients, **kwargs): """ Check parameter validity for the median rule. Args: gradients Non-empty list of gradients to aggregate ... Ignored keyword-arguments Returns: None if valid, otherwise error message string """ if not isinstance(gradients, list) or len(gradients) < 1: re...
def Check_Threading_isalive(subthreadinglist=[]): """subthreadinglist: which need to check """ threadingstatus=[] for i in subthreadinglist: if i.is_alive(): threadingstatus+=[True] else: threadingstatus+=[False] return threadingstatus
def collatz_naive(c_dict, n): """ store already computed values in c_dict """ chain_len = 1 curr_val = n while curr_val > 1: if curr_val % 2 == 0: curr_val /= 2 else: curr_val = 3 * curr_val + 1 chain_len += 1 return chain_len
def weekday_name(day_of_week): """Return name of weekday. >>> weekday_name(1) 'Sunday' >>> weekday_name(7) 'Saturday' For days not between 1 and 7, return None >>> weekday_name(9) >>> weekday_name(0) """ days = ['Sunday', 'Monda...
def solution(A, target): # O(N/2) """ Apply binary search on sorted array of integers. >>> solution([1, 2, 3, 7, 11, 15], 11) 4 >>> solution([2, 4, 5, 10, 11, 12, 24, 44], 2) 0 >>> solution([4, 5, 12, 42, 61], 7) -1 """ lower = 0 ...
def validate_date(year, month, day, hour, minute): """ avoid corrupting db if bad dates come in """ valid = True if year < 0: valid = False if month < 1 or month > 12: valid = False if day < 1 or day > 31: valid = False if hour < 0 or hour > 23: valid = Fa...
def _str_equal(obj, s): """Return whether *obj* is a string equal to string *s*. This helper solely exists to handle the case where *obj* is a numpy array, because in such cases, a naive ``obj == s`` would yield an array, which cannot be used in a boolean context. """ return isinstance(obj, str...
def kmgtp_num(x): """ Return a string of a number in the MEM size format, Ie. "30 MB". """ ends = [" ", "K", "M", "G", "T", "P"] while len(ends) and x > 1024: ends.pop(0) x /= 1024 return "%u %s" % (x, ends[0])
def is_matrix(block): """ Returns true if block is a matrix. A matrix must be a Python list of lists where each list has length greater than 1 and all lists must be same length """ return (all([isinstance(r,list) for r in block]) and all([len(block[0])==len(r) for r in bloc...
def get_coverage_value(coverage_report): """ extract coverage from last line: TOTAL 116 22 81% """ coverage_value = coverage_report.split()[-1].rstrip('%') coverage_value = int(coverage_value) return coverage_value
def get_results(amount, input_currency, converted_data): """ Loads transformed data to the dictionary. Parameters ---------- amount : float Amount of money. input_currency : str Currency in 3-letter format. converted_data : dict Converted rates. Returns ----...
def _init_req_fields(req): """ Initializes all the counts to zero and ensures that min_needed and max_counted exist. """ req["count"] = 0 if ("name" not in req) or (req["name"] == '') or (req["name"] == None): req["name"] = None if "no_req" in req: # enforce that no_req cannot requi...
def split_tokens(s,keywordDict): """ Returns list of syntax elements with quotes and spaces stripped. """ result = [] result_append = result.append s_len = len(s) i = 0 while i<s_len: start = i while i<s_len and s[i]!="'": if s[i]=="(" or s[i]==")": if i>start: result_a...
def _bencode_bytes(value, encoding='utf-8'): """ Encode a bytestring (strings as UTF-8), eg 'hello' -> 5:hello """ if isinstance(value, str): value = value.encode(encoding) return str(len(value)).encode(encoding) + b':' + value
def topological_sort(items, partial_order): """Perform topological sort. items is a list of items to be sorted. partial_order is a list of pairs. If pair (a,b) is in it, it means that item a should appear before item b. Returns a list of the items in one of the possible orders, or None ...
def non_multiples(a, b, p): """ Retourne la liste des entiers compris entre a et b non-multiples de p :param a: :param b: :param p: :return: """ return [k for k in range(a, b + 1) if k % p != 0]
def hcf(x, y): """Highest common factor""" if y == 0: return x else: return hcf(y, x % y)
def json_extract(obj, key, return_type): """Recursively fetch values from nested JSON. If return_type == 'string' then it returns string, elif return_type == 'list', it returns values as a list. """ arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""...
def assumed_role_to_principle(assumed_role_arn: str) -> str: """Return role ARN from assumed role ARN.""" arn_split = assumed_role_arn.split(":") arn_split[2] = "iam" base_arn = ":".join(arn_split[:5]) + ":role/" return base_arn + assumed_role_arn.split("/")[1]
def marginalise(pd_y, cpd_xy): """ Marginalise p(X|Y) with respect to p(Y). We get a new distribution p(X). """ pd_x = {} for y, p_y in pd_y.items(): for x, p_xy in cpd_xy[y].items(): p_x = pd_x.get(x, 0.0) pd_x[x] = p_x + (p_xy * p_y) return pd_x
def throughput_history(summaries): """Calculates the change in completion for a list of summaries. Args: summaries (List[ProjectSummary]): List of project summaries to analyze Returns: List[int]: The change in number of items complete between each set of two summaries provided. """ h...
def indices(s): """Create a list of indices from a slice string, i.e. start:stop:step.""" start, stop, step = (int(x) for x in s.split(':')) return list(range(start, stop, step))
def get_assist_turnover_ratio(assists, turnovers): """ Calculates the ratio of assists to turnovers. :param assists: Number of assists. :param turnovers: Number of turnovers. :return: The ratio :rtype: float """ try: ratio = float(assists) / turnovers except ZeroDivisionErro...
def map_manifest(dcc_files,guid_map): """ make a map of files """ mani_map = {k: v for (k,v) in guid_map.items() if k in dcc_files} print("Found {} matching files in GUID map from the DCC manifest.".format(len(mani_map))) return mani_map
def revswitch (protein, noswitch, sites): """Return a reversed protein sequence with cleavage residues switched with preceding residue""" #reverse protein sequence with a reverse splice convert to list revseq = list(protein[::-1]) if noswitch == False: #loop sequence list for i, c in enumerate(revseq...
def do_TA1b_check(path_items): """ Check the path in the archive to ensure the path is valid Task 1b directory structure: <TA1performer>_<run> NIST hypothesisID (1 to Y) <document_id>.ttl (1 to X) Ignores non ttl files. Prints number of ttl files found, a...
def translate_year_to_file_number(year): """ The file names consist of a number and a meta data string. The number changes over the years. 1980 until 1991 it is 100, 1992 until 2000 it is 200, 2001 until 2010 it is 300 and from 2011 until now it is 400. """ file_number = '' if y...
def int_converter(value): """check for *int* value.""" int(value) return str(value)
def sanitize_name_input(string_to_sanitize): """ Sanitize the string passed in parameter by replacing '/' and ' ' by '_' :param string_to_sanitize: :return : :Example: >>> sanitize_name_input('this/is an//example') this_is_an__example """ return string_to_sanitize \ .r...
def rotate(list_a: list, places: int): """Problem 19: Rotate a List N places to the left. Parameters ---------- list_a : list The input list places : int The number of places to rotate the list to the left Returns ------- list A list rotated n places to the left...
def get_summary_from_commit(commit): """ Takes a full commit message, and gives something abbreviated for changelogs """ message = commit["commit"]["message"].split("\n")[0] return "{}: {}".format(commit["sha"], message)
def _calc_csi(tp: int, fp: int, fn: int) -> float: """ Calculate critical success index defined as. Can be interpreted as accuracy that considers rare events, the class that is not rare should be the false class. Values range from [0, 1] where 1 is perfect accuracy? :param tp: true positives :param...
def to_data_type(data_type, value): """Return a conversion statement based on the data type provided """ if data_type in ['Decimal256(0)']: return f'toDecimal256(\'{value}\',0)' else: return f'to{data_type}(\'{value}\')'
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 producto_complejos (a,b,c,d): """ int,int,int,int --> bool OBJ: producto de 2 complejos """ return a*c-b*d , a*d+b*c
def table2dict(data): """ lupa._lupa._LuaTable to dict """ if str(type(data)) != "<class 'lupa._lupa._LuaTable'>": return data for k, v in data.items(): if str(type(v)) != "<class 'lupa._lupa._LuaTable'>": continue if 1 in list(v.keys()): # for array if k ==...
def item_diffs(old_items=None, new_items=None): """ Given previous cve-scan output and new cve-scan output for the same image, return a diff as a map. Keys: { 'added': [], 'removed': [], 'updated': [] } :param old_cves: mapped cve results (from map_rows() result) from pr...
def binary_to_decimal(binary: str) -> int: """ >>> binary_to_decimal("0") 0 >>> binary_to_decimal("1") 1 >>> binary_to_decimal("1010") 10 >>> binary_to_decimal("-11101") -29 """ is_negative = binary[0] == "-" binary = binary[1:] if is_negative else binary decimal = 0 ...
def sanitise_name(name: str) -> str: """ Change given service name into k8s compatible name, including: - 63 character limit - No '.', '_' :param name: :return: """ name = name.replace('.', '-').replace('_', '-') if len(name) > 50: name = name[len(name) - 50:] # K8s ...
def make_line_points(y1, y2, line): """ Convert a line represented in slope and intercept into pixel points """ if line is None: return None slope, intercept = line # make sure everything is integer as cv2.line requires it x1 = int((y1 - intercept)/slope) x2 = int((y2 -...
def _sargs(row,x,y): """ return x, y, if row == True else y,x""" if row: return (x,y) else: return (y,x)
def sum_digits(n): """Sum all the digits of n. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 """ length = len(str(n)) counter, sum = 0, 0 while (counter < length): sum += n % 10 # Adds the last digit ...
def _task_format(task_ref): """Format a task ref for consumption outside of this module""" return { 'id': task_ref['id'], 'type': task_ref['type'], 'status': task_ref['status'], 'input': task_ref['input'], 'result': task_ref['result'], 'owner': task_ref['owner'], ...
def parse_result(results): """ Given a string, return a dictionary of the different key:value pairs separated by semicolons """ if not results: return {} rlist = results.split(";") keyvalpairs = [pair.split(":") for pair in rlist] keydict = { pair[0].strip(): pair[1].stri...
def uadd(x): """Implementation of `uadd`.""" return x.__pos__()
def _get_registered_address_line(address_data): """Extract address line fields from streetName""" street_name = address_data.get('streetName', '') if street_name and isinstance(address_data.get('streetName'), str): address_line = [a.strip() for a in address_data['streetName'].split(',')] re...
def rename_dupe_cols(cols): """ Renames duplicate columns in order of occurrence. columns [0, 0, 0, 0] turn into [0, 1, 2, 3] columns [name10, name10, name10, name10] turn into [name10, name11, name12, name13] :param cols: iterable of columns :return: unique columns with digits increme...
def format_xkcd(comic_data): """Returns info about xkcd 'num'.""" xkcd_info = 'xkcd #{}: {} | {}'.format(comic_data['num'], comic_data['title'], comic_data['url']) return xkcd_info
def get_y_prime(tau, z): """ Equation [2](2.1.2) :param tau: time constant """ return (1.0 / tau) * z
def getMatch(birthdays): """Returns the date object of a birthday that occurs more than once in the birthdays list.""" if len(birthdays) == len(set(birthdays)): return None for a, birthdayA in enumerate(birthdays): for b, birthdayB in enumerate(birthdays[a+1:]): if birthdayA...
def _strip0(n: str): """ '123' -> '123' '034040' -> '34040' '0' -> '0' """ n_strip = n.lstrip('0') if not n_strip: n_strip = '0' return n_strip
def enumerate_keyed_param(param, values): """ Given a param string and a dict of values, returns a flat dict of keyed, enumerated params. Each dict in the values list must pertain to a single item and its data points. Example: param = "InboundShipmentPlanRequestItems.member" values = [ ...
def _is_name_pointer(field_name): """Returns True for name pointer field names such as `name_bodyadr`.""" # Denotes name pointer fields in mjModel. prefix, suffix = 'name_', 'adr' return field_name.startswith(prefix) and field_name.endswith(suffix)
def absmin(x): """ Returns ``abs(x).a`` for an interval, or ``abs(x)`` for anything else. """ if hasattr(x, '_mpi_'): return abs(x).a return abs(x)
def get_charset_intervals(charset): """ Given a charset, returns a list of INCLUSIVE (i.e. [a,b] in mathematical noation) intervals relative to the ascii table. For example, inserting 0123456789ABCDEFabcdef, the returned list will be [(48, 57), (65, 70), (97, 102)] :param charset: the charset a...
def get_insert_pos(fn, have): """when "after" is not given we have to find out ourselves""" while fn: fn, post = fn.rsplit('/', 1) for i in range(len(have)): if not have[i].startswith(fn): continue while ( (i < len(have) - 1) ...
def fuel_consumption_constant(position: int, target_position: int) -> int: """ >>> fuel_consumption_constant(16, 2) 14 >>> fuel_consumption_constant(2, 2) 0 >>> fuel_consumption_constant(2, 14) 12 """ return abs(position - target_position)
def convert_sequence(s): """Convert arguments to qmmlpack format""" if isinstance(s, (str, type(None), float, int)): return s else: if len(s) == 1: return s[0] elif len(s) == 2: if isinstance(s[1], (tuple, list)): # guards against accidentally...
def _serialize_range(start, end): """Return a string suitable for use as a value in a Range header. Args: start: The start of the bytes range e.g. 50. end: The end of the bytes range e.g. 100. This value is inclusive and may be None if the end of the range is not specified. Returns: Returns a ...
def _is_numpy_scalar(obj): """ True if object is any numpy.dtype scalar e.g. `numpy.int32`. """ return type(obj).__module__ == 'numpy'
def unpack_name(packed_name): """ Deconstruct a compact string used for naming pyromancy's compute messages. Args: packed_name (str): Returns: the unpacked message name (list / [str, str]) """ return packed_name.split("|")
def get_refcode(atoms_filename): """ Get the name of the MOF Args: atoms_filename (string): filename of the ASE Atoms object (accepts CIFS, POSCARs, and CONTCARs) Return: refcode (string): name of MOF (defaults to 'mof' if the original filename is just named CONTCAR or POSCAR) """ if '.cif' in atoms_f...
def validate_enc(item): """ Validate given item is encrypted. All leaf values in a sops encrypted file must be strings that start with ENC[. We iterate through lists and dicts, checking only for leaf strings. Presence of any other data type (like bool, number, etc) also makes the file invalid. ...
def single_correction(t, r, m, g): """ Calculates the correction to the deflection angle if using a truncated profile. This ensures that b keeps the definition it has in an untruncated profile. """ if not t: c = 1.0 elif r > m: c = 1.0 else: c = ((m / r) ** (3.0 ...
def union_set(base_set): """ :param base_set: set of sets :return: set, union set of base_set """ uset = set() for x in base_set: uset = uset | x return uset
def gen_output(u1, u2): """ Inputs: u1 : first column u2 : second column Outputs: y : binary variable (1 or 0) ; 1 if x2 is preferred ; 0 if x1 is preferred p: actual preference probability """ # utility function value generation diff = u2 - u1 y = 1*(diff > 0.) #p = prob...
def read_str( s: str, i1: int, i2: int, ) -> str: """Read a string segment Parameters ---------- s : str The entire string i1 : int The initial index i2 : int The last index Returns ------- str The string segment """ s_la...
def update_driver_standings(standings, race_result): """ This function updates the driver's standings to reflect the points earned from a race. Parameters: standings (list): A list of dictionaries that contains the current driver's championship standings. race_result (list): A list of dicti...
def _in_while_loop(control_flow_node_map, op_name): """ Check if a given control flow operator is part of a while loop execution frame. This is based on the fact that there is only one occurrence of `LoopCond` for a loop execution frame and it is only presented in the loop construct. Parameters...