content
stringlengths
42
6.51k
def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(fil...
def convert_to_bcd(decimal): """ Converts a decimal value to a bcd value :param value: The decimal value to to pack into bcd :returns: The number in bcd form """ place, bcd = 0, 0 while decimal > 0: nibble = decimal % 10 bcd += nibble << place decimal /= 10 place...
def _inject_args(sig, types): """A function to inject arguments manually into a method signature before it's been parsed. If using keyword arguments use 'kw=type' instead in the types array. sig the string signature types a list of types to be inserted Returns the altered...
def separate_elements(array): """splits the strings, delimited by whitespace in the provided list and adds each newly formed string to the returned list""" list_a = [] for element in array: list_a.extend(element.split(" ")) return list_a
def react_polymer(polymer): """Return polymer after all unit reactions have taken place.""" prev_poly = None while prev_poly != polymer: prev_poly = polymer for letter in 'abcdefghijklmnopqrstuvwxyz': upper = letter.upper() polymer = polymer.replace('{}{}'.format(lett...
def prepend_str(base_word: str, prepend: str, separator: str='') -> str: """Inserts str:prepend at beginning of str:base_word with default str:separator='', returns a str """ return f'{prepend}{separator}{base_word}'
def html_abstract_check(agr_data, value): """ future: check a database reference does not have html in the abstract :param agr_data: :param value: :return: """ if 'abstract' in agr_data: assert agr_data['abstract'] == value if agr_data['abstract'] == value: retu...
def is_upper(character): """ Returns True if the character is upper case and False if it is not a single character (a string with a length longer than one) or it is lower case. """ try: assert len(character) == 1 except: return False val = ord(character) if val >= 6...
def stringify_list(cols): """ Returns list with elements stringified """ return [str(c) for c in cols]
def add_with_saturation_bad(a, b, c=10): """add_with_saturation add with saturation as 25 to avoid bug. Otherwise it does not work and crash later. """ if c < 0: raise Exception('No.') return min(a+b, c)
def get_affected_future_frames(dialogue, from_turn_id, slot_name, slot_value, service): """ determine for all turns starting from from_turn_id if they contain the given combination of slot_name, slot_value, service if so, return affected List[(turn_id, frame_id, slot_name)] """ assert isinstance(fro...
def parse_subcommand(command_text): """ Parse the subcommand from the given COMMAND_TEXT, which is everything that follows `/iam`. The subcommand is the option passed to the command, e.g. 'wfh' in the case of `/pickem wfh tomorrow`. """ return command_text.strip().split()[0].lower()
def prune_a_loads(tlrfiles): """ When there are B or later products, take out the A loads. This is where most mistakes are removed. (CURRENTLY THIS FUNCTION IS NOT USED). """ outs = [] last_monddyy = None for tlrfile in reversed(tlrfiles): monddyy, oflsv = tlrfile.split('/')[-3:-1]...
def read_nalu_size(data, length_size): """Read nalu size.""" result = 0 for i in range(length_size): v = data[i] if type(v) == str: v = ord(v) result |= v << ((length_size - 1) - i) * 8 return result
def func(x, a, b): """ Model function for non linear regression fit. Function used by scipy.optimize.curve_fit method to calculate a and b coefficients minimizing squared error given independent and dependent variables. Parameters ---------- x : float Independent variable of no...
def dim_mul(dims1, dims2): """Create a new dimensionality for the multiplication of dims1 by dims2. :param dims1: Numerator dimensions. :type dims1: ``tuple`` :param dims2: Other numerator dimensions. :type dims2: ``tuple`` :rtype: ``tuple`` """ return ( dims1[0] + dims2[0], ...
def say_hi(name): """Take input name as string. Returns output.""" return f"Hello! {name}"
def right_index(i): """Vrati index praveho potomka prvku na pozici 'i'.""" return i * 2 + 2
def hex2int(arg_hex): """ Return hex value from integer values """ return int(arg_hex, 16)
def filt_first_arg(list_, func): """Like filt_first but return index (arg) instead of value""" for i, x in enumerate(list_): if func(x): return i return None
def getOption(arg): """ Stub function, set PshellServer.py softlink to PshellServer-full.py for full functionality """ return (False, "", "")
def get_postal_code(click_data: dict) -> str: """ Helper function for the callbacks Gets postal code from map click_data. --- Args: click_data (dict): user click information Returns: postal_code (str): Area postal code. '00180' by default. """ # try to find the area b...
def find(predicate, array): """ find_.find(list, predicate, [context]) Alias: detect Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined if no value passes the test. The function returns as soon as it finds an acceptable element, and d...
def stack_to_project(translation, resolution, coords_s): """Convert a dictionary of stack coordinates into a dictionary of project coordinates""" return {dim: val * resolution[dim] + translation[dim] for dim, val in coords_s.items()}
def ReassginmentError(original): """ This function takes in the original value of a variable, checks and makes sure its value is None if it is not None, then the value is trying to be reassigned and an error is raised :param original: The original value of the variable :type any type :return: bo...
def choose(n, seq): """ Return all n-element combinations of elements from seq >>> len(choose(5, [1,2,3,4,5,6,7])) 21 """ if n == 1: return [[x] for x in seq] if len(seq) <= n: return [seq] subseq = seq[:] elem = subseq.pop() return [[elem] + comb for comb in...
def calculate_average(list_of_nums): """Calculates the average of a list of numbers.""" total = 0 ### Set a breakpoint here! ### for num in list_of_nums: total += num average = total / len(list_of_nums) return average
def _offset(source, sink): """Finds common prefix, if any, and returns offset after alignment.""" if not sink: return 0 if isinstance(sink, list): sink = ''.join(sink) if isinstance(source, set): if sink[0] in source: return 1 return -1 source_length = len(source) sink_length = len(sin...
def _link(label, url): """Creates a markdown link. Args: label: The label for the link as a `string`. url: The URL for the link as a `string`. Returns: A markdown link as a `string`. """ return "[{label}]({url})".format( label = label, url = url, )
def call_from_global(func, *args, **kwargs): """ A supporting global function that calls the specified function with the specified arguments and keyword arguments. This is used by the test cases so that this function acts as a caller for the decorated API function. """ return func(*args, **kwarg...
def _config_get_list(list_string): """Convert list as string to list. :type list_string: list :param list_string: List as string. :returns: List of strings. """ l = [f.strip() for f in list_string[1:-1].split(",")] return l
def is_rule_in_set(rule, rule_list): """Check if the given rule is present in the rule_list :param rule_list: list of existing rules in dictionary format :param rule: new rule to be added :return boolean: """ for old_rule in rule_list: if rule['source'] == old_rule['source']\ ...
def _prepare_for_search(input_str): """ Ensures that no consecutive stars ('*') are in the search term to work with Path.rglob. Parameters ---------- input_str : str A string that will be used for file searching. Returns ------- str The input string containing no consec...
def _normalize_rate( in_rate: float ) -> float: """ Normalizes a frame rate float to one of the standard rates """ return round(in_rate * 1001)/1001
def check_palindrome(string): """ Check if the given string can be rearange as a palidnrome and if so, give a palidrome O(n) time for n long string O(n) space, worst case """ dico = {} for letter in string: dico[letter] = dico[letter]+1 if letter in dico else 1 palindrome = '' even = '' for k,v in di...
def rgb_html(r=0, g=0, b=0): """Converte R, G, B em #RRGGBB""" return '#%02x%02x%02x' % (r, g, b)
def is_close(first, second, rel_tol=1e-09, abs_tol=0.0): """ Almost equality for float numbers :param first :param second :param rel_tol: relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference ...
def parse_dining_items(eatery): """Parses the dining items of an eatery. Returns an array of the items an eatery serves and a flag for healthy options. Exclusive to non-dining hall eateries. Args: eatery (dict): A valid json dictionary from Cornell Dining that contains eatery information "...
def strtonum(value): """ For numbers 0 to 9, return the number spelled out. Otherwise, return the number. This follows Associated Press style. This always returns a string unless the value was not int-able, unlike the Django filter. Taken from: https://github.com/jmoiron/humanize/blob/master/humani...
def hflip_augment(is_training=True, **kwargs): """Applies random horizontal flip.""" del kwargs if is_training: return [('hflip', {})] return []
def max_contig_sum(L): """ L, a list of integers, at least one positive Returns the maximum sum of a contiguous subsequence in L """ sizeL=len(L) max_so_far,max_ending_here=0,0 for i in range(sizeL): max_ending_here+=L[i] if max_ending_here<0: max_ending_here=0 el...
def check_characters(text): """ Method used to check the digit and special character in a text. Parameters: ----------------- text (string): Text to clean Returns: ----------------- characters (dict): Dictionary with digit and special characters ...
def mean(numbers): """ Finds the mean of a list of numbers. """ return sum(numbers) / len(numbers)
def possibilities_count(sum_, dice_amount) -> int: """ Returns the total count of possibilities for a given sum and number of dice using lru_cache. Better than storing all the possible combinations in a list. It can even be used for more number of dices. """ poss_count = 0 if dice_amoun...
def h_index(citations): """ Calculate the H-index https://en.wikipedia.org/wiki/H-index :param citations: list of citations (sorted or unsorted) """ c = list(citations) c.sort(reverse=True) for i in range(len(c)): if i > c[i]: return i return len(c)
def set_name_q(name_q, q): """Set the external instrument names in regression; return generic name if user provides no explicit name." Parameters ---------- name_q : string User provided instrument names. q : array Array of instruments Re...
def nrmsd(a, b): """Return Normalized Root-Mean-Square Difference.""" return 200 * abs(a - b) / (abs(a) + abs(b))
def decrypt(sk, c): """Decrypt a cyphertext based on the provided key.""" return (c % sk) % 2
def _consume_until_marker(it, marker): """ Consume data from the iterator, until marker is found (compared using operator `is`). Returns tuple of number of elements consumed before the marker and bool indicating whether the marker was found (False means the iterator was exhausted. """ i = -1 ...
def int_or_none(var): """ Trys to convert 'var' into an integer. Returns None if an TypeError occures. """ try: return int(var) except (TypeError, ValueError): return None
def get_range_0(size): """returns a range spanning from 0 to size-1 size -- number of elements in the range """ return range(0, size)
def inflate(data, model, is_collection: bool): """ Handles deserializing responses from services into model objects.""" if data is None: return None if model is not None and hasattr(model, '_from_dict'): if is_collection: if isinstance(data, list): return [model._...
def jaccard(set_one: list, set_two: list) -> float: """ Calculate Jaccard score for input lists :param set_one: A list of graph nodes -> part one :param set_two: A list of graph nodes -> part two :return: Jaccard score """ intersection = len(set(set_one) & set(set_two)) union = len(set(s...
def parseUniprotLine(line): """ Parse a uniprot fasta file line, returning the uniprot id and species. This is a rather hacked parser that is brittle to changes in the default uniprot fasta file header. """ cols = line.split("|") uniprot_id = cols[1] description = cols[2] specie...
def linear_interpolation_01(x, values): """Interpolate values given at 0 and 1. Parameters: x : float y : float points : (v0, v1) values at 0 and 1 Returns: float interpolated value """ return values[0] * (1 - x) + values[1] * x
def exp(root,power): """ root^power returns string of equation""" base = " x ".join(str(root)*power) print( chr(ord('c'))) return f"{base} = {pow(root,power)}"
def colons_to_spaces(s): """ replaces colons in text with spaces :param s: :return: """ return " ".join(s.split("-"))
def get_interface_type(interface): """Gets the type of interface, such as 10GE, ETH-TRUNK...""" if interface is None: return None iftype = None if interface.upper().startswith('GE'): iftype = 'ge' elif interface.upper().startswith('10GE'): iftype = '10ge' elif interfac...
def to_str(bytes_or_string): """if bytes, return the decoded string (unicode here in python3). else return itself""" if isinstance(bytes_or_string, bytes): return bytes_or_string.decode('utf-8') return bytes_or_string
def ratiosFitness(ratios): """ Return a balance score between 0 and 1 1 means the dataset is well balanced, for example [0.5, 0.5, 0.5, 0.5] """ score = 0 for u in range(len(ratios)): current = ratios[u] current = abs(0.5 - current) current = current / 0.5 score += current score = score / len(ratios) ...
def camel_case_to_lower_case_underscore(string): """ Split string by upper case letters. F.e. useful to convert camel case strings to underscore separated ones. @return words (list) """ words = [] from_char_position = 0 for current_char_position, char in enumerate(string): if...
def formatFileName(serializableName: str)->str: """ Formats an AbstractJsonSerialable's name (or any string for that matter) into an appropriate file name """ return serializableName.replace(" ", "_") + ".json"
def n_filters(stage, fmap_base, fmap_max, fmap_decay): """Get the number of filters in a convolutional layer.""" return int(min(fmap_max, fmap_base / 2.0 ** (stage * fmap_decay)))
def capitalize(string: str) -> str: """ Capitalizing the string, assuming the first character is a letter. Does not touch any other character, unlike the `string.capitalize()`. """ return string[:1].upper() + string[1:]
def _validate_port_number(port_number): """Validate port number. Parameters ---------- port_number : int Supplied port number. Returns ------- int Valid port number. Raises ------ TypeError If `port_number` is not of type int. ValueError If ...
def isMEME_ff(motif_file): """ Check if the given file is in .meme format ---- Parameters: motif_file (str) : path to the motif file ---- Returns: (bool) """ if motif_file and isinstance(motif_file, str): ff = motif_file.split('.')[-1]...
def instance_group(group_type, instance_type, instance_count, name=None): """ Construct instance group :param group_type: instance group type :type group_type: ENUM {'Master', 'Core', 'Task'} :param instance_type :type instance_type: ENUM {'g.small', 'c.large', 'm.medium', 's.medium', 'c.2xlar...
def _make_constituency_url(state, constituency): """ Generates a URL for a constituency. """ return r"http://eciresults.nic.in/Constituencywise" \ r"S%d%d.htm?ac=%d" % (state, constituency, constituency)
def calc_tp_tn(actual, predicted, sensitive, unprotected_vals, positive_pred): """ Returns true positive and true negative for protected and unprotected group. """ tp_protected = 0.0 tp_unprotected = 0.0 tn_protected=0.0 tn_unprotected=0.0 for i in range(0, len(predicted)): prote...
def clamp(value, min=0, max=255): """ Clamps a value to be within the specified range Since led shop uses bytes for most data, the defaults are 0-255 """ if value > max: return max elif value < min: return min else: return value
def to_uri(bucket: str, key: str) -> str: """Construct a S3 URI. Args: bucket: The S3 bucket name. key: The S3 key. Returns: A S3 URI in the format s3://bucket/key. """ return f's3://{bucket}/{key}'
def flatten_friends_ids(users): """Returns a list of unique user IDs for the friends of a group of users users: dict of user profiles (as returned by crawl_friends) """ friends_ids = [] for user_id in users: friends_ids.extend(users[user_id]["friends_ids"]) return list(s...
def same_base_index(a, b): """Check if the base parts of two index names are the same.""" return a.split("_")[:-1] == b.split("_")[:-1]
def inorder_traversal(root): """ in order traversal input: root node of a binary tree output: array of values """ results = [] stack = [] node = root while stack or node: if node: stack.append(node) node = node.left else: node = st...
def dq_check_passfail(rule_results): """ Check the data quality results. All-or-nothing pass or fail based on all rules in the ruleset. """ list_of_status = [x["status"] for x in rule_results] # True if all rules pass, False if any rule fails return all(x == "SUCCEEDED" for x in list_of_st...
def view_complete(value): """ Append necessary request values onto the url. """ return "{}?view_adult=true&view_full_work=true".format(value)
def hasUser(user, data): """ Check if user is on config/users.json and save user object on result if found """ result = [i for i in data['users'] if i == user] return True if len(result)>0 else False
def IsIdenticalTopology(Nterm1, Nterm2, numTM1, numTM2, posTM1, posTM2, #{{{ topo1, topo2, min_TM_overlap = 5): """Check whether topo1 and topo2 are identical""" # Created 2011-11-15, updated 2011-11-15 # Two topologies are considered identical (Krogh et al. 2001) if # 1. numTM1 == numTM2 # 2. Each helix o...
def interpret_as_bool(value) -> bool: """ computes boolean from text, different forms are allowed, fallback: False """ return value.lower() in ['true', 't', 'y', 'yes', 'yeah']
def list_as_range_string(consecutive_values): """ Format a single-range string from a list of consecutive values. :param consecutive_values: List of consecutive values :return: """ if not isinstance(consecutive_values, list): consecutive_values = list(consecutive_values) if len(conse...
def chunk(obj, max_length): """ A wrapped recursive function to chunk a list/string/... into pieces under a certain length/size, i.e. given a very long string, break it into numerous smaller strings, all under max_length: $ result = utils.chunk(["aa bb cc dd ee ff gg", ], 0, 5) $ ['aa bb', ' cc d', 'd ee ', '...
def _subs(count: int) -> str: """DRY.""" return f'{count} validation error{"" if count == 1 else "s"} for Document'
def What_Season_Is_This(val): """ Maps day of month """ if val in [12,1,2]: return 2 # heating season elif val in [6,7,8]: return 0 # cooling season else: return 1
def arithmetical_expr(cont_frac, with_spaces=True, force_floats=False): """Generates the arithmetical expression as string of a continued fraction. The string is ready to be evaluated by a functions like `eval()` or by other programming languages or calculators. Beware of integer division instead of tr...
def convertPatternsToRegexp(patterns): """Converts multiple file name patterns to single regular expression""" import fnmatch import re if not patterns: return None fullRe = "" for pattern in patterns: reStr = fnmatch.translate(pattern) if fullRe: fu...
def xsplit(l, x): """ xsplit function. Split a string separate with blank space and return the x first members of the list. :param l: must be a string separate with blank space :param x: must be an integer :return: return the x first members of the list :rtype: <str> """ if x >= 0 and x < len(l): return...
def distance(a, b): """Calculates Manhattan distance between two coordinates.""" return abs(a[0] - b[0]) + abs(a[1] - b[1])
def binary_search_recur(array, low, high, val): """ Worst-case Complexity: O(log(n)) reference: https://en.wikipedia.org/wiki/Binary_search_algorithm """ if low > high: # error case return -1 mid = (low + high) // 2 if val < array[mid]: return binary_search_recur(arra...
def create_redis_compose_node(name): """ Args: name(str): Name of the redis node Returns: dict: The service configuration for the redis node """ return { "container_name": name, "image": "redis:3.2.8", "command": "redis-server --appendonly yes", "deplo...
def find_score(listOfWords): """returns a list of scores based on a list of words listOfWords --> totalScores""" scores = {3: 1, 4: 1, 5: 2, 6: 3, 7: 5, 8: 11, 9: 11, 10: 11, 11: 11, 12: 11, 13: 11, 14: 11, 15: 11, 16: 11} totalScores = [] for word in listOfWords: totalScores.append(sco...
def arch_url(hostname, port, ext): """ Return the base url for a particular archiver service. Parameters ---------- {hostname} port : int port on host that has the ext directory ext : string directory that hosts the desired service """ return "http://" + hostname + "...
def code_to_chars(code): """Convert each numeric code to its corresponding characters""" return '\033[' + str(code) + 'm'
def charToString(charArray): """ Takes an array of chars and returns the corresponding string.""" result = "" for i in charArray: result += i.decode("UTF-8") return result
def get_resource_type(resource_id): """Returns resource type""" lookup = {0: "VM", 1: "Public IP", 2: "Volume", 3: "Snapshot", 4: "Template", 5: "Projects", 6: "Network", 7: "VPC", 8: "CPUs", ...
def attr(obj, key): """ A simple method to get the attribute of an object or a dictionary. This avoids complex statements like: `obj.something.another_thing["something"].another_thing["more"]` to just `attr(obj, "something.another_thing.something.another_thing.more")` :param obj: The object ...
def get_roadside_config(config:dict): """ takes a config dictionary and returns the variables related to roadside deployment (push to server). If there is any error in the configuration, returns a quadruple of -1 with a console output of the exception """ try: server = config["DataTransfer"]...
def _flatten(lst): """ flatten a nested list of lists or values """ return sum(([x] if not isinstance(x, (list, tuple)) else _flatten(x) for x in lst), [])
def sort_recursive(arr, n): """Sorts the array using Insertion Sort Recursively Params: arr: the array to be sorted n: the number of elements to be sorted starting from the left """ # Base Case will do nothing if n <=1: return None sort_recursive(arr, n-1) i...
def get_engine_size(t): """ Function to get engine size """ tt = t.split(" ")[0].split('l') tt = tt[0] return tt
def move(cycle): """ Push last element of cycle to first position :param cycle: One cycle of permutation in cycles notation :type cycle: list :return: Returns moved cycle :rtype: list """ cycle.insert(0, cycle[-1]) cycle.pop(-1) return cycle