content
stringlengths
42
6.51k
def get_ns(node): """Get Absolute namespace from node name string Args: node (str): Node name Returns: str: Absolute namespace """ parts = node.rsplit("|", 1)[-1].rsplit(":", 1) return (":" + parts[0]) if len(parts) > 1 else ":"
def create_ssl_config(certfile=None, keyfile=None, cafile=None, check_hostname=True, secure=True, ssl_context=None): """ Choose CertificateManager settings :param certfile: path of certfile - contains public key :param keyfile: path of keyfile - contains private key :param cafile: path of cafile - contains public key of other end of connection :param check_hostname: boolean corresponding to if client should check hostname of server-submitted certificate :param secure: boolean corresponding to if CertificateManager should secure socket; unless specifically desired, it is RECOMMENDED this is kept true. If set to false, any certificates provided will be ignored, no wrapping will occur if wrapping function is called :param ssl_context: """ settings = {"certfile": certfile, "keyfile": keyfile, "cafile": cafile, "check_hostname": check_hostname, "secure": secure, "ssl_context": ssl_context} return settings
def boolean(value): """Turn the given string value into a boolean. Any truthy value will be interpreted as True and anything else will be False. For convenience, this function will also accept a boolean value (and simply return it) and the value None, which will be interpreted as False. """ if isinstance(value, bool) or value is None: return bool(value) return value.lower() in ('true', 't', 'yes', 'y', '1')
def titled_table( title_str: str, table_str: str, symbol: str = "-", n_empty_start: int = 1, n_empty_end: int = 0, ) -> str: """ Adds an underlined title string to a given table string. The line, that underlines the title will be as long as the longest line of the table. Parameters ---------- title_str The title to be put on top of the table. table_str The string representing the table. For example generated using tabulate. symbol A single character the line should be 'made' of. n_empty_start Number of empty lines added before the title. n_empty_end Number of empty lines added after the table string. Returns ------- result_string An underlined title, followed by a table. """ # get the number of characters in the given table's longest line max_line_length = max([len(line) for line in table_str.split("\n")]) # now, simply concatenate the different lines result_string = ( n_empty_start * "\n" + title_str + "\n" + max_line_length * symbol + "\n" + table_str + "\n" + n_empty_end * "\n" ) return result_string
def check_option_log_in(val, home): """Check if Instagram Bot log in option is valid.""" try: # Change option to integer. val = int(val) # Check if option is in range. if val <= 0 or val > 5: print('Not an option, please try again.\n\n\n') return val, home home = False return val, home except ValueError: # Option is not an integer. home = True print('Please enter an integer 1-5.\n\n\n') return val, home
def br_compact_code(record_id, length=3, alphabet=None, prefix=""): """ Generate a compact code for a record ID Args: record_id: the record ID length: the minimum length of the code alphabet: the alphabet to use """ if not alphabet: # Default alphabet (Base 29 => ca. 700k codes with 4 digits) alphabet = "0123456789ABCDEFHJKLNQRSUVWXYZ" digits = [] base = len(alphabet) remainder = record_id while remainder: digits.append(alphabet[remainder % base]) remainder = remainder // base digits.reverse() code = "".join(digits) # Pad with leading "zeros" code = (alphabet[0] * length + code)[-(max(length, len(code))):] return "%s%s" % (prefix, code) if prefix else code
def cons(x, l): """ alpha * list[alpha] -> list[alpha] """ return [x] + l
def wordvector_distance(indices, class_wordvector_distances): """Get the distance of two class word vectors, given a pre-computed distance matrix. This can be used to determine edge weights between two batch graph nodes. Args: indices: the indices of the two classes. In the graph structure, the first index corresponds to the origin vertex and the second index corresponds to the destination vertex. Tensor of shape `[2]`. class_wordvector_distances: pre-computed class word vector distances for all the classes in the dataset. The matrix is symmetrical. Returns: the distances between the word vectors of the classes specified in `indices`. """ return class_wordvector_distances[indices[0]][indices[1]]
def escape_html(string: str, quote=True) -> str: """ Replace special characters "&", "<" and ">" to HTML-safe sequences. :param string: the string :param quote: If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. :return: the escaped string """ string = string.replace("&", "&amp;") # Must be done first! string = string.replace("<", "&lt;") string = string.replace(">", "&gt;") if quote: string = string.replace('"', "&quot;") string = string.replace("'", "&#x27;") return string
def is_component(func): """ Checks whether the @component decorator was applied to a function. Parameters ---------- func : function The function to be examined Returns ------- bool True if the decorator was applied, False if not Examples -------- See component(). """ try: if func._attributes['_pype_component']: return True else: return False except: return False
def chunks(l, n): """Split list l into n chunks as uniformly as possible.""" k, m = divmod(len(l), n) return [l[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)]
def swap_pair(num): """ Swap the bits in a binary representation of a number. :param num: The number. :return: returns the integer after swapping the bits of the initial number. """ # odd bit arithmetic right shift 1 bit odd = (num & int('AAAAAAAA', 16)) >> 1 # even bit left shift 1 bit even = (num & int('55555555', 16)) << 1 return odd | even
def get_images_urls(posts): """Returns a list of all the urls in the list of posts.""" return [post['URL'] for post in posts]
def thermal_stress(therex, K, nu, Tres, Twell): """Thermally induced stess [MPa] assuming a steady state has been reached In fractoolbox, tensile stress is -ve and compressive stress is +ve This convention means that Twell-Tres is used to find the deltaT and that thermal stress is added to the hoop stress calculations (eg the function effhoopstress). This is the opposite convection to to what is used in Zoback (2010) pp 174 eq 6.4. Args: therex (float): Coefficient of thermal expansion, which is typically 1.e-5 per Kelvin K (float): Bulk modulus, which is typically 1.e10 nu (float): Possions ratio, which is typically 0.25 Ensure that the elastic moduli (K & nu) are internally consistent Tres (float): Reservoir temperature in Kelvin Twell (float): Internal well temperature in Kelvin, which is typically ~40degC for a high-temperature geothermal well that was logged by a borehole imager under injection but this can be higher if well permeability is low Returns: float: Thermally induced stress (sigma_Dt) Function written by Irene using eq 7.150 P204 Jager et al (2007) """ sigma_Dt = ( ( 3 * therex * K * ((1 - 2 * nu) / (1 - nu)) * (Twell - Tres) ) / 1.e6) return sigma_Dt
def err(a: float, b: float) -> float: """Error function.""" return 0.5 * (a - b) ** 2
def listify(x): """Convert one element into a list of that element. No-op on list inputs.""" if not isinstance(x, (list, tuple)): return [x] else: return x
def get_last_update_id(updates): """Calculates the highest ID of all the updates we receive from getUpdates""" update_ids = [] for update in updates["result"]: update_ids.append(int(update["update_id"])) return max(update_ids)
def state_to_index(valuation, base): """ Maps states to an decimal integers. """ factor = 1 integer = 0 for i in range(len(valuation)): integer += factor * valuation[i] factor *= base return integer
def decimal_str_to_int(decimal_string): """ Helper to decimal currency string into integers (cents). WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param string The amount in currency with full stop decimal separator @return integer The amount in cents """ int_string = decimal_string.replace('.', '') int_string = int_string.lstrip('0') return int(int_string)
def limit(x): """Limit the argument to the range -1.0 to 1.0""" return max([-1.0, min([1.0, x])])
def almost_equals(x, y, threshold=10**(-5)): """Return True when two numerical values are equal up to the threshold.""" return abs(x - y) < threshold
def getModelFromData(data): """ get translation model from data - data consists of sets of point pairs (p,p') p' = p + (tx,ty) p = (x,y) p' = (x',y') the translation model is just [tx,ty] a translation matrix T would be [[1 0 tx] [0 1 ty]] """ sumdeltax = 0 sumdeltay = 0 if data is None: return None for pair in data: p = pair[0] pprime = pair[1] x = p[0] y = p[1] xprime = pprime[0] yprime = pprime[1] deltax = xprime-x deltay = yprime-y sumdeltax += deltax sumdeltay += deltay npairs = len(data) avgdeltax = float(sumdeltax) / npairs avgdeltay = float(sumdeltay) / npairs tx = avgdeltax ty = avgdeltay model = [tx, ty] return model
def strcol(col): """Regularize""" return col.lower().replace("-", "_").replace(" ", "_")
def append_slash(path): """Append a slash in a path if it does not end with one. Parameters ---------- path : str The directory name with its path. """ if not path.endswith('/'): path += '/' return path
def version_fulfills_request(available_version, requested_version): """ Return whether available_version fulfills requested_version. Both are dicts with 'major' and 'minor' items. """ # No requested major version is fulfilled by anything if requested_version['major'] is None: return True # If major version is requested, that at least must match if requested_version['major'] != available_version['major']: return False # Major version matches, if no requested minor version it's a match if requested_version['minor'] is None: return True # If a minor version is requested, the available minor version must be >= return ( available_version['minor'] is not None and available_version['minor'] >= requested_version['minor'] )
def param_row(param_keys, param_values): """ Returns a dict {param key: param value} """ values = list(param_values) return {k: values[i] for i, k in enumerate(param_keys)}
def polygonArrayToOSMstructure(polygon): """ polygonArrayToOSMstructure(polygon) With a polygon array gets structure of poly for OSM sql. Parameters ---------- polygon : Array Array that contains the poligon separated [[lat,long], [lat', long'], [lat'', long''], ...] same as [[y,x],[y',x'], [y'',x''], ...] representation of OSM return. Returns ------- String Returns the string asociated for OSM sqls (poly: ...). """ s = '(poly:"' for y, x in polygon[:-1]: s += str(x)+ ' '+ str(y)+' ' s += str(polygon[-1][1])+' '+str(polygon[-1][0]) +'")' return s
def title_score(title): """ check if python is in the title """ score = 0 if 'python' in title: score += 2 if title in {'Senior', 'Sr.', 'senior', 'sr.'}: score -= 2 return score
def getdminfo(dms): """Help function to create description of DM inputs.""" dminfo = ', '.join(str(d) for d in dms) return f"Reconstructed tau decay mode: {dminfo}"
def read_textfile(filepath): """ Read a whole file into memory as a string """ if filepath is None: return '' with open(filepath) as f: return ''.join(f.readlines())
def getitem_or_default(l, idx, default=None): """ gets the item at position idx or returns the default value :param list: list of things :param idx: position :param default: optional default value :return: thing at index idx or default """ try: return l[idx] except IndexError: return default
def personal_top_three(scores): """ Get the top 3 scores. :param scores list - List of scores :return list - Best 3 scores. """ scores.sort(reverse=True) topc = 3 top = [] if len(scores) < topc: topc = len(scores) for i in range(0, topc): top.append(scores[i]) return top
def _get_tag_of_type(typ, tags): """Selects all tags of pathways of a give tag """ return_tags = [] for tag in tags: if tag[0] == typ: return_tags.append(tag) return return_tags
def is_track(uri): """Returns True if the specified URI points to a spotify track.""" return uri.startswith("spotify:track:") or uri.startswith( "https://open.spotify.com/track/" )
def Option(cls): """Shorthand description for a type allowing NoneType""" return cls + (type(None),) if isinstance(cls, tuple) else (cls, type(None))
def key_exists(search_key: str, search_dict: dict): """Returns bool if a key exists at the top level of a dict""" return search_key in search_dict.keys()
def multi_bracket_validation(stringInput): """returns boolean, True for balanced brackets, false for not""" if type(stringInput) is not str: raise ValueError('Input a string!!') sharkTooth_counter = 0 square_counter = 0 parenthese_counter = 0 for letter in stringInput: if letter is '(': parenthese_counter += 1 elif letter is ')': parenthese_counter -= 1 elif letter is '[': square_counter += 1 elif letter is ']': square_counter -= 1 elif letter is '{': sharkTooth_counter += 1 elif letter is '}': sharkTooth_counter -= 1 final_counter = parenthese_counter + sharkTooth_counter + square_counter if final_counter == 0: return True else: return False
def column_widths(table): """Get the maximum size for each column in table""" return [max(map(len, col)) for col in zip(*table)]
def sent2tokens(sent): """ Returns a list of tokens, given a list of (token, pos_tag, label) tuples """ return [token for token, postag, label in sent]
def swap_blue_red(bs): """ Swap the blue and red channels in the image. """ new_bs = bytearray(bs) for i in range(0, len(bs), 4): new_bs[i] = bs[i+2] new_bs[i+2] = bs[i] return new_bs
def raw_seg_list(generate_test_segments): """A generic list of raw segments to test against.""" return generate_test_segments(["bar", "foo", "bar"])
def get_bool(value): """Convert string value to bool.""" if value is None: return if isinstance(value, bool): return value if value.lower() == "true": return True if value.lower() == "false": return False
def get_build_data(dsc, start_time, end_time, scm_url, owner): """ Return a dict of build information, for the CG metadata. """ # Technically, Debian packages just have "Source" (ie name) and "Version" # fields. name = '%s-deb' % dsc['Source'] # Nothing mandates that all Debian packages must have a "-" in the Version # field to split into Koji's concepts of "version" and "release". If we # come across this pattern in a package, arbitrarily set the "release" # value to "0" to satisfy Koji. try: version, release = dsc['Version'].split('-') except ValueError: version = dsc['Version'] release = '0' info = { 'name': name, 'version': version, 'release': release, 'source': scm_url, 'start_time': start_time, 'end_time': end_time, 'owner': owner, 'extra': { 'typeinfo': { 'debian': {}, }, }, } return info
def caesar_alpha_shuffle(shift): """Creates an array of the resulting alphabet after the caesar shuffle. Args: shift (int): The number of places to shift the alphabet. Returns: list: A list of the resulting alphabet after caesar shuffled. """ alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] for i in range(shift): for j in range(1, len(alphabet)): alphabet[0], alphabet[j] = alphabet[j], alphabet[0] return alphabet
def coord_to_string(x, y): """Convert a 2D coordinate to a string. Insert '/' between the coordinates to simplify the split operation when decoding. Return the string. """ return "{0}/{1}".format(x, y)
def _histint_sim(x, y): """ histogram intersection kernel compute the similarity between the dicts x and y with terms + their counts """ # get the words that occur in both x and y (for all others min is 0 anyways) s = set(x.keys()) & set(y.keys()) # nothing in common? if not s: return 0. return float(sum([min(x[word], y[word]) for word in s]))
def code(information:dict) -> str: """ input: item:dict = {"language":str,"text":str} """ return f"```{information['language'].replace(' ', '_')}\n{information['text']}\n```"
def get_bboxes_in_cropped_area(x, y, w, h, bboxlist): """Filter out bounding boxes within the given cropped area.""" bboxes = [] for item in bboxlist: # if xmin is greater or equal to x, if bbox is inside the crop if ((item[0] >= x) and (item[1] >= y) and (item[2] <= (x + w)) and (item[3] <= (y + h))): bboxes.append(item) else: continue return bboxes
def det3(A): """Compute the determinant of a 3x3 matrix""" if not (len(A) == 3 and len(A[0]) == 3): raise ValueError("Bad matrix dims") return ( A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]) )
def _revsbetween(repo, roots, heads): """Return all paths between roots and heads, inclusive of both endpoint sets.""" if not roots: return [] parentrevs = repo.changelog.parentrevs visit = heads[:] reachable = set() seen = {} minroot = min(roots) roots = set(roots) # open-code the post-order traversal due to the tiny size of # sys.getrecursionlimit() while visit: rev = visit.pop() if rev in roots: reachable.add(rev) parents = parentrevs(rev) seen[rev] = parents for parent in parents: if parent >= minroot and parent not in seen: visit.append(parent) if not reachable: return [] for rev in sorted(seen): for parent in seen[rev]: if parent in reachable: reachable.add(rev) return sorted(reachable)
def get_read_from_map_from_permutation(original, permuted): """With a permutation given by C{original} and C{permuted}, generate a list C{rfm} of indices such that C{permuted[i] == original[rfm[i]]}. Requires that the permutation can be inferred from C{original} and C{permuted}. .. doctest :: >>> for p1 in generate_permutations(range(5)): ... for p2 in generate_permutations(range(5)): ... rfm = get_read_from_map_from_permutation(p1, p2) ... p2a = [p1[rfm[i]] for i in range(len(p1))] ... assert p2 == p2a """ from warnings import warn warn("get_read_from_map_from_permutation is deprecated and will be " "removed in 2019", DeprecationWarning, stacklevel=2) assert len(original) == len(permuted) where_in_original = dict( (original[i], i) for i in range(len(original))) assert len(where_in_original) == len(original) return tuple(where_in_original[pi] for pi in permuted)
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: ? Space Complexity: ? """ if num == 0: raise ValueError if num == 1: return '1' if num == 2: return '1 1' else: arr = [0, 1, 1] for count in range(3, num + 1): next_num = arr[arr[count-1]] + arr[count-arr[count-1]] arr.append(next_num) count_and_say = ' '.join([str(number) for number in arr[1:]]) return count_and_say
def area_of_polygon(x, y): """Calculates the area of an arbitrary polygon given its verticies""" area = 0.0 for i in range(-1, len(x)-1): area += x[i] * (y[i+1] - y[i-1]) return abs(area) / 2.0
def format_txt_from_dict(resp_dict, apl_trans:str, id_plus_dir:str)->str: """Formats the entry for each prediction""" lines = [ id_plus_dir, apl_trans, resp_dict['transcript'], " ".join([str(round(conf, 4)) for conf in resp_dict['confidence']]), ' '.join([f"({word}, {str(round(conf, 4))})" for word, conf in resp_dict['words_confidence']]) ] return '\n'.join(lines)
def f(string, *args, **kwargs): """ Uses ``str.format`` for string interpolation. >>> {{ "{0} arguments and {x} arguments"|f('positional', x='keyword') }} "positional arguments and keyword arguments" """ return string.format(*args, **kwargs)
def listify_cleanup(value): """Clean up top level splicer_code Convert newline delimited strings into a list of strings. Remove trailing newline which will generate a blank line. Or replace None with "" in a list. Used with nested dictionaries used to mirror scopes. CXX_definitions: | // Add some text from splicer // And another line namespace: ns0: CXX_definitions: - // lines from explict splicer - namespace ns0 """ if isinstance(value, dict): new = {} for key, item in value.items(): new[key] = listify_cleanup(item) elif isinstance(value, str): new = value.split("\n") if value[-1] == "\n": new.pop() elif isinstance(value, list): new = ["" if v is None else v for v in value] else: new = [ str(value) ] return new
def distance(p1,p2): """Distance between two points p1 and p2 p1: (x1,y1,z1) p2: (x2,y2,z2)""" from numpy import asarray p1,p2 = asarray(p1),asarray(p2) from numpy.linalg import norm return norm(p2-p1)
def sortDictionaryByKey(directory): """ Sorts a dictonary by key in ascending order. """ import collections return collections.OrderedDict(sorted(directory.items()))
def get_id_from_url(url): """ Parameters ---------- url : Returns ------- """ split_by = '-' if '-' in url else '.' return url.split('/')[-1].split(split_by)[0]
def combine_posts(posts): """ Function to combine posts to single text :param posts: all posts by a user :return: (String) combined text """ combined_text = '.'.join(posts) return combined_text
def some_method(a1, a2): """ some_method returns the larger num :param a1: num1 :param a2: num2 :return: 1 or 2 """ if a1 > a2: return 1 elif a1 < a2: return 2 else: return 0
def _is_official_alert_rule_format(rules_dict: dict) -> bool: """Are alert rules in the upstream format as supported by Prometheus. Alert rules in dictionary format are in "official" form if they contain a "groups" key, since this implies they contain a list of alert rule groups. Args: rules_dict: a set of alert rules in Python dictionary format Returns: True if alert rules are in official Prometheus file format. """ return "groups" in rules_dict
def relationship_diff(current_items, new_items): """ To be used in POST and PUT/PATCH relationship requests, as, by JSON API specs, in update requests, the 'remove' items' relationships would be deleted, and the 'add' would be added, while for create requests, only the 'add' would be added. :param current_items: The current items in the relationship :param new_items: The items passed in the request :return: """ return { 'add': {k: new_items[k] for k in (set(new_items.keys()) - set(current_items.keys()))}, 'remove': {k: current_items[k] for k in (set(current_items.keys()) - set(new_items.keys()))}, }
def audit_secret_renewals(audit_events): """ Return the lease ids of all secret leases that have been renewed """ return [ ae["request"]["data"]["lease_id"] for ae in audit_events if ae["type"] == "request" and ae["request"].get("operation") == "update" and ae["request"].get("path") == "sys/leases/renew" ]
def calculateAlleleNumber(regionOfInterest,locus): """ Calulate alleleNumber for STR loci. Expects: a dictionary 'locus' with the same keys as LOCInames' columns, and the allele seq Expects allele regionOfInterest, i.c. flanked out allele based on locusDict[locus] This function is also used by Analysis. In case of stutterBuffer a correctionfactor is calculated. """ if not locus['locusType']: return None correctionFactor = 0 try: correctionFactor+=len(locus['removed_from_flank_forwardP']) correctionFactor+=len(locus['removed_from_flank_reverseP']) except KeyError: pass #correction not needed regionOfInterest=len(regionOfInterest) - correctionFactor if regionOfInterest == locus['ref_length']: alleleNumber = locus['ref_alleleNumber'] else: if '.' not in locus['ref_alleleNumber']: ref_length = int(locus['ref_length']) ref_alleleNumber = int(locus['ref_alleleNumber']) else: ref_length = (int(locus['ref_length'])- int(locus['ref_alleleNumber'][locus['ref_alleleNumber'].index('.')+1:])) ref_alleleNumber = int(locus['ref_alleleNumber'][:locus['ref_alleleNumber'].index('.')]) ref_difference = regionOfInterest - ref_length ref_offset = (regionOfInterest - ref_length )%locus['locusType'] alleleNumber = str( ref_alleleNumber + int(ref_difference/locus['locusType']) - (1 if (ref_difference<0 and ref_offset) else 0) ) #correction when regionOfInterest < ref_length if ref_offset != 0: alleleNumber += '.'+str((regionOfInterest - ref_length )%locus['locusType']) return alleleNumber
def have_binaries(packages): """Check if there are any binaries (executables) in the packages. Return: (bool) True if packages have any binaries, False otherwise """ for pkg in packages: for filepath in pkg.files: if filepath.startswith(('/usr/bin', '/usr/sbin')): return True return False
def get_concepts_beginning_end(cwk): """Given a continuous wikifier, return two dictionnaries associating for \ each concept the pageRanks at the beginning and at the end of the \ resource""" nb_chunks = len(cwk) beginning = {} for i in range(nb_chunks//4): for concept in cwk[i]['concepts']: if concept['title'] in beginning: beginning[concept['title']].append(concept['pageRank']) else: beginning[concept['title']] = [concept['pageRank']] end = {} for i in range(nb_chunks-nb_chunks//4, nb_chunks): for concept in cwk[i]['concepts']: if concept['title'] in end: end[concept['title']].append(concept['pageRank']) else: end[concept['title']] = [concept['pageRank']] return beginning, end
def apply_spline_subdivison_to_path(path, subdivision): """Apply spline subdivision to the list of points.""" spline = [] points = list(path) pointsNumber = len(points) # extend the points array points.append((points[pointsNumber - 1][0] + (points[pointsNumber - 1][0] - points[pointsNumber - 2][0]), points[pointsNumber - 1][1] + (points[pointsNumber - 1][1] - points[pointsNumber - 2][1]))) points.append((points[pointsNumber][0] + (points[pointsNumber][0] - points[pointsNumber - 1][0]), points[pointsNumber][1] + (points[pointsNumber][1] - points[pointsNumber - 1][1]))) pointMinus1 = (points[0][0] + (points[0][0] - points[1][0]), points[0][1] + (points[0][1] - points[1][1])) pointMinus2 = (pointMinus1[0] + (pointMinus1[0] - points[0][0]), pointMinus1[1] + (pointMinus1[1] - points[0][1])) # adding to the end is equivalent to index -1 and -2 points.append(pointMinus2) points.append(pointMinus1) # interpolation spline.append(points[0]) # first point for i in range(1, pointsNumber): # compute the third order coefficients coefficients = [] for j in range(2): coefficients.append([ (-points[i - 2][j] + 3 * points[i - 1][j] - 3 * points[i][j] + points[i + 1][j]) / 6.0, (3 * points[i - 2][j] - 6 * points[i - 1][j] + 3 * points[i][j]) / 6.0, (-3 * points[i - 2][j] + 3 * points[i][j]) / 6.0, (points[i - 2][j] + 4 * points[i - 1][j] + points[i][j]) / 6.0 ]) for j in range(subdivision): t = float(j + 1) / subdivision spline.append(((coefficients[0][2] + t * (coefficients[0][1] + t * coefficients[0][0])) * t + coefficients[0][3], (coefficients[1][2] + t * (coefficients[1][1] + t * coefficients[1][0])) * t + coefficients[1][3])) return spline
def is_input(port): """Judge whether the port is an input port.""" try: return port.mode == 'r' except Exception: return False
def factorial_iterative(num): """ Calculates factorial of a given number Uses iterative approach :param num: the number to calculate the factorial :return: the factorial result """ if num == 0: return 1 factorial = 1 for i in range(1, num + 1): factorial = factorial * i return factorial
def has_won(bag, result): """Tell whether the user has won or not. It takes 5 rocks in the bag to win.""" if bag != {}: if bag["rock"] == 5: print("") print("Your bag starts rumbling and the rocks rise into the air and form a circle which gets larger and turns into a portal! You step through and find yourself in your own backyard again!") print("") print("CONGRATULATIONS! YOU WON!") print("") result = True return result
def backend_http_settings_id(subscription_id, resource_group_name, appgateway_name, name): """Generate the id for a http settings""" return '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/applicationGateways/{2}/backendHttpSettingsCollection/{3}'.format( subscription_id, resource_group_name, appgateway_name, name )
def contrast(lum1, lum2): """Get contrast ratio.""" return (lum1 + 0.05) / (lum2 + 0.05) if (lum1 > lum2) else (lum2 + 0.05) / (lum1 + 0.05)
def ordc(c): """ Compressed version of ord that returns indices between 0 and 95. """ c = ord(c) if c < 32 or c > 126: return 95 else: return c - 32
def getPrice(receipt): """ input: receipt - text of the receipt output: last price in the receipt in pence if found, empty string othrwise """ noDigits = 0 price = '' pos = receipt.rfind('GBP') + 3 while (noDigits < 3) & (pos < len(receipt)): if receipt[pos].isdigit(): price += receipt[pos] noDigits += 1 pos += 1 if noDigits < 3: return '' return price
def part1(adapters): """ Find adapters with jolt diff of 1 and 3 """ adapters.sort() adapters.insert(0, 0) # add 0 at start for the wall jolt adapters.append(max(adapters) + 3) # adding phone's inbuilt adapter diff_of_one = 0 diff_of_three = 0 for i in range(len(adapters) - 1): diff = adapters[i + 1] - adapters[i] if diff == 1: diff_of_one += 1 elif diff == 3: diff_of_three += 1 return diff_of_one * diff_of_three
def wang_ind(x, a, b): """Wang method: indicator fucntion of interval.""" return (x >= a) * (x <= b)
def addHello(a_string): """assumes that a_string is a string returns a string, "hello, " + string""" return "Hello, " + a_string
def _constant_time_compare(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when they have different lengths. Since Django only uses it to compare hashes of known expected length, this is acceptable. """ if len(val1) != len(val2): return False result = 0 for x, y in zip(val1, val2): result |= ord(x) ^ ord(y) return result == 0
def isUniversityEmail(email): """ Checks if the person has a university of windsor email """ return email.lower().endswith('@uwindsor.ca')
def make_ratios(cred, cgreen, cblue): """ get ratios of colors """ maxcolor = max(cred, cgreen, cblue) return float(cred)/float(maxcolor), \ float(cgreen)/float(maxcolor), \ float(cblue)/float(maxcolor)
def calc_dh(DTheta, F0, rho, cp, dt): """Gets change in height for a change in time per phil's notes? Arguments: DTheta -- change in potential temperature, K F0 -- surface heat flux, w/m2 rho -- density of air, kg/m3 cp -- heat capacity of air dt -- change in time, s Returns: dh -- change in height, m """ dh = 1.0*(dt)*((0.2*F0)/(rho*cp*DTheta)) return dh
def twos_complement(hex: str, bits: int) -> int: """compute the 2's complement of int value val""" val = int(hex, 16) if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val
def truncate_experiences(lst): """ truncate experience based on a boolean list e.g., [True, False, False, True, True, False] -> [0, 3, 4, 6] (6 is dummy) """ batch_points = [i for i, x in enumerate(lst) if x] batch_points.append(len(lst)) return batch_points
def isNumber(str_val): """ A function which tests whether the input string contains a number of not. """ try: float(str_val) # for int, long and float except ValueError: try: complex(str_val) # for complex except ValueError: return False return True
def format_atom_comment(options: dict, idx: int) -> str: """ render an optional end-of-line comment after a regular atom :param options: option dict :param idx: index :return: '' if terse else str(idx) """ if options["terse"]: return "" return str(idx)
def _flatten_nested_list(x): """ Flatten nested list Argument -------- x : list nested list with different leveling of different objects Returns ------- flatten version of list """ out = [] for xi in x: if type(xi) is list: out += _flatten_nested_list(xi) else: out.append(xi) return out
def value_similar_to(val, lst, thresh): """ Check if a value is close to some lst of values within some threshold """ return any(abs(val - vali) < thresh for vali in lst)
def ssr_to_ss(ssr_obj, rewrite=None): """ Convert ssr dict to ss dict :param ssr_obj: :param rewrite: :return: """ # for key, val in rewrite.items(): # rewrite_obj[key] = val ss = { 'server': ssr_obj['server'], 'server_port': ssr_obj['server_port'], 'method': ssr_obj['method'], 'password': ssr_obj['password'], 'remarks': ssr_obj['remarks'] } if rewrite: rewrite_obj = {} available_keys = ['server', 'server_port', 'method', 'password'] for key, val in rewrite.items(): if key in available_keys: rewrite_obj[key] = val ss.update(rewrite_obj) return ss
def getfullURL(date): """Returns Congressional Record URL (of PDF record) for a given date.""" base_url = "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf" return base_url
def _validate_template_folder(template_folder): """ Validates the given `template_folder` value. Parameters ---------- template_folder : `None` or `str` The template folder's value. Returns ------- template_folder : `None` or `str` The template folder's validated value. Raises ------ TypeError If `template_folder` was not given neither as `None` or `str` instance. """ if template_folder is not None: if type(template_folder) is str: pass elif isinstance(template_folder, str): template_folder = str(template_folder) else: raise TypeError( f'`template_folder` can be given as `str` instance, got ' f'{template_folder.__class__.__name__}.' ) if not template_folder: template_folder = None return template_folder
def get_y_vals(signal, pvc_indexes): """ obtains y-coordinates of PVC locations :param signal: the original ECG signal :param pvc_indexes: the x-coordinates of the detected PVCs :return: array of y-coordinates """ pvc_y_vals=[] for i in range(0, len(pvc_indexes)): pvc_y_vals.append(signal[pvc_indexes[i]]) return pvc_y_vals
def pass_3(model_kit, file_model_info, extra): # rename """ modify the key name - remove "bandai-" - remove "-bandai" - change "hguc-" to "hg-" - add key-name to the product-line['title'] """ replace_list = [ ('pre-order-', ''), ('bandai-', ''), ('-bandai', ''), ('hguc-', 'hg-'), ('bb-', ''), ('cross-silhouette-', 'cs-'), ('-model-kit', ''), ('model-kit-', ''), ('sd-gundam-', 'sd-'), ('hobby-', ''), ('realistic-model-', ''), ('master-grade-', 'mg-'), ] updated_model_kit = model_kit.lower() for pair in replace_list: to_replace = pair[0] replacement = pair[1] updated_model_kit = updated_model_kit.replace(to_replace, replacement) file_model_info.get('title', []).insert(0, updated_model_kit) return updated_model_kit, file_model_info
def fix_indentation(text): """Replace tabs by spaces""" return text.replace('\t', ' '*4)
def sized(y) -> bool: """Check whether or not an object has a defined length. Parameters ---------- value : Input object. type : object y : """ try: len(y) except TypeError: return False return True
def format_score(judge_no, request): """ need to improve in this module """ score = {} tec_first = int(request["technical_merit_first"]) tec_second = int(request["technical_merit_second"]) pre_first = int(request["presentation_first"]) pre_second = int(request["presentation_second"]) score["score"] = {} score["score"]["technicalmerit"] = tec_first * 10 + tec_second score["score"]["presentation"] = pre_first * 10 + pre_second # Undecidion how to read below data. score["contest_no"] = 1 score["player_no"] = 2 score["skating_no"] = 2 score["judge_user"] = judge_no return score["score"]
def is_valid_smb_hidden_files(smb_hidden_files): """ Validates smbhiddenfiles NAS volume parameter. String should be forward slash (/) delimited. :type smb_hidden_files: str :param smb_hidden_files: The smbhiddenfiles parameter to be validated. :rtype: bool :return: True or False depending on whether smb_hidden_files passes validation. """ if smb_hidden_files is None: return False if not smb_hidden_files.startswith("/") or \ not smb_hidden_files.endswith("/"): return False return True
def song(json): """Extract the song from a TikTok url. :param json json: Parsed JSON of the TikTok video's HTML page. :rtype: str :returns: TikTok song. """ return json["props"]["pageProps"]["itemInfo"]["itemStruct"]["music"]["title"]
def hierarchical_name_variants(h_name: str): """ Given a hierarchical name, obtain variants :param h_name: :return: An ordered list of names that may refer to the same object """ parts = h_name.split(".") if len(parts) > 1: return [h_name, parts[-1]] else: return [h_name]
def first(collection, match_function): """ Returns the first item in the collection that satisfies the match function """ return next((item for item in collection if match_function(item)), None)