content
stringlengths
42
6.51k
def running_paren_sums(program): """ Map the lines in the list *program* to a list whose entries contain a running sum of the per-line difference between the number of '(' and the number of ')'. """ count_open_parens = lambda line: line.count('(') - line.count(')') paren_counts = map(count_open_parens, program) rps = [] total = 0 for paren_count in paren_counts: total += paren_count rps.append(total) return rps
def s2(n, k): """Calculates the Stirling number of the second kind.""" if n == 0 or n != 0 and n == k: return 1 if k == 0 or n < k: return 0 return k * s2(n-1, k) + s2(n-1, k-1)
def calc_ts(fn: float, fp: float, tp: float) -> float: """ :param fn: false negative miss :param fp: false positive or false alarm :param tp: true positive or hit :return: Threat score """ try: calc = tp / (tp + fn + fp) except ZeroDivisionError: calc = 0 return calc
def get_slack_pending_subgraph_notification_message(subgraph_name: str): """ Get slack message template with defined values :param subgraph_name: :param subgraph_version: :return: """ main_title = ":warning: `Subgraph status is NOT OK`" message = { 'text': 'Subgraph is NOT OK status', 'blocks': [ { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': main_title } }, { 'type': 'section', 'fields': [ { 'type': 'mrkdwn', 'text': f'*Subgraph name:*\n {subgraph_name}' }, { 'type': 'mrkdwn', 'text': f'*Version (current|pending):*\n `pending`' } ] } ] } return message
def is_int(val): """check when device_id numeric represented value is int""" try: int(val) return True except ValueError: return False
def dict_strs_to_dict(*dict_strs): """ Parses a list of key:value strings into a dict. Used to go from CLI->Python. """ d = {} for dict_str in dict_strs: try: k, v = dict_str.split(":", 1) except ValueError: raise ValueError("can't parse string '{0}': must have format 'key:value'".format( dict_str)) d[k] = v return d
def _escape_html(text, escape_spaces=False): """Escape a string to be usable in HTML code.""" result = "" for c in text: if c == "<": result += "&lt;" elif c == ">": result += "&gt;" elif c == "&": result += "&amp;" elif c == '"': result += "&quot;" elif c == "'": result += "&#39;" elif c == " " and escape_spaces: result += "&nbsp;" elif ord(c) < 32 or 127 <= ord(c) < 160: result += '&#x{0};'.format(hex(ord(c))[2:]) else: result += c return result
def choose_ncv(k): """ Choose number of lanczos vectors based on target number of singular/eigen values and vectors to compute, k. """ return max(2 * k + 1, 20)
def dic_similar(dic1, dic2): """ Check is Sparky parameter dictionaries are the same. """ if dic1.keys() != dic2.keys(): print("Not same keys!") assert dic1.keys() == dic2.keys() for key in dic1.keys(): if dic1[key] != dic2[key]: print(key, dic1[key], dic2[key]) assert dic1[key] == dic2[key] return True
def get_ids(cs): """Return chemical identifier records.""" records = [] for c in cs: records.append({k: c[k] for k in c if k in {'names', 'labels'}}) return records
def get_path_dicts(key): """gets the right training data and model directory given the demo""" td_dict = { 'company': 'data/company/company_full.json', } td_lookup_dict = { 'company': 'data/company/company_full_lookup.json', } td_ngrams_dict = { 'company': 'data/company/company_full_ngrams.json', } td_both_dict = { 'company': 'data/company/company_full_both.json', } model_dir_dict = { 'company': 'data/models', } td = td_dict[key] td_lookup = td_lookup_dict[key] td_ngrams = td_ngrams_dict[key] td_both = td_both_dict[key] model_dir = model_dir_dict[key] return td, td_lookup, td_ngrams, td_both, model_dir
def is_in_range(f, f_range): """ f_range is a tuple (f_min, f_max) """ return (f >= f_range[0]) and (f < f_range[1])
def compact_dict(source_dict): """ Drop all elements equal to None """ return {k: v for k, v in source_dict.items() if v is not None}
def check_number(x, lower=None, upper=None): """ This function returns True if the first argument is a number and it lies between the next two arguments. Othwerise, returns False. :param x: Value to be checked :type x: number :param lower: minimum value accepted :type lower: number :param upper: maximum value accepted :type upper: number :return: if 'x' check pass :rtype: bool """ if x is None: return False lower = lower if lower is not None else float("-inf") upper = upper if upper is not None else float("inf") is_number = isinstance(x, float) or isinstance(x, int) return is_number and (x >= lower and x <= upper)
def is_prime(n: int) -> bool: """Primality test using 6k+-1 optimization.""" if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True
def _insert_rst_epilog(c): """Insert the rst_epilog variable into the configuration. This should be applied after other configurations so that the epilog can use other configuration variables. """ # Substitutions available on every page c[ "rst_epilog" ] = """ .. |eups-tag| replace:: {eups_tag} .. |eups-tag-mono| replace:: ``{eups_tag}`` .. |eups-tag-bold| replace:: **{eups_tag}** """.format( eups_tag=c["release_eups_tag"] ) return c
def validate_padding(value): """Validates and format padding value Args: value: `str` padding value to validate. Returns: formatted value. Raises: ValueError: if is not valid. """ padding = value.upper() if padding not in ['SAME', 'VALID']: raise ValueError('Padding value `{}` is not supported, ' 'expects `SAME`\`VALID`'.format(value)) return padding
def djb2(data, seed=5381): """ djb2 hash algorithm. Input: a 'bytes' object. Output: 32-bit integer. http://www.cse.yorku.ca/~oz/hash.html Use the hash value from the previous invocation as the seed input for the next invocation if you want to perform the hash in chunks-- see unit tests for example. """ # https://stackoverflow.com/questions/16745387/python-32-bit-and-64-bit-integer-math-with-intentional-overflow hash = seed & 0XFFFFFFFF for d in data: hash = 0xFFFFFFFF & (0XFFFFFFFF & (hash * 33) + d) return hash
def tuple_list_to_lua(tuple_list): """Given a list of tuples, return a lua table of tables""" def table(it): return "{" + ",".join(map(str, it)) + "}" return table(table(t) for t in tuple_list)
def pr_list_to_str_list(pr_list): """ converts pr list to string list which is comfortable to be serialized to json :param projectList: SQLProject list :return: string list """ str_list = [] for pr in pr_list: str_list.append(pr.alias) return str_list
def email_normalize(email): """ Email normalization to get unique path. :param email: user email address. :return: normalized string value """ return email.replace('@', '_at_').replace('.', '_dot_')
def input_checker(s): """ This function takes a string input and returns false if it contains one or more non terminal spaces. If not, the function returns an integer. Args: s (string): string which needs to be checked Returns: boolean: False if the string contains one or more non terminal spaces int: Value of the number in the string if the string does not contain any non terminal spaces """ s = s.strip() temp = s.split() if len(temp) > 1: return False else: return int(s)
def _format_comment(comment, comm_char): """Format a multiline comment.""" return '\n'.join(f'{comm_char} {_line}' for _line in comment.splitlines())
def zero_if_less_than(x, eps): """Return 0 if x<eps, otherwise return x""" if x < eps: return 0 else: return x
def vector_from_line(point,line): """returns the shortest vector from the line to the point""" linepoint = line[0] dx,dy = line[1] # move line (and therefore the point) so the line passes through (0,0) px = point[0] - linepoint[0] py = point[1] - linepoint[1] # find closest point on the line if dx == 0.0: cx = 0 cy = py elif dy == 0.0: cx = px cy = 0 else: cx = (py + px*dx/dy)/(dy/dx + dx/dy) cy = py + (dx/dy)*(px-cx) return px-cx,py-cy
def brightness(color): """ Returns the luminance of a color in RGB form """ return 0.2126*color[0] + 0.7152*color[1] + 0.0722*color[2]
def split_sequence(seq, n): """Generates tokens of length n from a sequence. The last token may be of smaller length.""" tokens = [] while seq: tokens.append(seq[:n]) seq = seq[n:] return tokens
def break_list2chunks(lst, n): """ Break a list into chunks of size N using list comprehension Args: lst (list): 1d list n (int): How many elements each output list should have Returns: list: 2D list """ return [ lst[i * n:(i + 1) * n] for i in range((len(lst) + n - 1) // n ) ]
def bit_first(x): """Get the first digit where 1 stands(0-indexed) Args: x (int): bit Returns: int: first digit >>> bit_first(1) 0 >>> bit_first(4) 2 >>> bit_first(6) 2 >>> bit_first(0b1011000) 6 """ return x.bit_length() - 1
def get_license_file_key(license_desc): """ Converts a license description to a file and URL-safe string. For example, "Music and Dance" becomes "music-and-dance". :param license_desc: The license description to encode :return: The encoded license description """ return license_desc.lower()\ .replace(" - ", "-")\ .replace(" ", "-")\ .replace(",", "")\ .replace("(", "")\ .replace(")", "")\ .replace("'", "")\ .replace("/", "-")\ .replace("\\", "-")\ .replace(";", "")
def pairs_to_lists(pairs): """Convert list of pairs into to two tuple lists. Removes any SNPs with an empty match list. Parameters ---------- pairs : list From filter_by_distance(): (rsid, loc, set((rsid, loc))) Returns ------- snp_list : list_of_tuple comp_list : list_of_tuple (rsid, loc) """ query = [] comp = [] for snp, loc, matches in pairs: if not matches: continue query.append((snp, loc)) for snp2, loc2 in matches: comp.append((snp2, loc2)) return set(query), set(comp)
def get_category(risk_attr): """ Assigns a category to a given risk attribute, that is to a human at a given hour of a given day Args: risk_attr (dict): dictionnary representing a human's risk at a given time Returns: str: category for this person """ if risk_attr["test"]: return "D" if risk_attr["infectious"] and risk_attr["symptoms"] == 0: return "B" if risk_attr["infectious"] and risk_attr["symptoms"] > 0: return "C" if risk_attr["exposed"]: return "A" if risk_attr["order_1_is_tested"]: return "J" if risk_attr["order_1_is_symptomatic"]: return "I" if risk_attr["order_1_is_presymptomatic"]: return "H" if risk_attr["order_1_is_exposed"]: return "E" return "K"
def edit_distance(a, b): """Returns the Hamming edit distance between two strings.""" return sum(letter_a != letter_b for letter_a, letter_b in zip(a, b))
def isfloat(s:str) -> bool: """ Functions to determine if the parameter s can be represented as a float Parameters: ----------- * s [str]: string which could be or not a float. Return: ------- * True: s can be represented as a float. * False: s cannot be represented as a float. """ float_c = list(".0123456789") if not all([c in float_c for c in s]): return False return True
def check_same_parent(a, b, dataset, dict_parents): """ Check that the parents are the same """ return dict_parents[dataset][a] == dict_parents[dataset][b]
def parseIDNResponse(s): """Parse the response from *IDN? to get mfr and model info.""" mfr, model, ver, rev = s.split(',') return mfr.strip() + ' ' + model.strip()
def available_inventory_accuracy(counted_items, counted_items_that_match_record): """Return the Available Inventory Accuracy. Args: counted_items (int): Total items supposedly in the inventory according to the WMS. counted_items_that_match_record (int): Number of items were the WMS count matches the actual count. Returns: Percentage of available inventory that was correctly counted in the WMS. """ return (counted_items_that_match_record / counted_items) * 100
def isnumber(s): """ Checks if string can be converted to float and is >0""" try: f=float(s.replace(',','.')) if f > 0: return True else: return False except ValueError: return False
def factorial_tabulation(n): """Tabulation implementation of factorial: O(n) runtime, O(n) space""" d = [0] * (n + 1) d[0] = 1 # could alternatively have base case of d[1] = 1 and compute d[n] from there, looping from i = 2 for i in range(1, n + 1): d[i] = i * d[i - 1] return d[n]
def prior_max_field(field_name, field_value): """ Creates prior max field with the :param field_name: prior name (field name initial) :param field_value: field initial properties :return: name of the max field, updated field properties """ name = field_name value = field_value.copy() value.update({ 'label': 'Max', 'required': False, }) return name + '_max', value
def bits2int(mask): """ Change, for example, 24 or '24' into '4294967040'. It returns the stringified version of the integer, in other words. NOTE: Currently only v4; will need update for v6. """ try: mask = int(mask) except: raise ValueError('Invalid netmask, non-numeric: ' + mask) else: if 1 <= mask <= 32: return str(int("1"*mask+"0"*(32-mask),2)) else: raise ValueError('Invalid netmask, outside of 1 <= m <= 32 range: ' + str(mask))
def find_missing_number(array): """ :param array: given integer array from 1 to len(array), missing one of value :return: The missing value Method: Using sum of list plus missing number subtract the list of the given array Complexity: O(n) """ n = len(array) expected_sum = (n + 1) * (n + 2) // 2 return expected_sum - sum(array)
def num_to_bin(num): """ Convert a `num` integer or long to a binary string byte-ordered such that the least significant bytes are at the beginning of the string (aka. little endian). NOTE: The code below does not use struct for conversions to handle arbitrary long binary strings (such as a SHA512 digest) and convert that safely to a long: using structs does not work easily for this. """ binstr = [] while num > 0: # add the least significant byte value binstr.append(chr(num & 0xFF)) # shift the next byte to least significant and repeat num = num >> 8 # reverse the list now to the most significant # byte is at the start of ths string to speed decoding return ''.join(reversed(binstr))
def _fill_defaults(options, settings): """ Returns options dict with missing values filled from settings. """ result = dict(settings) # settings is a list of (key,value) pairs result.update(options) return result
def _parse_brackets(brackets): """ Return a `dict` of brackets from the given string. """ return dict(zip(brackets[::2], brackets[1::2]))
def rank(x, i): """Return rank of x[i] w.r.t. all values in x. Rank of x[i] is the number of elements below x[i], that is, elements smaller than x[i], or equal to x[i] but left from it in x. """ a = x[i] return sum(int(b < a or (b == a and j < i)) for j, b in enumerate(x))
def get_response_definition(response, resolver): """ Get response definition from openapi schema """ if '$ref' in response: resp_ref = resolver.resolve(response['$ref']) return resp_ref[1] if 'content' in response: return response return None
def round_price(price): """Takes a price and rounds it to an appropriate decimal place that Robinhood will accept. :param price: The input price to round. :type price: float or int :returns: The rounded price as a float. """ price = float(price) if price <= 1e-2: returnPrice = round(price, 6) elif price < 1e0: returnPrice = round(price, 4) else: returnPrice = round(price, 2) return returnPrice
def compact(sequence): """ Returns list of objects in sequence sans duplicates, where s1 = (1, 1, (1,), (1,), [1], [1], None, '', 0) compact(s1) == [[1], 1, 0, (1,), None, ''] """ result = [] dict_ = {} result_append = result.append for i in sequence: try: dict_[i] = 1 except: if i not in result: result_append(i) result.extend(dict_.keys()) return result
def compare_letter_count(origin: str, compared_to: str) -> bool: """ Compares word_1 and word_2, returns True if they are anagrames :param origin: First word :param compared_to: Second word :return: True if origin and compared_to have the same length and the same amount of each letters """ if type(origin) != str or type(compared_to) != str: return False origin = origin.lower().replace(" ", "") compared_to = compared_to.lower().replace(" ", "") if len(origin) != len(compared_to): return False return all([origin.count(letter) == compared_to.count(letter) for letter in origin])
def get_short_title(title: str) -> str: """Get the short version of a text.""" titles = [title, title.split("\n")[0], title.split(".")[0]] lens = [len(title) for title in titles] short_titles = sorted(zip(lens, titles), key=lambda v: v[0]) return short_titles[0][1]
def render_calendar(context): """Render venue calendar.""" return {"request": context.get("request")}
def lose_lose(key): """ This hash function is extremely bad. Don't use it. This hash function appeared in K&R (1st ed) but at least the reader was warned: "This is not the best possible algorithm, but it has the merit of extreme simplicity." """ hash = 0 for letter in str(key): hash += ord(letter) return hash
def db2pow(x): """ Converts from dB to power ratio Parameters ---------- x - Input in dB Returns ------- m - magnitude ratio """ m = 10.0 ** (x / 10.0) return m
def _get_encoded_list(items): """Return Python list encoded in a string""" return '[' + ', '.join(['\'%s\'' % (item) for item in items]) + ']' \ if items else '[]'
def _snapping_round(num, eps, resolution): """ Return num snapped to within eps of an integer, or int(resolution(num)). """ rounded = round(num) delta = abs(num - rounded) if delta < eps: return int(rounded) else: return int(resolution(num))
def cli_dump(key, spacer, value, suppress_print=False): """ Returns a command line interface pretty string for use in admin scripts and other things that dump strings to CLI over STDOUT. """ spaces = spacer - len(key) output = "%s:" % key output += " " * spaces output += "%s" % value output += "\n" return output
def choose(paragraphs, select, k): """Return the Kth paragraph from PARAGRAPHS for which SELECT called on the paragraph returns True. If there are fewer than K such paragraphs, return the empty string. Arguments: paragraphs: a list of strings select: a function that returns True for paragraphs that can be selected k: an integer >>> ps = ['hi', 'how are you', 'fine'] >>> s = lambda p: len(p) <= 4 >>> choose(ps, s, 0) 'hi' >>> choose(ps, s, 1) 'fine' >>> choose(ps, s, 2) '' """ # BEGIN PROBLEM 1 true_list = [] for i in paragraphs: if select(i): true_list.append(i) if k < len(true_list): return true_list[k] else: return '' # END PROBLEM 1
def validate_business_payload(new_payload): """ this method validate the business payload """ if len(new_payload['business_name']) > 50: return {'message': 'name is too long'}, 400 if len(new_payload['category']) > 50: return {'message': 'body is too long'}, 400 if len(new_payload['location']) > 50: return {'message': 'location is too long'}, 400 if len(new_payload['profile']) > 256: return {'message': 'profile is too long'}, 400
def _eval_keys(keys): """Return the replacement mapping from rmap-visible parkeys to eval-able keys. >>> _eval_keys(("META.INSTRUMENT.NAME",)) {'META.INSTRUMENT.NAME': 'META_INSTRUMENT_NAME'} """ evalable_map = {} for key in keys: replacement = key.replace(".", "_") if replacement != key: evalable_map[key] = replacement return evalable_map
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return f"{prefix}{num}{suffix}"
def decode_num(num): """ decodes the num if hex encoded """ if isinstance(num, str): return int(num, 16) return int(num)
def get_item_length(obj, key): """ Template tag to return the length of item in gien dictionary """ val = "0" if obj and type(obj) == dict: val = len(obj.get(key, [])) return val
def is_lp(row): """Picks up a lof of splice_region_variant with MED impact.""" c = -1 if isinstance(row['cadd_phred'], str): if row['cadd_phred'].strip() and row['cadd_phred'].strip() != 'None': c = float(row['cadd_phred']) else: c = row['cadd_phred'] return ( (row['dbnsfp_lr'] == 'D' or row['dbnsfp_radialsvm'] == 'D') and c>=20.0) or ((row['eff_indel_splice'] == 1 or row['is_splicing'] == 1) and row['impact_severity'] in ('HIGH','MED'))
def ordinal_suffix(n): """Returns a suffix (`st`, `nd`, ...) of the given ordinal number (1, 2, ...). :param int n: Ordinal number. :returns: Suffix (:class:`str`) that corresponds to `n`. """ n = abs(n) return ( "st" if (n % 10) == 1 and (n % 100) != 11 else \ "nd" if (n % 10) == 2 and (n % 100) != 12 else \ "rd" if (n % 10) == 3 and (n % 100) != 13 else \ "th" )
def setup_go_func(func, arg_types=None, res_type=None): """ Set up Go function, so it know what types it should take and return. :param func: Specify Go function from library. :param arg_types: List containing file types that function is taking. Default: None. :param res_type: File type that function is returning. Default: None. :return: Returns func arg back for cases when you want to setup function and assign it to variable in one line. """ if arg_types is not None: func.argtypes = arg_types if res_type is not None: func.restype = res_type return func
def open_file_as_string(filename): """Takes a filename as a string, returns text of file as a string""" fin = open(filename) s = "" for i in fin: s += (i.strip()) return s
def valid_list(val, rule): """Default True, check against rule if provided.""" return (rule(val) if callable(rule) else val == rule if rule else True)
def add(coords1, coords2): """ Add one 3-dimensional point to another Parameters coords1: coordinates of form [x,y,z] coords2: coordinates of form [x,y,z] Returns list: List of coordinates equal to coords2 + coords1 (list) """ x = coords1[0] + coords2[0] y = coords1[1] + coords2[1] z = coords1[2] + coords2[2] return [x, y, z]
def shell(cmd, cwd=None, closeFds=True): """ Executes a shell command :param cmd: Command string :param cwd: Current working directory (Default value = None) :param closeFds: If True, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. Defaults to True. :returns: a (return code, std out, std error) triplet :rtype: tuple of int, str, str """ import subprocess if cwd: #pylint: disable=consider-using-with process = subprocess.Popen( cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, close_fds=closeFds ) else: process = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=closeFds) stdout, stderr = process.communicate() return (process.returncode, stdout, stderr)
def calculate_polynomial_derivative_term(coefficient, variable, order): """Calculates the derivative of the nth order term of a polynomial. Args: coefficient (float): The coefficient of the nth order term in the polynomial variable (float): float to plug in for the variable in the polynomial order (int): order of the nth order term in the polynomial (so, n.) Returns: float: The result of taking the derivative of the nth order term a polynomial, :math:`n \\cdot \\text{coefficient} \\cdot \\text{variable}^{n-1}` So, the edge case of taking the derivative of the zeroth-order term is taken care of, since you explicity multiply by the order of the polynomial (which is zero in the n = 0 case.) Raises: TypeError: A non-integer was passed as the order. """ if type(order) != int: raise TypeError('Non-integer order in polynomial term') else: return order * coefficient * variable**(order - 1)
def stage_title(stage): """Helper function for setting the title bar of a stage""" stage_txt = ("Name", "Vocation", "Character Design and Details", "Stats and Skills", "All Done: Thank You!") stage_cmd = ("{w@add/name <character name>{n", "{w@add/vocation <character's vocation>{n", "{w@add/<field name> <value>", "{w@add/<stat or skill> <stat or skill name>=<+ or -><new value>{n", "{w@add/submit <application notes>") msg = "{wStep %s: %s" % (stage, stage_txt[stage - 1]) msg += "\n%s" % (stage_cmd[stage - 1]) return msg
def partition(length, parts): """des: Partitions 'length' into (approximately) equal 'parts'. arg: length: int, length of the Dataset parts: int, parts of the Dataset should be divided into. retrun: sublengths: list, contains length (int) of each part divided Dataset. """ sublengths = [length//parts] * parts for i in range(length % parts): # treatment of remainder sublengths[i] += 1 return sublengths
def get_fibonacci_list(target): """ returns fibonacci numbers upto less than the target and not including zero""" fib = [1, 1] while fib[-1] < target: fib.append(fib[-1] + fib[-2]) return fib[:-1]
def get_file_versions(digital_object): """Returns the file versions for an ArchivesSpace digital object. Args: digital_object (dict): Resolved json of an ArchivesSpace digital object. Returns: string: all file version uris associated with the digital object, separated by a comma. """ return ", ".join([v.get("file_uri") for v in digital_object.get("file_versions")])
def aws_event_tense(event_name): """Convert an AWS CloudTrail eventName to be interpolated in alert titles An example is passing in StartInstance and returning 'started'. This would then be used in an alert title such as 'The EC2 instance my-instance was started'. Args: event_name (str): The CloudTrail eventName Returns: str: A tensed version of the event name """ mapping = { "Create": "created", "Delete": "deleted", "Start": "started", "Stop": "stopped", "Update": "updated", } for event_prefix, tensed in mapping.items(): if event_name.startswith(event_prefix): return tensed # If the event pattern doesn't exist, return original return event_name
def listcollections(elvisresponse): """ Create a dictionary of 'data collections' in ELVIS. Input: a dictionary comprising the "available_data" element of an ELVIS response package Output: a dictionary like { 0 : "NSW Government", 1 : "ACT Government", ... 7 : "Geoscience Australia" } """ i = 0 collections = {} while i < len(elvisresponse): collections.update( {i : elvisresponse[i]["source"] } ) i+=1 return collections
def validate_int_list(char_list: list) -> bool: """ Verify that all values in the list are integers. :param text: :return: """ valid_int_list = True for element in char_list: if not element.isnumeric(): valid_int_list = False break return valid_int_list
def build_limit_clause(limit): """Build limit clause for a query. Get a LIMIT clause and bind vars. The LIMIT clause will have either the form "LIMIT count" "LIMIT offset, count", or be the empty string. or the empty string. Args: limit: None, int or 1- or 2-element list or tuple. Returns: A (str LIMIT clause, bind vars) pair. """ if limit is None: return '', {} if not isinstance(limit, (list, tuple)): limit = (limit,) bind_vars = {'limit_row_count': limit[0]} if len(limit) == 1: return 'LIMIT %(limit_row_count)s', bind_vars bind_vars = {'limit_offset': limit[0], 'limit_row_count': limit[1]} return 'LIMIT %(limit_offset)s, %(limit_row_count)s', bind_vars
def extract_label(line): """Extracts the English label (canonical name) for an entity""" if "en" in line["labels"]: return line["labels"]["en"]["value"] return None
def is_production_filename(filename): """Checks if the file contains production code. :rtype: bool :returns: Boolean indicating production status. """ return 'test' not in filename and 'docs' not in filename
def build_successors_table(tokens): """Return a dictionary: keys are words; values are lists of successors. >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.'] >>> table = build_successors_table(text) >>> sorted(table) [',', '.', 'We', 'and', 'bad', 'came', 'catch', 'eat', 'guys', 'investigate', 'pie', 'to'] >>> table['to'] ['investigate', 'eat'] >>> table['pie'] ['.'] >>> table['.'] ['We'] """ table = {} prev = '.' for word in tokens: if prev not in table: "*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***" prev = word return table
def _GetDefines(config): """Returns the list of preprocessor definitions for this configuation. Arguments: config: The dictionary that defines the special processing to be done for this configuration. Returns: The list of preprocessor definitions. """ defines = [] for d in config.get('defines', []): if type(d) == list: fd = '='.join([str(dpart) for dpart in d]) else: fd = str(d) defines.append(fd) return defines
def has_excel(pubdata): """ sets a display variable so that if there is an excel document, we can display a link to an excel reader :param pubdata: :return: pubdata """ pubdata['hasExcel'] = False if pubdata.get('links') is not None: for link in pubdata['links']: if link.get('linkFileType', {}).get('text') == 'xlsx': pubdata['hasExcel'] = True return pubdata
def ib(tb, r, a, b, c): """Chicago design storm equation - intensity before peak. Helper for i function. Args: tb: time before peak in minutes (measured from peak towards beginning) r: time to peak ratio (peak time divided by total duration) a: IDF A parameter - can be calculated from getABC b: IDF B parameter - can be calculated from getABC c: IDF C parameter - can be calculated from getABC Returns: Returns intensity in mm/hr. """ return a*((1-c)*tb/r+b)/((tb/r)+b)**(c+1)
def longest(s1, s2): """Return longest sorted string of distinct letters from two strings. input = 2 strings, characters are a-z output = 1 string, with distinct characters from both ex: a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy" """ concat = s1 + s2 set_up = set(concat) s_set_up = sorted(set_up) output = ''.join(s_set_up) return output
def parse_dashed_list(value: str): """ Parameters ---------- value: str string with 2 numbers separated by 1 dash Returns ------- list list from those 2 numbers or `None` if error occurred Examples -------- >>> parse_dashed_list('1-5') [1, 2, 3, 4, 5] """ dash_pos = value.find('-') if dash_pos != -1: s = int(value[:dash_pos]) t = int(value[dash_pos + 1:]) return list(range(s, t + 1)) return None
def pop_indices(lst, indices): """ pop the lst given a list or tuple of indices. this function modifies lst directly inplace. >>> pop_indices([1,2,3,4,5,6], [0,4,5]) >>> [2, 3, 4] """ for n in sorted(indices, reverse=True): lst.pop(n) return lst
def convert_version(version): """Convert a python distribution version into a rez-safe version string.""" """ version = version.replace('-','.') version = version.lower() version = re.sub("[a-z]", "", version) version = version.replace("..", '.') version = version.replace("..", '.') version = version.replace("..", '.') return version """ return str(version)
def quartiles_range(values): """Gets the upper and lower quartile from the list for statistics""" tmpvalues = sorted(values) entries = len(tmpvalues) # Interquartile range only makes sense for a sufficient amount of multiple values if entries > 3: if entries % 2 == 0: lower = int(entries * 0.25) upper = int(entries * 0.75) else: lower = int(entries * 0.25) + 1 upper = int(entries * 0.75) + 1 return tmpvalues[upper] - tmpvalues[lower] else: return 0
def join(fulllist, filterlist, complementary=False): """Using second list filter first list, return the intersection of two lists or complementary set of intersection with first list as universe. Keyword arguments: complementary -- return complementary set of intersection """ if not isinstance(fulllist, list) or not isinstance(filterlist, list): raise TypeError('Onlt support list at present.') fullset, filterset = set(fulllist), set(filterlist) intersection = fullset & filterset result = fullset - intersection if complementary else intersection return result
def select_regexp_char(char): """ Select correct regex depending the char """ regexp = '{}'.format(char) if not isinstance(char, str) and not isinstance(char, int): regexp = '' if isinstance(char, str) and not char.isalpha() and not char.isdigit(): regexp = r"\{}".format(char) return regexp
def simpleAddDictionaries(d1,d2): """ Add the elements of two dictionaries. Assumes they have the same keys. """ assert set(d1.keys()) == set(d2.keys()) return dict([ (key, d1[key]+d2[key]) for key in d1])
def r2h(rgb): """ Convert an RGB-tuple to a hex string. """ return '#%02x%02x%02x' % tuple(rgb)
def get_connection_types(itfs, dst, src, bidir, dominant_type=None): """ Gets the types of a connection depending on the source and destination types. Determines the overlapping "drives" and "receives" types for the destination and source respectively. If the connection is bidirectional then the "drives" and "receives" types of both destination and source are taken into account. >>> itfs = {} >>> itfs['et1'] = { 'receives': ['type_a'], 'drives': 'type_b' } >>> itfs['ap1'] = { 'receives': ['type_b', 'type_c'], 'drives': 'type_a' } >>> itfs['ap2'] = { 'drives': ['type_b', 'type_c'] } >>> get_connection_types(itfs, 'ap1', 'et1', bidir=False) ('type_a',) >>> get_connection_types(itfs, 'et1', 'ap1', bidir=False) ('type_b',) >>> get_connection_types(itfs, 'et1', 'ap1', bidir=True) ('type_a', 'type_b') >>> get_connection_types(itfs, 'ap2', 'ap1', bidir=False) ('type_b', 'type_c') >>> get_connection_types(itfs, 'ap2', 'ap1', bidir=False, dominant_type='type_c') ('type_c',) """ def get(itf, direction_types): if not direction_types in itf: return set() if isinstance(itf[direction_types], str): return set([itf[direction_types]]) return set(itf[direction_types]) driving_types = get(itfs[dst], "drives") receiving_types = get(itfs[src], "receives") if bidir: # If the connection is bidirectional we also take all the types # in the opposite direction into account driving_types.update(get(itfs[dst], "receives")) receiving_types.update(get(itfs[src], "drives")) if dominant_type in driving_types or dominant_type in receiving_types: # A dominant type will override any other types for the given connection return (dominant_type,) return tuple(sorted(driving_types & receiving_types))
def get_drift(x: int) -> int: """Returns an int if not zero, otherwise defaults to one.""" return int(x) if x and x != 0 else 1
def parse_submission_id(comment_url): """ Simple helper method which will parse the full url of the reddit page and find the submission_id only This is useful as it allows the user to enter only the partial url or just the submission_id in the form. -----params---- @comment_url - the url or submission id the user has passed into our form @return - just the parsed submission_id """ index_start = comment_url.find('comments') # assume user has passed in just the 6 character submission id, # if it's incorrect it will be caught by try catch in get_comments if(index_start == -1): return comment_url # parse submission id which will start 9 characters after comments keyword in the url # and is always 6 characters in length else: return comment_url[index_start+9:index_start+15]
def parse_instruction(raw_instruction): """ ABCDE (0)1002 DE - two-digit opcode, 02 == opcode 2 C - mode of 1st parameter, 0 == position mode B - mode of 2nd parameter, 1 == immediate mode A - mode of 3rd parameter, 0 == position mode, omitted due to being a leading zero :param raw_instruction: Assuming int value :return: op_code, param_1_mode, param_2_mode, param_3_mode, """ instruction = list(f"{raw_instruction:05}") op_code = int(''.join(instruction[3:5])) mode_1 = int(instruction[2]) mode_2 = int(instruction[1]) mode_3 = int(instruction[0]) return op_code, mode_1, mode_2, mode_3
def cm_to_EMU(value): """1 cm = 360000 EMUs""" return int(value * 360000)
def transform_to_range(val, old_min, old_max, new_min, new_max): """ Transform a value from an old range to a new range :return: scaled value """ old_range = (old_max - old_min) new_range = (new_max - new_min) new_val = (((val - old_min) * new_range) / old_range) + new_min return new_val