content
stringlengths
42
6.51k
def tap_tupoff(tup = (), off = 0): """block_models.tap_tupoff Return the input tuple with constant offset added to both elements """ assert len(tup) == 2, "block_models.py.tap_tupoff wants 2-tuple, got %d-tuple" % (len(tup), ) return (tup[0] + off, tup[1] + off)
def find_tag_column_pairs(tags): """ Creates a dict, where k = the user-created tag names, like 'life', v = db column names, like 'tag1'} """ all_tag_columns = {} counter = 0 for tag in tags: counter += 1 all_tag_columns[str(tag)] = "tag" + str(counter) return all_tag_columns
def quote(path): """ Return a path with quotes added if it contains spaces. path is the path. """ if ' ' in path: path = '"%s"' % path return path
def step_anneal(base_lr, global_step, anneal_rate=0.98, anneal_interval=30000, min_lr=None): """ Annealing learning rate by steps :param base_lr: base learning rate :type base_lr: float :param global_step: global training steps :type global_step: int :param anneal_rate: rate of annealing :type anneal_rate: float :param anneal_interval: interval steps of annealing :type anneal_interval: int :param min_lr: minimum value of learning rate :type min_lr: float :return: scheduled learning rate :rtype: float """ lr = base_lr * anneal_rate ** (global_step // anneal_interval) if min_lr is not None: lr = max(min_lr, lr) return lr
def admins_from_iam_policy(iam_policy): """Get a list of admins from the IAM policy.""" # Per # https://cloud.google.com/appengine/docs/standard/python/users/adminusers, An # administrator is a user who has the Viewer, Editor, or Owner primitive role, # or the App Engine App Admin predefined role roles = [ 'roles/editor', 'roles/owner', 'roles/viewer', 'roles/appengine.appAdmin', ] admins = [] for binding in iam_policy['bindings']: if binding['role'] not in roles: continue for member in binding['members']: user_type, email = member.split(':', 2) if user_type == 'user': admins.append(email) return admins
def verify_bool_parameter(bool_param): """ :type: bool :param bool_param: Boolean parameter to check :rtype: str :return: Fixed format :raises: ValueError: invalid form """ if bool_param is None: return None if bool_param is True: return "true" if bool_param is False: return "false" raise ValueError('"{}" is not a valid parameter. Allowed values are: True or False'.format(bool_param))
def flatlist(nested_list): """ flattens nested list """ flat_list = [item for inner_list in nested_list for item in inner_list] return flat_list
def _format_size(x: int, sig_figs: int = 3, hide_zero: bool = False) -> str: """ Formats an integer for printing in a table or model representation. Expresses the number in terms of 'kilo', 'mega', etc., using 'K', 'M', etc. as a suffix. Args: x (int) : The integer to format. sig_figs (int) : The number of significant figures to keep hide_zero (bool) : If True, x=0 is replaced with an empty string instead of '0'. Returns: str : The formatted string. """ if hide_zero and x == 0: return str("") def fmt(x: float) -> str: # use fixed point to avoid scientific notation return "{{:.{}f}}".format(sig_figs).format(x).rstrip("0").rstrip(".") if abs(x) > 1e14: return fmt(x / 1e15) + "P" if abs(x) > 1e11: return fmt(x / 1e12) + "T" if abs(x) > 1e8: return fmt(x / 1e9) + "G" if abs(x) > 1e5: return fmt(x / 1e6) + "M" if abs(x) > 1e2: return fmt(x / 1e3) + "K" return str(x)
def set_bitstring_bit(bitstring, bitnum, valuetoset): """set a bit in a bitstring, 0 = MSB""" bytepos = bitnum >> 3 bitpos = 7 - (bitnum % 8) bytevalue = bitstring[bytepos] # if setting to 1... if valuetoset: if bytevalue & (2 ** bitpos): # nothing to do, it's set. return bitstring else: return bitstring[:bytepos] + (bytevalue + (2 ** bitpos)).to_bytes(1, byteorder='big') + bitstring[bytepos + 1:] else: # I'm setting it to 0... if bytevalue & (2 ** bitpos): return bitstring[:bytepos] + (bytevalue - (2 ** bitpos)).to_bytes(1, byteorder='big') + bitstring[bytepos + 1:] else: # nothing to do, it's not set. return bitstring
def append_food_name(food_dict, class_names): """ Append food names from labels for nutrition analysis """ food_labels = food_dict['labels'] # [0].to_list() food_names = [' '.join(class_names[int(i)].split('-')) for i in food_labels] food_dict['names'] = food_names return food_dict
def sortFileTree(files): """ Sort the file tree as returned by getFileTree, by 1. Directory, then Files 2. Alphabetical Input: List of dictionaries [ { path: file's absoluate path type: dir/file isRoot: boolean; is "root" directory isParent: boolean; is parent directory } ] Output: Sorted nested dictionary """ sortedList = sorted(files, key=lambda x: (x['type'], x['path'])) return sortedList
def bipartiteMatch(graph): """Find maximum cardinality matching of a bipartite graph (U,V,E). The input format is a dictionary mapping members of U to a list of their neighbors in V. The output is a triple (M,A,B) where M is a dictionary mapping members of V to their matches in U, A is the part of the maximum independent set in U, and B is the part of the MIS in V. The same object may occur in both U and V, and is treated as two distinct vertices if this happens.""" # initialize greedy matching (redundant, but faster than full search) matching = {} for u in graph: for v in graph[u]: if v not in matching: matching[v] = u break while 1: # structure residual graph into layers # pred[u] gives the neighbor in the previous layer for u in U # preds[v] gives a list of neighbors in the previous layer for v in V # unmatched gives a list of unmatched vertices in final layer of V, # and is also used as a flag value for pred[u] when u is in the first layer preds = {} unmatched = [] pred = dict([(u, unmatched) for u in graph]) for v in matching: del pred[matching[v]] layer = list(pred) # repeatedly extend layering structure by another pair of layers while layer and not unmatched: newLayer = {} for u in layer: for v in graph[u]: if v not in preds: newLayer.setdefault(v, []).append(u) layer = [] for v in newLayer: preds[v] = newLayer[v] if v in matching: layer.append(matching[v]) pred[matching[v]] = v else: unmatched.append(v) # did we finish layering without finding any alternating paths? if not unmatched: unlayered = {} for u in graph: for v in graph[u]: if v not in preds: unlayered[v] = None return matching, list(pred), list(unlayered) # recursively search backward through layers to find alternating paths # recursion returns true if found path, false otherwise def recurse(v): if v in preds: L = preds[v] del preds[v] for u in L: if u in pred: pu = pred[u] del pred[u] if pu is unmatched or recurse(pu): matching[v] = u return 1 return 0 for v in unmatched: recurse(v)
def handle_response(response): """ Responses from blockstream's API are returned in json or str :param response: http response object from requests library :return response: decoded response from api """ if isinstance(response, Exception): print(response) return response else: return response
def mag2flux(mag,zp=25): """ Convert magnitude to flux """ f = 10**(2/5*(zp-mag)) return f
def good_phone(phone_numbers): """ Good_phone function""" phone_number = str(phone_numbers) if phone_number[1:].isdigit() and phone_number.startswith("+375"): return len(phone_number) == 13 else: return False
def get_key_from_dict (dictionary, key, group, required=True): """ Grab a value from dictionary :param dictionary: Dictionary to utilize :param key: Key to fetch :param group: Group this key belongs to, used for error reporting purposes :param required: Boolean indicating whether this key is necessary for a valid manifest :return Value if found """ if key not in dictionary: if required: raise KeyError ("Failed to generate manifest: {0} missing {1}".format (group, key)) else: return None else: return dictionary[key]
def quote_aware_split(string, delim=',', quote='"'): """ Split outside of quotes (i.e. ignore delimiters within quotes.""" out = [] s = '' open_quote=False for c in string: if c == quote: open_quote = not open_quote if c == delim and not open_quote: out += [s] s = '' else: s += c return out + [s]
def w_unichr(s): """ A hack to add basic surrogate pair support for SMP Unicode characters when using a build which isn't wide. Seems to (at least partially) work! """ try: return chr(s) except: if not s: raise # Convert the Unihan data to Hex. hex_val = str(hex(int(s)))[2:] result = '0'*(8-len(hex_val)) s = 'Fix PyDev Lexer!' exec_ = "s = u'\\U%s%s'" % (result, hex_val) #print exec_ exec(exec_) return s
def date_format(date_str): """Formats date to yyyy-mm-dd. Returns date as string""" # The day in row data is not supplied day = '01' split_date = date_str.split('/') # When month is not supplied if len(split_date) < 2: month, year = '01', split_date[0] else: month, year = split_date return f'{year}-{month}-{day}'
def multiord(x): """ Like ord(), but takes multiple characters. I.e. calculate the base10 equivalent of a string considered as a set of base-256 digits. """ num = 0 scale = 1 for i in range(len(x)-1, -1, -1): num = num + (ord(x[i])*scale) scale = scale*256 return num
def join_provenances(provenance1, provenance2): """ Given two provenances (lists of id strings) join them together """ # Use a dict to join them joined = dict( (p, True) for p in provenance1 ) joined.update( (p, True) for p in provenance2 ) return list(joined.keys())
def remove_quotes(text): """Removes lines that begin with '>', indicating a Reddit quote.""" lines = text.split('\n') nonquote_lines = [l for l in lines if not l.startswith('>')] text_with_no_quotes = '\n'.join(nonquote_lines).strip() return text_with_no_quotes or text
def _generate_Sequence(min, max, step): """ Generate sequence (that unlike xrange supports float) max: defines the sequence maximum step: defines the interval """ i = min I = [] while i <= max: I.append(i) i = i + step return I
def dict_value2key(mydict, value): """Returns a key for given value or None""" if mydict is None: return None else: try: return list(mydict.keys())[list(mydict.values()).index(value)] except ValueError: return None
def wall_long_mono_to_string(mono, latex=False): """ Alternate string representation of element of Wall's basis. This is used by the _repr_ and _latex_ methods. INPUT: - ``mono`` - tuple of pairs of non-negative integers (m,k) with `m >= k` - ``latex`` - boolean (optional, default False), if true, output LaTeX string OUTPUT: ``string`` - concatenation of strings of the form ``Sq^(2^m)`` EXAMPLES:: sage: from sage.algebras.steenrod.steenrod_algebra_misc import wall_long_mono_to_string sage: wall_long_mono_to_string(((1,2),(3,0))) 'Sq^{1} Sq^{2} Sq^{4} Sq^{8}' sage: wall_long_mono_to_string(((1,2),(3,0)),latex=True) '\\text{Sq}^{1} \\text{Sq}^{2} \\text{Sq}^{4} \\text{Sq}^{8}' The empty tuple represents the unit element:: sage: wall_long_mono_to_string(()) '1' """ if latex: sq = "\\text{Sq}" else: sq = "Sq" if len(mono) == 0: return "1" else: string = "" for (m,k) in mono: for i in range(k,m+1): string = string + sq + "^{" + str(2**i) + "} " return string.strip(" ")
def dict_diff(d1, d2): """Return a dict""" d = {} keys = set(d1.keys()) | set(d2.keys()) for k in keys: if k not in d1: d1[k] = 0 elif k not in d2: d2[k] = 0 d[k] = d1[k] - d2[k] return d
def make_loop_index(ss): """Returns a list of loop indices to see where new base-pairs can be formed. """ loop, stack = [], [] nl, L = 0, 0 for i, char in enumerate(ss): if char == '(': nl += 1 L = nl stack.append(i) loop.append(L) if char == ')': _ = stack.pop() try: L = loop[stack[-1]] except IndexError: L = 0 return loop
def _regexify_matching_pattern(rule_pattern: str, wildcard_optional=False) -> str: """Regexifies pattern against which tokens will be matched (i.e. the left- hand side of the rule usually). """ return rule_pattern.replace("*", f"(.{'+*'[wildcard_optional]})")
def fork_url(feedstock_url: str, username: str) -> str: """Creates the URL of the user's fork.""" beg, end = feedstock_url.rsplit("/", 1) beg = beg[:-11] # chop off 'conda-forge' url = beg + username + "/" + end return url
def hex_str_to_int(input_str): """ Converts a string with hex bytes to a numeric value Arguments: input_str - A string representing the bytes to convert. Example : 41414141 Return: the numeric value """ try: val_to_return = int(input_str, 16) except Exception as e: val_to_return = 0 print(e) return val_to_return
def _escape_html(text): """Escape text for inclusion in html""" return ( text.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace(" ", "&nbsp;") )
def oa_syntax(file): """ Return the full name of an Override Audit syntax based on the short name. """ return "Packages/OverrideAudit/syntax/%s.sublime-syntax" % file
def count_words(sent:str, dictionary:dict): """ Flag whether a word experiment_results """ words = str(sent).split() if any(w in words for w in dictionary): return True else: return False
def clean_empty(data): """Remove empty entries in a nested list/dictionary of items, deep removing nested empty entries. """ if isinstance(data, dict): cleaned = {k: clean_empty(v) for k, v in data.items()} return {k: v for k, v in cleaned.items() if v} if isinstance(data, list): return [v for v in map(clean_empty, data) if v] return data
def etaCalc(T, Tr = 296.15, S = 110.4, nr = 1.83245*10**-5): """ Calculates dynamic gas viscosity in kg*m-1*s-1 Parameters ---------- T : float Temperature (K) Tr : float Reference Temperature (K) S : float Sutherland constant (K) nr : float Reference dynamic viscosity Returns ------- eta : float Dynamic gas viscosity in kg*m-1*s-1 """ eta = nr * ( (Tr + S) / (T+S) )*(T/Tr)**(3/2) return eta
def viz_td(body, port=None, align="CENTER"): # pylint: disable=unused-argument """Create HTML td for graphviz""" port_text = "" if port is None else 'PORT="{}"'.format(port) return '<TD {port_text} ALIGN="{align}">{body}</TD>'.format(**locals())
def GetMovingImages(ListOfImagesDictionaries, registrationImageTypes, interpolationMapping): """ This currently ONLY works when registrationImageTypes has length of exactly 1. When the new multi-variate registration is introduced, it will be expanded. """ if len(registrationImageTypes) != 1: print("ERROR: Multivariate imageing not supported yet!") return [] moving_images = [mdict[registrationImageTypes[0]] for mdict in ListOfImagesDictionaries] moving_interpolation_type = interpolationMapping[registrationImageTypes[0]] return moving_images, moving_interpolation_type
def _kwargs_arg_log(**kwargs): """ Check kwargs argument """ taillines = 100 timestamps = False if 'taillines' in kwargs and kwargs.get("taillines") is not None: taillines = kwargs.get("taillines") if 'timestamps' in kwargs and kwargs.get("timestamps") is not None: timestamps = kwargs.get("timestamps") # return kubernetes api param return {"tail_lines": taillines, "timestamps": timestamps}
def make_symbol_list(maximum): """For a given maximum, return the list of symbols to compute permutations for For instance, 3 would return ['0', '1', '2', '3'] Parameters ---------- maximum: int Returns ------- List[str] A list of strings representing the symbols to be permuted """ return [str(i) for i in range(0, maximum + 1)]
def check2(seq): """ Check for consecutive bytes that repeat once (ex "bb"), and that no others have more consecutive bytes This function is a prevention of a horrific regex. """ seq = seq.strip(".") old = "" status = False count = 0 for x in seq: if x == old: count += 1 elif x != old: count = 1 if count > 2: return False elif count == 2: status = True old = x return status
def translate_with_get(num_list, transl_dict): """ Translates integer list to number word list. If there is no translation available, "no translation" instead of the number word is added to the list. Args: num_list: list with interger items. transl_dict: dictionary with integer keys and number word values. Returns: list of strings which are the translated numbers into words. """ translation = [] for item in num_list: translation.append(transl_dict.get(item, "no translation")) return translation
def isNotNone(value): """Verifie si la valeur d'un element est pas null Args: value (Object): la valeur a verifier Returns: bool: True of False """ return not(value == None)
def check_label(predicted_cui, golden_cui): """ Some composite annotation didn't consider orders So, set label '1' if any cui is matched within composite cui (or single cui) Otherwise, set label '0' """ return int( len(set(predicted_cui.split("|")).intersection(set(golden_cui.split("|")))) > 0 )
def atof(s): """Convert the string 's' to a float. Return 0 if s is not a number.""" try: return float(s or '0') except ValueError: return 0
def is_comment(line): """This function simply checks to see if a line in a RASP file is a comment. Comments begin with a ';' character. Args: line (str): Line from html text. Returns: bool: Whether or not a line is a comment. """ return line.startswith(';')
def model_par(model): """ Given the model, return a list of associated Parameters model - name of the model used """ if model == 'powerlaw': return ['PhoIndex','norm'] if model == 'bbodyrad': return ['kT','norm'] if model == 'ezdiskbb': return ['T_max','norm'] if model == 'diskbb': return ['Tin','norm'] if model == 'cutoffpl': return ['PhoIndex','HighECut','norm'] if model == 'fdcut': return ['cutoffE','foldE'] if model == 'relxill': return ['gamma','logxi','refl_frac','norm'] if model == 'gauss': return ['LineE','Sigma','norm'] if model == 'laor': return ['lineE','norm'] else: raise ValueError("This is not a model pre-entered into model_par!")
def is_xccdf(obj): """ This is currently the best way of telling if an object is an openscap XCCDF benchmark object. """ try: return obj.object == "xccdf_benchmark" except: return False
def prox_l2(x, lambd=1, **kwargs): """ l2 regularization proximity operator (ridge) x : vector to project lambd: reg """ return x / (1 + lambd)
def get_hit_limit_value(armour_value, mobility_value, attack_speed): """ Method to calculate the minimum value the attacking player needs to roll on a D20 dice to hit the target player, which is based on the attack speed of the attacking player, as well as the armour value and mobility value of the target player :param armour_value: the armour value of the target player :param mobility_value: the mobility value of the target player :param attack_speed: the attack speed of the attacking player :return: the minimum value needed to not miss the target player """ print("Attacking Speed: " + str(attack_speed)) print("Enemy Armour: " + str(armour_value) + " Mobility: " + str(mobility_value)) if attack_speed > mobility_value: return round(((armour_value * 6) - ((armour_value * 3) / (attack_speed/mobility_value))) / 5) elif attack_speed < mobility_value: return round(((armour_value * 6) - ((armour_value * 3) * (attack_speed / mobility_value))) / 5)
def frange(start, end=None, inc=None): """A range function, that does accept float increments...""" if end == None: end = start + 0.0 start = 0.0 if inc == None: inc = 1.0 L = [] while 1: next = start + len(L) * inc if inc > 0 and next >= end: break elif inc < 0 and next <= end: break L.append(next) return L
def parse_to_short_cmd(command): """Takes any MAPDL command and returns the first 4 characters of the command Examples -------- >>> parse_to_short_cmd('K,,1,0,0,') 'K' >>> parse_to_short_cmd('VPLOT, ALL') 'VPLO' """ try: short_cmd = command.split(',')[0] return short_cmd[:4].upper() except: # pragma: no cover return
def get_serendipity_val(dic, key): """Return the serendipity of a RNA.""" # The key was in the training set try: return dic[key] # The key wasn't in the training set, then the serendipity is 1 except KeyError: return 1.0
def _julian_day(dt): """Calculate the Julian Day from a (year, month, day, hour, minute, second, microsecond) tuple""" # year and month numbers yr, mo, dy, hr, mn, sc, us = dt if mo <= 2: # From paper: "if M = 1 or 2, then Y = Y - 1 and M = M + 12" mo += 12 yr -= 1 # day of the month with decimal time dy = dy + hr/24.0 + mn/(24.0*60.0) + sc/(24.0*60.0*60.0) + us/(24.0*60.0*60.0*1e6) # b is equal to 0 for the julian calendar and is equal to (2- A + # INT(A/4)), A = INT(Y/100), for the gregorian calendar a = int(yr / 100) b = 2 - a + int(a / 4) jd = int(365.25 * (yr + 4716)) + int(30.6001 * (mo + 1)) + dy + b - 1524.5 return jd
def create_json_topology(): """ TOPOLOGY DEFINITION Some attributes of fog entities (nodes) are approximate """ ## MANDATORY FIELDS topology_json = {} topology_json["entity"] = [] topology_json["link"] = [] cloud_dev = {"id": 0, "model": "cloud", "mytag": "cloud", "IPT": 5000 * 10 ** 6, "RAM": 40000, "COST": 3, "WATT": 20.0} sensor_dev = {"id": 1, "model": "sensor-device", "IPT": 100 * 10 ** 6, "RAM": 4000, "COST": 3, "WATT": 40.0} actuator_dev = {"id": 2, "model": "actuator-device", "IPT": 100 * 10 ** 6, "RAM": 4000, "COST": 3, "WATT": 40.0} link1 = {"s": 0, "d": 1, "BW": 1, "PR": 10} link2 = {"s": 0, "d": 2, "BW": 1, "PR": 1} topology_json["entity"].append(cloud_dev) topology_json["entity"].append(sensor_dev) topology_json["entity"].append(actuator_dev) topology_json["link"].append(link1) topology_json["link"].append(link2) return topology_json
def is_link(value): """ Checks if value is link or not. :param value: any object. :return: Boolean :rtype: bool Usage: >>> is_link('foo') False >>> is_link({'sys': {'type': 'Link', 'id': 'foobar'}}) True """ return ( isinstance(value, dict) and value.get('sys', {}).get('type', '') == 'Link' )
def get_requirements(path): """ Read requirements.txt from a project and return a list of packages. :param path: The path of the project :return: A list of required packages """ req_path = f"{path}/requirements.txt" try: with open(req_path, "r") as file: req_list = file.read().splitlines() except: print("no requirement file in this path") return [] return req_list
def ignore_this_demo(args, reward, t, last_extras): """In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success, and also if we have exit_gracefully, which means for the bag-items tasks, it may not have had visible item(s) at the start, for some reason. """ ignore = (t == 0) if 'exit_gracefully' in last_extras: assert last_extras['exit_gracefully'] return True return ignore
def get_coord(site, L): """Get the 3-vector of coordinates from the site index.""" # XXX: 3D hardcoded, can do N-D x = site // (L[1]*L[2]) yz = site % (L[1]*L[2]) y = yz // L[2] z = yz % L[2] return [x, y, z]
def serialize(grid): """Serializes sudoku grids into a string. Args: grid (list, None): This list characterizes a sudoku grid. The ints are in 0-9, where 0 denotes an empty cell and any other number is a filled cell. Returns: str: This string represents a walk through the grid from top to bottom and left to right. """ string = '' if grid: for row in grid: for cell in row: string += str(cell) return string
def N_primes(N:int): """ list of first N prime numbers Args: N (int): number Returns: list: N prime numbers """ try: nums = [True] * (N*100) except: nums = [True] * (N*10) count = 0 x = 1 primes = [] while count<N: x += 1 if nums[x]: primes.append(x) count += 1 for i in range(x, len(nums), x): nums[i] = False return primes
def check_for_missing_vehicles_table(error): """ Determines if the error is caused by a missing "vehicles" table. Parses the exception message to determine this. Inputs ------ e (ProgrammingError): ProgrammingError exception caught during a query """ return '"vehicles" does not exist' in str(error)
def json_extract(obj, key): """Recursively fetch values from nested JSON.""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, (dict, list)): extract(v, arr, key) elif k == key: arr.append(v) elif isinstance(obj, list): for item in obj: extract(item, arr, key) return arr values = extract(obj, arr, key) return values
def S_STATEMENT_VAR_DEC(var, eol): """Evaluates an S_STATEMENT node for variable decleration""" return var + ";";
def is_even(number: int) -> bool: """ This method will find if the number passed is even or not :param number : a number :return: True if even False otherwise """ if number <= 0: return False return number % 2 == 0
def convert_1d_list_to_string(data): """Utility function.""" s = '' for d in data: s += str(d) + ',' return s[:-1]
def string_escape(string): """escape special characters in a string for use in search""" return string.replace("\\","\\\\").replace("\"","\\\"")
def uint_to_bit_list(n, bits=32): """little-endian""" return [1 & (n >> i) for i in range(bits)]
def a_scramble(str_1, str_2): """Challenge 2 - Return whether str_1 characters can make str_2""" arr1 = list(str_1.lower()); arr2 = list(str_2.lower()); for i in arr2: try: arr1.remove(i) except ValueError: return False return True
def valid_pdf_attachment(pdf_attachment): """ Given a string representing an attachment link, this function asserts if the link is a valid PDF link. """ invalid_urls = ["https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/522875/BIS-16-22-evaluation-of-24_-advanced-learning-loans-an-assessment-of-the-first-year.pdf"] pdf_extension = ".pdf" in pdf_attachment not_mailto = "mailto" not in pdf_attachment not_invalid = pdf_attachment not in invalid_urls return pdf_extension and not_mailto and not_invalid
def solve(passphrases): """Calculate number of valid passphrases. :passphrases: string of passphrases, separated by newlines :return: number of valid passphrases >>> solve('abcde fghij') 1 >>> solve('abcde xyz ecdab') 0 >>> solve('a ab abc abd abf abj') 1 >>> solve('iiii oiii ooii oooi oooo') 1 >>> solve('oiii ioii iioi iiio') 0 """ valid = 0 for passphrase in passphrases.split('\n'): words = passphrase.split() words = [''.join(word) for word in map(sorted, words)] if len(words) == len(set(words)): valid += 1 return valid
def sum_regular(data): """ Sums all elements in passed sequence. You may assume that all elements in passed argument is numeric >>> sum_regular([3, 6, 9]) 18 >>> sum_regular(range(10)) 45 >>> sum_regular((8.2, 6.3, 13.1)) 27.6 >>> sum_regular([]) 0 Args: data: iterable or sequence with numbers Returns: Sum of all elements in passed args, as single number """ return sum(i for i in data)
def reverse_complement(seq): """Reverse complement a DNA sequence.""" complement = { 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'a': 't', 't': 'a', 'g': 'c', 'c': 'g' } return ''.join([complement[b] for b in seq[::-1]])
def bytes_to_int(byte_array: bytes) -> int: """ Bytes to int """ return int.from_bytes(byte_array, byteorder='big')
def is_valid_depth(d): """ Returns: True if d is an int >= 0; False otherwise. Parameter d: the value to check Precondition: NONE (d can be any value) """ return (type(d) == int and d >= 0)
def ascii_replace(text: str): """ replace quotes with their ASCII character representation Args: text (str): text to replace in Returns: str: replaced text """ text = text.replace("'", "&#39;") text = text.replace("[&#39;", "['") text = text.replace("&#39;]", "']") return text
def shape_to_json(shape): """Convert symbolic shape to json compatible forma.""" return [sh.value for sh in shape]
def is_namedtuple(x): """Check if object is an instance of namedtuple.""" t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
def compress_path(path): """removes useless points from a path and leaves only turn-points""" new_path = path i = 0 while i < len(new_path)-2: x1,y1 = new_path[i] x2,y2 = new_path[i+1] x3,y3 = new_path[i+2] if (((x1 == x2) and (x2 == x3)) or ((y1 == y2) and (y2 == y3))): new_path.pop(i+1) else: i = i + 1 return new_path
def calculate_strong_beats(beats_in_bar, grouping): """ Given a particular number of beats in a bar and grouping option, we need to calculate what beats are to be considered strong beats. for example in 7/4 time signature, with grouping of 2,2,3 the strong beats are 1, 3, and 5. :param beats_in_bar: integer. The number of beats in a bar. :param grouping: list of integers. The beat grouping chosen by the user. """ strong_beats = [1] for beat in grouping: strong_beat = strong_beats[-1] + (beat) if strong_beat < beats_in_bar: strong_beats.append(strong_beat) return strong_beats
def to_scalar_safe(obj): """ Convert a numpy data type to a standard python scalar. """ try: return obj.item() except Exception: return obj
def normalize(x, x_mean, x_std): """ perform z-score normalization of a signal """ x_scaled = (x-x_mean)/x_std return x_scaled
def _fullSide_(side): """ Internal function to return the side based on the string short name @param side(string) The short name @return: The full form based on the input """ side = side.upper() sideDict = {"L": "Left", "R": "Right", "C": "Centre" } if side not in sideDict.keys(): raise RuntimeError("This is not supported short name for a side side: {0}".format(side)) return sideDict[side]
def play_result(row): """ Function to determine play outcome""" if row['Punt Blocked']: return 'Punt Blocked' elif row['Fair Catch']: return 'Fair Catch' elif row['Touchback']: return 'Touchback' elif row['Downed']: return 'Downed' elif row['Returned for Negative Gain']: return 'Negative Gain' elif row['Returned for Positive Gain']: return 'Positive Gain' elif row['Returned for No Gain']: return 'No Gain' elif row['Out of Bounds']: return 'Out of Bounds' elif row['PENALTY']: return 'Penalty'
def formatSrtTime(secTime): """Convert a time in seconds (google's transcript) to srt time format.""" sec, micro = str(secTime).split('.') m, s = divmod(int(sec), 60) h, m = divmod(m, 60) return "{:02}:{:02}:{:02},{}".format(h,m,s,micro)
def extend_range(min_max, extend_ratio=.2): """Symmetrically extend the range given by the `min_max` pair. The new range will be 1 + `extend_ratio` larger than the original range. """ mme = (min_max[1] - min_max[0]) * extend_ratio / 2 return (min_max[0] - mme, min_max[1] + mme)
def all_but_last(seq): """ Returns a new sequence containing all but the last element of the input sequence. If the input sequence is empty, a new empty sequence of the same type should be returned. Example: >>> all_but_last("abcde") "abcd" """ newSeq = seq * 0 for i in range(len(seq) - 1): newSeq += seq[i] return newSeq
def strip(value): """Strip string.""" return value.strip()
def death_m(well): """If the well is a melanophore, kill it""" if well == 'M': return 'S' else: return well
def check_type(item, expected_type): """Check the datatype of an object Arguments: item {object} -- the object to check expected_type {string} -- expected type of object Raises: TypeError: That the type isn't as expected Returns: string -- datatime of the item gotten with type() """ item_type = str(type(item)) if "str" in expected_type.lower() and item_type == "<class 'str'>": pass elif "int" in expected_type.lower() and item_type == "<class 'int'>": pass elif "bool" in expected_type.lower() and item_type == "<class 'bool'>": pass elif "float" in expected_type.lower() and item_type == "<class 'float'>": pass elif "tuple" in expected_type.lower() and item_type == "<class 'tuple'>": pass elif "list" in expected_type.lower() and item_type == "<class 'list'>": pass elif "dict" in expected_type.lower() and item_type == "<class 'dict'>": pass elif "datetime" in expected_type.lower() and item_type == "<class 'datetime.datetime'>": pass elif "none" in expected_type.lower() and item_type == "<class 'NoneType'>": pass else: raise TypeError("{a} isn't a {b}".format(a=object, b=expected_type)) return item_type
def mean(*args): """ Calculates the mean of a list of numbers :param args: List of numbers :return: The mean of a list of numbers """ index = 0 sum_index = 0 for i in args: index += 1 sum_index += float(i) return (sum_index / index) if index != 0 else "Division by zero"
def key_for_min(pick): """ Helper function for choose_a_pick :param pick: :return: """ return pick[1][1]
def _calc_shakedrop_mask_prob(curr_layer, total_layers, mask_prob): """Calculates drop prob depending on the current layer.""" return 1 - (float(curr_layer) / total_layers) * mask_prob
def valid_xml_char_ordinal(c): """ Check if a character is valid in xml. :param c: Input character. :return: True or False. """ codepoint = ord(c) # conditions ordered by presumed frequency return ( 0x20 <= codepoint <= 0xD7FF or codepoint in (0x9, 0xA, 0xD) or 0xE000 <= codepoint <= 0xFFFD or 0x10000 <= codepoint <= 0x10FFFF )
def urljoin(*args): """ Construct an absolute URL from several URL components. Args: *args (str) : URL components to join Returns: str : joined URL """ from six.moves.urllib.parse import urljoin as sys_urljoin from functools import reduce return reduce(sys_urljoin, args)
def _GetQueryParametersForAnnotation(log_location): """Gets the path to the logdog annotations. Args: log_location (str): The log location for the build. Returns: The (host, project, path) triad that identifies the location of the annotations proto. """ host = project = path = None if log_location: # logdog://luci-logdog.appspot.com/chromium/... _logdog, _, host, project, path = log_location.split('/', 4) return host, project, path
def set_thermodriver(run_jobs_lst): """ Set vars for the thermodriver run using the run_jobs_lst """ write_messpf = False run_messpf = False run_nasa = False if 'thermochem' in run_jobs_lst: write_messpf = True run_messpf = True run_nasa = True else: if 'write_messpf' in run_jobs_lst: write_messpf = True if 'run_messpf' in run_jobs_lst: run_messpf = True if 'run_nasa' in run_jobs_lst: run_nasa = True return write_messpf, run_messpf, run_nasa
def _create_keys_string(entity, keys) -> str: """Create formatted string for requested keys if non-null in entity. :param Dict entity: entity to check against, eg a Disease or Statement :param Tuple keys: key names to check :return: formatted String for use in Cypher query """ nonnull_keys = [f"{key}:${key}" for key in keys if entity.get(key)] keys_string = ', '.join(nonnull_keys) return keys_string
def address_range(prg): """ Get address range of code """ result = bytearray() result_end = (prg[1] * 255) + prg[0] + (len(prg) - 2) result.append(int(result_end / 255)) result.append(int(result_end % 255)) result.append(prg[1]) result.append(prg[0]) return result
def copies(string, cnt): """returns cnt concatenated copies of string. The cnt must be a positive whole number or zero.""" if cnt < 0: raise ValueError("cnt="+repr(cnt)+" is not valid") return str(string)*cnt
def get_all(): """ returns list of all accepted table types. >>> get_all() ['fact', 'dimension', 'dimension role'] """ return ['fact', 'dimension', 'dimension role']