content
stringlengths
42
6.51k
def ten(value): """Return whether value is below ten. Args: value (int): A number. Returns: bool: Whether `value` is less than ten. """ if (value < 10): return True else: return False
def calculate_inst_vel(x_disp, y_disp, time_steps): """ Calculate instantaneous velocities of (x,y) coordinates. Keyword arguments: x_disp -- list of step values of x-coordinates y_disp -- list of step values of y-coordinates time_steps -- list of time step values for frames of a tiff stack ...
def bettertitle(value): """ Alternative to the builtin title(). Ensures that the first letter of each word is uppercase but retains the original case of all others. """ return ' '.join([w[0].upper() + w[1:] for w in value.split()])
def get_print_id(id): """ Some of the ids have the name in them still - we'll parse it out if we see it to make things a bit more consistent in our naming :param id: :return: """ if "-" in id: # the ones with the ID are split by hyphens return id.split("-")[0].rstrip() # split it by hyphen, get the first i...
def classify(tree, input): """classify the input using the given decision tree""" # if this is a leaf node, return its value if tree in [True, False]: return tree # otherwise find the correct subtree attribute, subtree_dict = tree subtree_key = input.get(attribute) # None if input is...
def is_number(val): """Checks if value is is_number Args: val (str) Returns: bool: True if successful, False otherwise """ try: float(val) return True except ValueError: return False
def ParseSubversionPropertyValues(props): """Parse the given property value which comes from [auto-props] section and returns a list whose element is a (svn_prop_key, svn_prop_value) pair. See the following doctest for example. >>> ParseSubversionPropertyValues('svn:eol-style=LF') [('svn:eol-style', 'LF')] ...
def rzpad(value, total_length): """ Right zero pad value `x` at least to length `l`. """ return value + b"\x00" * max(0, total_length - len(value))
def el (name, content): """Write a XML element with given element tag name (incl. element attributes) and the element's inner content.""" return "<%s>%s</%s>" % (name, content, name.partition(" ")[0])
def get_type(obj): """ Get the type of object or if it is a class, return the class itself. """ return obj if type(obj) is type else type(obj)
def stripnl(s): """remove newlines from a string (and remove extra whitespace)""" s = str(s).replace("\n", " ") return ' '.join(s.split())
def merge_sort(inp, left=0, rght=None, flex=None): """docstring""" if rght is None: rght = len(inp) if (rght-left) <= 1: return inp mid = (rght-left) // 2 if flex is None: flex = [0] * mid lend = left + mid merge_sort(inp, left=left, rght=lend, flex=flex) merge_so...
def get_coords(object_, points): """Return coordinates for an object which is somewhere in a list of points.""" return next(coords for coords, maybe_this_object in points if maybe_this_object == object_)
def parse_bool(text): """Parses a boolean text and converts it into boolean value (if possible). Supported truth string values: * true: "true", "yes", "on", "1" * false: "false", "no", "off", "0" :raises: ValueError, if text is invalid """ from distutils.util import strtobool re...
def calc_acc(true_pos, true_neg, false_pos, false_neg): """ function to calculate accuracy. Args: true_pos: Number of true positives true_neg: Number of true negatives false_pos: Number of false positives false_neg: Number of false negatives Returns: None """ try: acc = (true_pos +...
def normalize_mutation(mut, offset): """Normalize SNPs and call mutation type. Returns: tuple: Type ("SNP" or "Indel") and (base_from, base_to) for SNPs, None for indels """ pos_str, mut_str = mut.split(":") read, pos = pos_str.split("@") if ">" in mut_str: base_from, ba...
def _has_newline(line) -> bool: """Used by has_bad_header to check for \\r or \\n""" if line and ("\r" in line or "\n" in line): return True return False
def get_range_score(weighted_node, biz_count, proj_count): """ get range_socre and normalized_range_score(0~99.99) :param weighted_node: :param biz_count: :param proj_count: :return: """ range_score = round((weighted_node + biz_count + proj_count), 2) a = 1 if weighted_node / 32.0 > ...
def get_position(indicator): """ Obtains position for indicator """ return {"URBANIDAD": 3, "HOMBRES": 5, "ALFABETIZACION": 11, "ESCOLARIDAD": 14, "ASISTENCIA": 17, "PARTICIPACION": 23 }[indicator]
def build_sql_filter(url_filters, fields): """given a dictionary containing a list of url parameters, construct the sql code for in (<field_name>__in=), like (<field_name>__like=) and is equal (<field_name>=) to for each of the specified fields in the filter dictionary. Any fields that do not exist...
def prefix_comment_id(i): """Return 'fullname' version of ID (includes Reddit type prefix).""" return i if i.startswith('t1_') else 't1_' + i
def canon(raw_attr_name: str) -> str: """ Canonicalize input attribute name as it appears in proofs and credential offers: strip out white space and convert to lower case. :param raw_attr_name: attribute name :return: canonicalized attribute name """ if raw_attr_name: # do not dereference...
def middle_me(N: int, X: str, Y: str) -> str: """ This function takes a key of X and place it in the middle of Y repeated N times. """ string = N * Y if len(string) % 2: return X else: id_x = len(string) // 2 return f'{string[:id_x]}{X}{string[id_x:]}'
def parse_env(Env): """Convert list of strings into dict object. Docker Inspect ENV is a list of strings. Env strings are in the form of KEY=VALUE. Split strings into key=value pairs and return dict object. Only return keys with "good_stuff". """ env = {} good_stuff = ['USER', 'PASS', '_DB']...
def parse_args_into_dict(input_arguments): """ Takes a tuple like (u'input_b=mystr', u'input_c=18') and returns a dictionary of input name to the original string value :param Tuple[Text] input_arguments: :rtype: dict[Text, Text] """ return {split_arg[0]: split_arg[1] for split_arg in ...
def create_pack_object_header(obj_type, obj_size): """:return: string defining the pack header comprised of the object type and its incompressed size in bytes :parmam obj_type: pack type_id of the object :param obj_size: uncompressed size in bytes of the following object stream""" c = 0 # 1 byte hdr = str() # ou...
def is_pair(hand): """ This functions takes the hand (list) and returns true if it has one pair """ pair_count = 0 for card in hand: if hand.count(card) is 2: pair_count = pair_count + 1 if pair_count == 2: return True
def gcd(x, y): """ Python code to demonstrate naive method to compute gcd, Euclidean algo """ while (y): x, y = y, x % y return x
def _warn(warn_message, *args, **kwargs): """ Inputs: warn_message- the warning message Used to override "warnings.formatwarning" to output only the warning message. """ return f'{warn_message}\n\n'
def is_function_pointer_stack(stack): """Count how many non-nested paranthesis are in the stack. Useful for determining if a stack is a function pointer""" paren_depth = 0 paren_count = 0 star_after_first_paren = False last_e = None for e in stack: if e == "(": paren_depth +...
def best_action(state, actions, Q, U): """Return the optimal action for a state, given U.""" def EU(action): return Q(state, action, U) return max(actions(state), key=EU)
def stringToList(inputString): """Convert a string into a list of integers.""" return [ord(i) for i in inputString]
def capfirst(value): """Capitalize the first character of the value.""" return value and value[0].upper() + value[1:]
def _get_total_citation_by_year(l, max_year=2015): """ Calculate the total citation by year :param l: list of (year, citation) tuple :param max_year: the maximal year :return: dict with the totatl number of citation in each year """ min_year = int(min([y for y, v in l])) total_citations...
def common_nodes (nodes1, nodes2) : """ Returns list of the intersection of two sets/lists of nodes """ nodes1 = set(nodes1) nodes2 = set(nodes2) return nodes1 & nodes2
def it(style, text): """ Color printing in terminal """ emphasis = { "red": 91, "green": 92, "yellow": 93, "blue": 94, "purple": 95, "cyan": 96, } return ("\033[%sm" % emphasis[style]) + str(text) + "\033[0m"
def format_percent(n, baseline): """Format a ratio as a percentage (showing two decimal places). Returns a string. Accepts baseline zero and returns '??' or '--'. """ if baseline == 0: if n == 0: return "--" else: return "??" return "%.2f%%" % (100 * n ...
def remove_csrf_token(data): """Flask-WTF==0.14.2 now includes `csrf_token` in `form.data`, whereas previously wtforms explicitly didn't do this. When we pass form data straight through to the API, the API often carries out strict validation and doesn't like to see `csrf_token` in the input. So this helper ...
def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----WebKi...
def is_draw(state): """Returns True if no boxes are empty but nobody has won. If not returns False.""" for i in state: for s in i: if s == 0: return False return True
def _skip(app, what, name, obj, skip, options): """ To skip some functions, see `Skipping members <https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html>`_. """ if name.startswith("_") and name not in \ ["__qualname__", "__module__", "__di...
def warning_check_2(Vcell, warning_flag): """ Check Vcell is None or not. :param Vcell: Vcell of FC Voltage :type Vcell : float :param warning_flag: input warning flag :type warning_flag : bool :return: update warning_flag as bool """ if not warning_flag: if Vcell is None: ...
def is_prime(P): """ Method to check if a number is prime or composite. Parameters: P (int): number to be checked, must be greater than 1 Returns: bool: True if prime, False if composite """ for i in range(2, P): j = P % i ...
def admin1_origin(x, conv_d): """return admin1""" country = x[0] if country != "United States": city = x[1] if conv_d.get(country, "None") != "None": admin1 = conv_d[country][0].get(city) return admin1 else: return x[2]
def translate_scale_round_path(viewBox, W_ratio, H_ratio, points): """ Input: list of absolute points. The path is translated and scaled to be in original picture referential. Coordinates are rounded and made integers. Output: list of transformed points """ ts_points = list() for p...
def dsk_out(fout,kvecs,mdsk,edsk): """ output fluctuating structure factor dS(k) in energy.pl format Args: fout (str): output filename kvecs (list): a list of 3D vectors mdsk (list): mean <dS(k)>, one value per kvector edsk (list): error, one value per kvector Returns: bool: success """ f...
def value_to_int(attrib, key): """ Massage runs in an inning to 0 if an empty string, or key not found. Otherwise return the value """ val = attrib.get(key, 0) if isinstance(val, str): if val.isspace() or val == '': return 0 return val
def convert_to_float(lst, purpose): """ Returns list of all float-convertable values of `lst`, along with length of new list """ float_times = [] len_times = 0 for t in lst: if (str(t)[:3] != 'DNF') and (t != '') and (str(t)[-1] != '+'): float_times.append(float(t)) ...
def _apply_G_adv_loss(scores_fake, loss_func): """ Compute G adversarial loss function and normalize values """ adv_loss = 0 if isinstance(scores_fake, list): for score_fake in scores_fake: fake_loss = loss_func(score_fake) adv_loss += fake_loss adv_loss /= len(sc...
def most_freq(neighbors): """ Returns the dominant color with the greater frequency Example: num_dominating = [paper, paper, paper, spock, spock, spock, spock, spock] Returns: spock """ return max(set(neighbors), key=neighbors.count)
def get_core_list_bindata(bin_data, dict_parts): """ Obtain list of core names in binary data :param str_in_file: Binary data :param dict_parts: Dictionary with file blocks info :return: List of name strings """ block_info = dict_parts['cores_dir'] max_cores = int(block_info[4]) if l...
def valid_file_name(o_name): """ Replace the illegal string in the file """ in_valid_chars = "|\\?*<\":>+[]/'," for c in in_valid_chars: o_name = o_name.replace(c, "_") return o_name.replace(" ", "_")
def _standard_args(func_name, num_files): """ Generate a set of standard """ glue_files = [func_name+str(i + 1)+'.glue' for i in range(num_files)] pipe_files = [func_name+str(i + 1)+'.dat' for i in range(num_files)] pipe_script = './' + func_name + '.com' glue_script = './' + func_name + '.py' ...
def correct_indentation(text): """ Tries to improve the indentation before running :epkg:`docutils`. @param text text to correct @return corrected text """ title = {} rows = text.split("\n") for row in rows: row = row.replace("\t", " ") cr ...
def format_selection(selection): """Format selection. Parameters ---------- selection: list or others the selections formatting properly. Returns ------- selection: list or others the selections formatting properly. """ if type(selection) == list: i_len = l...
def getTemperature( U_code, helium_mass_fraction=None, ElectronAbundance=None, mu = None): """U_code = snapdict['InternalEnergy'] helium_mass_fraction = snapdict['Metallicity'][:,1] ElectronAbundance= snapdict['ElectronAbundance']""" U_cgs = U_code*1e10 gamma=5/3. kB=1.38e-16 #erg /K m_proton=1.67e-24 # g i...
def vsub(v, w): """Subtract a vector from another.""" try: return tuple(i - j for i, j in zip(v, w)) except TypeError: return v - w
def parse_boolean(arg: str): """Returns boolean representation of argument.""" arg = str(arg).lower() if 'true'.startswith(arg): return True return False
def copy_keys(dic, *keys): """Return a copy of the dict with only the specified items present. ``dic`` may be any mapping. The return value is always a Python dict. """ ret = {} for key in keys: ret[key] = dic[key] # Raises KeyError. return ret
def toggle_bit(val: int, bitNo: int) -> int: """ Toggle specified bit in int """ return val ^ (1 << bitNo)
def para2sents(para, width): """ Turn para into double array of words (wordss) Where each sentence is up to 5 word neighbors of each entity :param para: :return: """ words = para.split(" ") sents = [] for i, word in enumerate(words): if word.startswith("@"): start...
def get_cycle_start(year): """Round year down to the first year of the two-year election cycle. Used when filtering original data for election cycle. """ return year if year % 2 == 1 else year - 1
def _is_target_node(node: str) -> bool: """Check if it is valid target node in BEL. :param node: string representing the node :return: boolean checking whether the node is a valid target in BEL """ if node.startswith('bp') or node.startswith('path'): return True return False
def monomial_lcm(A, B): """ Least common multiple of tuples representing monomials. Examples ======== Lets compute LCM of `x*y**4*z` and `x**3*y**2`:: >>> from sympy.polys.monomials import monomial_lcm >>> monomial_lcm((1, 4, 1), (3, 2, 0)) (3, 4, 1) which gives `x**...
def lower_bound(arr, value, first, last): """Find the lower bound of the value in the array lower bound: the first element in arr that is larger than or equal to value Args: arr : input array value : target value first : starting point of the search, inclusi...
def compute_jaccard_similarity_score(x, y): """ Jaccard Similarity J (A,B) = | Intersection (A,B) | / | Union (A,B) | """ intersection_cardinality = len(set(x).intersection(set(y))) union_cardinality = len(set(x).union(set(y))) return intersection_cardinality / float(union_cardinality)
def search_for_letters(phrase: str, letter: str) -> set: """Restun a set of the 'letters' found in 'phrase'.""" return set(letter).intersection(set(phrase))
def dict_indexer_with_default(d, key, default): """:yaql:operator indexer Returns value of a dictionary by given key or default if there is no such key. :signature: left[right, default] :arg left: input dictionary :argType left: dictionary :arg right: key :argType right: keyword :a...
def geofilterhelper(filters): """This field constructs a valid, IPViking-readable xml string from a list of dictionary filters. For guidance on necessary fields, please look at the IPViking Developer's docs. Required fields: command, action, category""" outputs = [] for filt in filters: fiel...
def filter_default(input_dict, params_default): """ Filter input parameters with default params. :param input_dict: input parameters :type input_dict : dict :param params_default: default parameters :type params_default : dict :return: modified input_dict as dict """ for i in params...
def build_github_url(state, generated_filename): """ Generate a URL to a preprocessed result file hosted on GitHub Args: generated_filename: Standardized filename of an election result file. Returns: String containing a URL to the preprocessed result file on GitHub. """ tpl = ...
def distance_rel(tuple1, tuple2): """ Calculates the relative distance of two tuples, returns values between 0.0 and +inf. >>> distance_rel(('a'), ()) inf >>> distance_rel(('a'), ('a')) 0.0 >>> distance_rel(['a', 'b'], ('b', 'c')) 2.0 >>> distance_rel(['a', 'b'], ('c'...
def _encode_string(string: str) -> bytes: """Encode a string to utf-8. This can be used to circumvent the issue of the standard encoding of a windows console not being utf-8. See: https://github.com/DanielNoord/pydocstringformatter/issues/13 """ return string.encode("utf-8")
def get_empty_znode(node_id): """ Get an empty ZNode with headers filled. Args: node_id: String that identifies the ZNode Returns: A dictionary representing a ZNRecord """ return { 'id': node_id, 'simpleFields': {}, 'listFields': {}, 'mapFields': {}}
def extract(data, key): """Return a dict of {long_name : value, ...} for the given stats key.""" return {bm['fullname']:bm['stats'][key] for bm in data['benchmarks']}
def payment_amount(balance, payment): """ The amount of a payment given a balance is which ever is less """ curr_payment = min(balance, payment) return curr_payment
def match_length(S, idx1, idx2): """ Returns the length of the match of the substrings of S beginning at idx1 and idx2. """ if idx1 == idx2: return len(S) - idx1 match_count = 0 while idx1 < len(S) and idx2 < len(S) and S[idx1] == S[idx2]: match_count += 1 idx1 += 1 ...
def main(elem, ns, **job_id_identifiers): """Stolos's pyspark plugin will call this function to begin the application The function parameters may be one of the below. The plugin will intelligently figure out what type of object you want to receive based on the function definition. def mai...
def evaluate_difference(lst_a, lst_b): """ Determines how much overlap there is between the two input lists. Essentially a value function to maximize. """ assert isinstance(lst_a, list) assert isinstance(lst_b, list) lst_a_len = lst_a.__len__() if lst_a_len > lst_b.__len__(): r...
def _silent_format(string, params): """ Attempt to format a string, and ignore any exceptions that occur. :param str string: String to format. :param tuple params: Formatting parameters. :return: The formatted string, or the string parameter on error. """ try: return string % params...
def get_temporal_feature_names(osn_name): """ Returns a set of the names of the temporal engineered features. :param osn_name: The name of the dataset (i.e. reddit, slashdot, barrapunto) :return: names: The set of feature names. """ names = set() ###########################################...
def _internal_function(parameter): """ Describe here what this function does, its input parameters, and what it returns. """ return parameter.upper()
def match_with_batchsize(lim, batchsize): """ Function used by modify_datasets below to match return the integer closest to lim which is multiple of batchsize, i.e., lim%batchsize=0. """ if lim % batchsize == 0: return lim else: return lim - lim % batchsize
def remove_duplicates_in_items(items: list, id_key: str) -> list: """Remove duplicate items based on the given id key, Args: items (list): The items list. id_key (str): The ID key for suplication check. Returns: (list) New items without duplications. """ i...
def OrderedSet(alist): """ Creates an ordered set from a list of tuples or other hashable items """ mmap = {} # implements hashed lookup oset = [] # storage for set for item in alist: #Save unique items in input order if item not in mmap: mmap[item] = 1 oset.append(item) return oset
def to_camel_case(snake_str): """Convert a snake str to camel case.""" components = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + "".join(x.title() for x in components[1:])
def max_val(t): """Get max int element of tuple or list Each element of t is either an int, a tuple, or a list No tuple or list is empty Decorators: guenther.wasser Args: t ([tuple, list]): tuple or list Return: Returns the maximum int in t or (recursively) in an element of t """ ma...
def typename(obj): """Returns the type of obj as a string. More descriptive and specific than type(obj), and safe for any object, unlike __class__.""" if hasattr(obj, '__class__'): return getattr(obj, '__class__').__name__ else: return type(obj).__name__
def count_trees(data, route): """ >>> count_trees([ ... [False, False, True, True, False, False, False, False, False, False, False], ... [True, False, False, False, True, False, False, False, True, False, False], ... [False, True, False, False, False, False, True, False, False, True, Fal...
def split_dmrs_string(content): """ Split a string of DMRS read from a file into indvidual DMRS strings. :param content: File content :return: List of DMRS XML strings """ content_split = content.split('<dmrs') content_filter = filter(lambda x: x.strip() != '', content_split) c...
def _dict_to_str(param_dict, num_tabs: int) -> str: """ Takes a parameter dictionary and converts it to a human-readable string. Recurses if there are multiple levels of dict. Used to print out hyperparameters. :param param_dict: A Dictionary of key, value parameters. :return: A string version of t...
def construct_path(relation, start, end): """ Constructs a path between two actors using a dictionary of child-parent relationships. Returns a list with actor IDs. """ path = [start] while end != start: path.append(relation[start]) start = relation[start] path.reverse...
def get_2comp(val_int, val_size=16): """Get the 2's complement of Python int val_int :param val_int: int value to apply 2's complement :type val_int: int :param val_size: bit size of int value (word = 16, long = 32) (optional) :type val_size: int :returns: 2's complement resu...
def to_fqdn_list(value): """Space separated list of FQDNs returned as a set.""" return set((fqdn.lower() for fqdn in value.split()))
def build_dot_bracket( positions ): """ build dot bracket string """ # n_reverse = n_forward = 0 dot_bracket_str = "" for curr_position in range( 1, len( positions ) + 1 ): paired_to_position = positions[ curr_position - 1 ] if paired_to_position == 0: dot_bracket_str += "....
def writeListCfg(lst, cfgname): """ Write out a config file from a list. - Entries: 'listItem\n' :param lst: List to be written as a config file. :param cfgname: Filename or path/to/filename for config file. :return: Config filename or path/to/filename """ cfg_out = open(cfgname, 'w') ...
def sum_(hand: list): """ Converts ranks of cards into point values for scoring purposes. 'K', 'Q', and 'J' are converted to 10. 'A' is converted to 1 (for simplicity), but if the first hand is an ace and a 10-valued card, the player wins with a blackjack. """ vals = [card.rank for card in h...
def num_add_commas(num): """ Adds commas to a numeric string for readability. Parameters ---------- num : int An int to have commas added to. Retruns ------- str_with_commas : str The original number with commas to make it more readable. """ num_...
def fuckt(n): """Caoution! This is fucking recursion!""" if (n < 0): return 0 else: return 1 if n == 0 else n * fuckt(n - 1)
def split_frames(raw_agent_data): """ :param raw_agent_data: Expected data format List[Tuple[]] where tuple is in format (frame_id, ..., last_flag) """ frames = [] frame = [] id_ = None for d in raw_agent_data: if id_ is None: id_ = int(d[0]) else: ass...