content
stringlengths
42
6.51k
def posting_lists_union(pl1, pl2): """ Returns a new posting list resulting from the union of the two lists passed as arguments. """ pl1 = sorted(list(pl1)) pl2 = sorted(list(pl2)) union = [] i = 0 j = 0 while (i < len(pl1) and j < len(pl2)...
def as_string(my_val, error_msg=False): """Helper function for returning a single value from MySQL. Convert from [(my_val,)] to string. """ if not my_val or not my_val[0][0]: return error_msg else: return str(my_val[0][0])
def difficult_n_terminal_residue(amino_acids): """ Is the N-terminus one of {Gln, Glu, Cys}? --- Priority I: avoid N-terminal Gln, Glu, Cys """ return amino_acids[0] in {"Q", "E", "C"}
def clipboard_to_url(clipboard_txt): """ Returns url if the clipboard text starts with http otherwise, returns None """ if clipboard_txt.startswith('http'): return clipboard_txt else: print('Clipboard content is not a url:') print(f'{clipboard_txt}') return None
def validate_query_date(datestr): # noqa """Validates a user provided date that can be compared using date_key(). Returns True id the date is valid. """ parts = datestr.split("-") if len(parts) > 3: return False if len(parts) > 2: try: v = int(parts[2]) ex...
def luhn_checksum(card_number): """ Compute the Luhn checksum algorithm on all digits of the card number, and return whether or not the card number is constructed correctly. :param card_number: 16-digit card number to verify :return: True or False """ def digits_of(n): return [int(d...
def is_ipv4(addr): """return true if addr looks like an ipv4 address, false otherwise""" if addr == '0/0' or '.' in addr: return True else: return False
def _linear_interpolation(l_v, r_v, slope): """linear interpolation between l_v and r_v with a slope""" return l_v + slope * (r_v - l_v)
def wrap_fn(fn, ids, i, j, **kwargs): """ A wrapper for the QCA batch downloader """ # out_str = kwargs["out_str"] # kwargs.pop("out_str") # prestr = "\r{:20s} {:4d} {:4d} ".format(out_str, i, j) # elapsed = datetime.now() objs = [obj for obj in fn(ids, **kwargs)] # objs = [obj...
def deleteSymbol(command, mySymbols): """ Check if command is to delete stock symbol (d | delete [SYM/#]). """ expression = command.strip().lower() words = expression.split() return (len(mySymbols) > 0 and ("d " in expression or "delete " in expression) and (words[0] == "d" or words[0] == "delete") and ...
def convert_to_int(s) -> int: """ Converts a string to int Args: s (str): a string containg numbers and periods Returns: int: """ allowed_chars = "0123456789." num = s.strip() try: temp = int(num) return temp except: res = "".join([i for i ...
def _get_period(member): """Get period for which an artist is/was part of a group, orchestra or choir. Args: member (Dict): Dictionary containing the artist information. Returns: Tuple containing the begin and end year during which an artist was part of a group. """ begin_d...
def to_bytes(strlike, encoding="latin-1", errors="backslashreplace"): """Turns a str into bytes (Python 3) or a unicode to a str (Python 2)""" if strlike is None: return if not isinstance(strlike, bytes): return strlike.encode(encoding, errors) return strlike
def get_id_list(dict_list): """returns a list of all IDs of the items in a list of dictionaries :param dict_list: a list of entities in form of dictionaries :return: a list of all the entities id's """ values_array = [] items_array = dict_list.get('value') for x in items_array: valu...
def parse_postgre_sql_connection_string_as_string(connection_string): """Parse a PostgreSQL connection string to a dictionary in accordance with http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING""" fields = {} while True: connection_string = connection_string.stri...
def clean_input(text): """ Text sanitization function :param text: User input text :return: Sanitized text, without non ascii characters """ # To keep things simple at the start, let's only keep ASCII characters return str(text.encode().decode("ascii", errors="ignore"))
def build_sub_housenumber(hausnrzahl3, hausnrbuchstabe3, hausnrverbindung2, hausnrzahl4, hausnrbuchstabe4, hausnrverbindung3): """This function takes all the different single parts of the input file that belong to the sub address and combines them into one single string""" hausnr3 = hausnrzahl3 hausnr4...
def _bit_length(num): """Return number of bits needed to encode given number.""" return len(bin(num).lstrip('-0b'))
def f_rosenbrock(x): """ Define the benchmark Rosenbrock function. :param numpy.ndarray x: The function's argument array. :return: The evaluated function at the given input array. :rtype: float """ dim = len(x) f = 0.0 for i in range(dim-1): left_term = 100....
def get_char(data, index): """Return one byte from data as a signed char""" result = data[index] if result > 127: result -= 256 return result
def isInt(n_o): """parseInt polyfill""" try: return int(n_o) except ValueError: return False
def get_pubs(db): """ returns all the publication details """ try: return (db.child("TagRecords").get()).val() except Exception as e: return False
def is_float(value): """Determines whether or not the provided value is a float or not.""" try: float(value) return True except: return False
def _Repeat(func, times): """Returns the result of running func() n times.""" return [func() for _ in range(times)]
def get_index_from_tensor_name(tensor_name): """ Get the index of the tensor of a certain op. Args: tensor_name (str): The tensor name Returns: int: The index of the tensor """ return int(tensor_name.split(':')[1])
def iterative_replace_line (input_line: str, case: str, source: dict, add_line: str) -> str: """ Iterative replacer. Iteratively copy-pastes `input_line` each time with a new substitution of a templated variable depending on the `case`. Parameters: input_line (str) : input li...
def format_field(val: int, show: bool) -> str: """ Format a field """ return f'{val:>8}' if show else ""
def parse_suppress_errors(params): """Returns a list with suppressed error codes.""" val = params.get('suppressErrors', None) if not val: return [] return val.split('|')
def null_terminated(string): """Extract the NULL-terminated C string from the given array of bytes.""" return string.split(b'\0', 1)[0].decode()
def _is_float(value): """ Check whether a value is a float or not. """ try: value = float(value) return True except (TypeError, ValueError): return False
def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2), inner(word3))
def is_interactive_shell_example_line( func_start_index: int, py_module_str: str) -> bool: """ Get a boolean value of whether the target function is docstring of interactive shell string (e.g., `>>> def sample():`). Parameters ---------- func_start_index : int The index of the s...
def getzeros(num): """get leading zeros for a number string `num`. return a tuple `(leadingzeros, otherdigits)` """ leadingzeros = '' otherdigits = '' for i in range(len(num)): if num[i] != '0': otherdigits = num[i:] break leadingzeros += num[i] return...
def fix_actress_name(name): """Returns the updated name for any actress based on our replacement scheme""" """ if you want to ad any additional ways to fix names, simply add another elif line below elif name == 'name returned from javlibrary' return 'different name' """ if name == ...
def shorten(uri): """Makes a given uri a 10-character string""" return '{}...{}'.format(uri[:5], uri[-2:])
def num_pattern(i: int) -> str: """ Tries to make an unique pattern that will not generate collisions """ return f"_.:{i}:._([{i}])_!?{i}?!_"
def remove_falseneg(negatives, positives): """this method removes any negative fasta sequences that contain one of the positive sample sequences (essentially making them false negatives.""" seqs = [] for n in negatives: if not any(p in n for p in positives): seqs.append(n) return seq...
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if num == 0: raise(ValueError) if num == 1: return "1" if num == 2: return "1 1" answer = [None, 1, 1] i ...
def get_shift_bit(char, var): """Returns the var argument if char is '1', otherwise (bvnot var). Args: char: A string, either '0' or '1' var: A string, representing a variable we've defined in the smt2 file. Returns: The value or its inversion. """ if char == "0": return f"(bvnot {var})" e...
def jaccard(a, b): """ Calculate Jaccard similarity. :param a: sentence1, list of segmented words :param b: sentence2 :return: similar score """ a = set(a) b = set(b) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c))
def make_error_string(msg, args_str): """ - msg: string, an error message - args_str: string, original arguments RETURN: string, an error message """ return ("\n---\nERROR\n" + msg + f"\nin call to `add_schema_table({args_str})`\n---\n")
def confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None): """ Returns the confusion matrix between rater's ratings """ assert len(rater_a) == len(rater_b) if min_rating is None: min_rating = min(rater_a + rater_b) if max_rating is None: max_rating = max(rater_a + ...
def _get_type_name(klass): """ _get_type_name(KeyError) -> 'exceptions.KeyError' """ return klass.__module__ + '.' + klass.__name__
def rgb2rgba(rgb, max_val=1): """Convert color code from ``rgb`` to ``rgba``""" return (*rgb, 1)
def valid(parentheses): """ Validates if a string of only parenthetical characters (aka those in the set of {'(', ')', '[', ']', '{', '}'}) is in a valid order. Parameters: parentheses: str Return: int: 0 means False, and 1 means True """ # early exits: if there's an odd number of...
def get_date(*args, debug=0): """ Example: import cmglam as cm year, doy = cm.get_date(year, month, day) or year, month, day = cm.get_date(year, doy) """ # def help(): # print(""" # Example: # import cmglam as cm # year, doy = cm.get_date(year, month, day) # or # year, month, day = cm....
def choices_zip(choices): """ Creates a container compatible with Django's modelField.choices when both the databa :param choices: An iterable of the choices for the modelField :return: An iterable of two-item tuples, both items identical """ return [(c, c) for c in choices]
def set_xpath( data_base) -> dict: """ Sets the xpath based on which data base the user wants to search. :param data_base: The data base to search. :return: the xpath (search parameters in dict form) and db. (a magic string that tells the browser what database to search) """ if data_base == "Vul...
def isSymbolNumber(command, sortedSymbols): """ isSymbolNumber checks whether given command has Stock Symbol number and it is in the loaded Stock Symbols. """ return ((len(command.strip()) > 0) and command.strip().isdigit() and int(command.strip()) < len(sortedSymbols))
def tour_from_path(path): """Append the first city in a path to the end in order to obtain a tour""" path.append(path[0]) return path
def total_hazard_perceived_by_town(hazards: list, town_id: int, facilities: list) -> int: """ For the specified town retrieve the total risk caused by opened facility :param hazards: list of list, describe every hazard for the couple (town,facility) :param town_id: the town of interest :param facil...
def get_stylesheets_for_decorator(decorator: dict, count: int) -> list: """ Gets stylesheets for a decorator. Args: decorator (dict): Decorator config object. count (int): Current page count. Returns: list: List of CSS documents that apply to current usage of decorator. """...
def clamp(x, low, high): """ Ensures that x is between the limits set by low and high. For example, * clamp(5, 10, 15) is 10. * clamp(15, 5, 10) is 10. * clamp(20, 15, 25) is 20. @param x: the value to clamp. @param low: the minimum value allowed. @param high: the maximum value ...
def intersect_ranges(range_1, range_2): """If > 0: ranges intersect.""" range_1 = range_1 if range_1[1] > range_1[0] else range_1[::-1] range_2 = range_2 if range_2[1] > range_2[0] else range_2[::-1] return min(range_1[1], range_2[1]) - max(range_1[0], range_2[0])
def prettyprint_error(data: dict) -> str: """ Print generic errors returned from the API. """ error = 'Could not execute command\n' if 'message' in data: if type(data['message']) == list: error += ', '.join(data['message']) elif type(data['message']) == str: ...
def xobj_getattr(obj, attrName, *args): """ Return the value for the attr given following any .attrs """ checkExists = len(args) > 0 value = obj attrs = attrName.split('.') for attr in attrs: if not checkExists or hasattr(value, attr): value = getattr(value, attr) ...
def stop_count_records(stream, summary=None, comp_id="stop_count_records"): """Only count the records from the incoming stream.""" rec_counter = 0 for rec in stream: rec_counter += 1 if summary is not None: summary[comp_id] = rec_counter return rec_counter
def b_distance_function(x): """Returns the function :math:`f(x)= \frac{1}{1+x}`. The function is used to transform the distance between two countries to a measure between zero and one that is used to regulate the probability of meeting an individual from a certain country. Parameters ----------...
def _can_broadcast(shape1, shape2): """Whether two shapes can broadcast together using numpy rules""" for i, j in zip(reversed(shape1), reversed(shape2)): if i != j and i != 1 and j != 1: return False return True
def events_from_json(json_dict): """ simply accesses the events in a single json """ if not json_dict: return [] events = [] for group in json_dict: group_events = group["events"] events += group_events return events
def signum(x): """Return the sign of each entry of an array""" return (x < 0.) * -1. + (x >= 0) * 1.
def autocorrect(user_word, valid_words, diff_function, limit): """Returns the element of VALID_WORDS that has the smallest difference from USER_WORD. Instead returns USER_WORD if that difference is greater than or equal to LIMIT. """ # BEGIN PROBLEM 5 list_diff = [] list_words = [] for i...
def calculate_opt_dt(a, D): """Calculates the optimal dt based on size of pore and diffusion coefficent returns a value for dt """ return (a*1e-3) / (6*D)
def translator(data): """This provides a function that hashes the flight times a second time with a per user hash.""" #also no hashing #issue: security return(data)
def _error_msg_routes(iface, option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ msg = "Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]" return msg.format(iface, option, expected)
def round_to_step(x, parts=4): """ rounds to the step given, 4 is a quarter step, because 1.0 / 4 = 0.25. :param x: input value. :param parts: divisible by this many parts. :return: <float> to the rounded part. """ return round(x*parts)/parts
def get_atol(tol, atol, bnrm2, get_residual, routine_name): """ Parse arguments for absolute tolerance in termination condition. Parameters ---------- tol, atol : object The arguments passed into the solver routine by user. bnrm2 : float 2-norm of the rhs vector. get_residua...
def linearstep(edge0: float, edge1: float, x: float) -> float: """A linear transition function. Returns a value that linearly moves from 0 to 1 as we go between edges. Values outside of the range return 0 or 1. """ return max(0.0, min(1.0, (x - edge0) / (edge1 - edge0)))
def ngrams_you_are(data): """Extract special features from data corresponding to "you are" experssion. Args: data: list of text samples Returns: list of special expressions """ g = [x.lower() .replace("you are", " SSS ") .replace("you're", " SSS ") .repla...
def is_dataclass_type(cls: type) -> bool: """Like dataclasses.is_dataclass(), but works correctly for a non-dataclass subclass of a dataclass.""" try: return "__dataclass_fields__" in cls.__dict__ except Exception: return False
def get_watershed_subbasin_from_folder(folder_name): """ Get's the watershed & subbasin name from folder """ input_folder_split = folder_name.split("-") watershed = input_folder_split[0].lower() subbasin = input_folder_split[1].lower() return watershed, subbasin
def set_output_path(folder, protocol, fprefix, particip, output_file, sess): """ Define pathway of output files """ output_path = folder + '/' + protocol + '/' + fprefix + '-' + \ '%02d' % particip + '/' + output_file + '_' + protocol + \ '_' + fprefix + '-' + '%02d' % particip + '_' + 'run' + \...
def point_to_geojson(lat, lng): """ Converts a single x-y point to a GeoJSON dictionary object of coordinates :param lat: latitude of point :param lng: longitude of point :return: dictionary appropriate for conversion to JSON """ feature = { 'type': 'Feature', 'geometry': { ...
def dict_find(in_dict, value): """ Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Return...
def check_rows(board: list) -> bool: """ Checks if ther are no duplicates in each row of the board. >>> check_rows(['**12', '1234', '2231']) False >>> check_rows(['**12', '1234', '2431']) True """ for row in range(len(board)): row_nums = set() for elem in board[row]: ...
def sort_score_by_event_times(score): """Sorts events by start time and returns new score""" return list(map( lambda index: score[index], sorted( list(range(len(score))), key=lambda indx: score[indx][0]) ))
def _private_call(method, args, prefix='_'): """Determine if a call's first argument is a private variable name.""" if method.__name__ in ('__getattribute__', '__setattr__'): assert isinstance(args[0], str) return args[0].startswith(prefix) else: return False
def encode_letters(name): """ Encode the letters in a string.""" # Character codes. codes = [] codes.append("aeiouy") # Vowels map to 0. codes.append("bfpv") # 1 codes.append("cgjkqsxz") # 2 codes.append("dt") # 3 codes.append("l") # 4 codes.append("m...
def add(a, b): """ Function to add two values """ c = a + b return c
def parse_float(value): """ Convert string to amount (float) :param value: string value :return: float value if the parameter can be converted to float, otherwise None """ try: return float(value) except (ValueError, TypeError): return None
def joinStrs(strlist): """Join a list of strings into a single string (in order).""" return ''.join(strlist)
def _format_page_object_string(page_objects): """Format page object string to store in test case.""" po_string = '' for page in page_objects: po_string = po_string + " '" + page + "',\n" + " " * 8 po_string = "[{}]".format(po_string.strip()[:-1]) return po_string
def generate_changelog(releases): """Generates a changelog from GitHub release notes""" changelog = "" for release in releases: changelog += "\n## [{tag}]({url}) - {date}\n{body}\n".format( tag=release['tag_name'], url=release['html_url'], date=release['published...
def q_matrix(q): """return the rotation matrix based on q""" m = [0.0]*16 m[0*4+0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]) m[0*4+1] = 2.0 * (q[0] * q[1] - q[2] * q[3]) m[0*4+2] = 2.0 * (q[2] * q[0] + q[1] * q[3]) m[0*4+3] = 0.0 m[1*4+0] = 2.0 * (q[0] * q[1] + q[2] * q[3]) m[1*4+1] = 1...
def is_stupid_mkr(name: str) -> bool: """ Stupid mkr Parameters ----------- name: str Name of user, maybe stupid mkr """ if name is None: return False return name.lower() == "mkr"
def format(value, format_spec=''): """Return value.__format__(format_spec) format_spec defaults to the empty string. See the Format Specification Mini-Language section of help('FORMATTING') for details.""" return value.__format__(format_spec)
def get_formatted_percentage(x, tot): """ Return a percentage to one decimal place (respecting ) """ return "{0:.1f}".format((float(x) / tot * 100)) if tot else '0'
def per_capita_TED(sum_12_mo): """Calculates final Peak Hour Excessive Delay number. Args: sum_12_mo, the integer sum of all TED values. Returns: A value for Peak Hour Excessive Delay per capita. """ print(sum_12_mo) pop_PDX = 1577456 return sum_12_mo / pop_PDX
def tabular2dict(tabular, keys): """ Utility function to turn tabular format CONLL data into a sequence of dictionaries. @param tabular: tabular input @param keys: a dictionary that maps field positions into feature names @rtype: C{list} of featuresets """ tokendicts = [] lines = tab...
def add_spaces(amount): """ should only work if more then 6 Players are there, to make sure the embed looks good(still looks shit on mobile). """ spaces = "\t|\n\t|\n\t|\n\t|\n\t|\n" i = 6 amount = int(amount) while i <= amount: spaces += "\t|\n" return spaces
def measure_prf(num_TP, num_FN, num_FP): """Compute P, R, and F from size of TP, FN, and FP [FMP, Section 4.5.1] Notebook: C4/C4S5_Evaluation.ipynb""" P = num_TP / (num_TP + num_FP) R = num_TP / (num_TP + num_FN) if (P + R) > 0: F = 2 * P * R / (P + R) else: F = 0 re...
def f(a, b): """ f @param a: @param b: @return: """ a += b return a
def walk_json(obj, *fields): """ for example a=[{"a": {"b": 2}}] walk_json_field_safe(a, 0, "a", "b") will get 2 walk_json_field_safe(a, 0, "not_exist") will get None """ try: for f in fields: obj = obj[f] return obj except: return None
def getNumberDecomposition(numberString): """Decomposes the number in its digits. Returns a list of strings [units, tens, hundreds, thousands]. """ number = int(numberString) decomposition = [numberString[len(numberString) - 1]] for i in range(1, 4): if (number >= pow(10, i)): ...
def gtir(registers, opcodes): """gtir (greater-than immediate/register) sets register C to 1 if value A is greater than register B. Otherwise, register C is set to 0""" test_result = int(opcodes[1] > registers[opcodes[2]]) return test_result
def convert_seconds_to_video_time_string(seconds): """ Converting elapsed seconds from the beginning of a video to video time's string representation Arguments: seconds (int): Time for the beginning of a video. Examples: >>> convert_seconds_to_video_time_string(16) ...
def minimum(a,b): """ UNUSED: return the smallest value of a and b """ if(a < b): return a else: return b
def s(word, seq, suffix="s"): """Adds a suffix to ``word`` if some sequence has anything other than exactly one element. Parameters ---------- word : str The string to add the suffix to. seq : sequence The sequence to check the length of. suffix : str, optional. The ...
def uniqueValues(aDict): """ Write a Python function that returns a list of keys in aDict that map to integer values that are unique (i.e. values appear exactly once in aDict). The list of keys you return should be sorted in increasing order. (If aDict does not contain any unique values, you should ...
def lib_utils_oo_chomp_commit_offset(version): """Chomp any "+git.foo" commit offset string from the given `version` and return the modified version string. Ex: - chomp_commit_offset(None) => None - chomp_commit_offset(1337) => "1337" - chomp_commit_offset("v3.4.0.15+git.derp") ...