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 - c...
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. """ ...
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 ...
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, hom...
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 alp...
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...
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 als...
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 fu...
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 bi...
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 hoo...
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 @retu...
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 d...
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 T...
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 [...
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...
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]) ...
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 lette...
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 ...
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"...
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: r...
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)) ...
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][...
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) # ope...
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 :: ...
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] ...
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}, {st...
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: | ...
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: rul...
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 ...
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["re...
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 ...
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')): ret...
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]['c...
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][...
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 ...
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 an...
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, resou...
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(): ...
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): di...
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. I...
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 --...
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 T...
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...
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'], ...
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....
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...
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-...
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["...
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 dependin...
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)