content
stringlengths
42
6.51k
def str_to_bool_safe(s, truelist=("True", "true", "T"), falselist=("False", "false", "F")): """ Converts a boolean codified as a string. Instead of using 'eval', compares with lists of accepted strings for both true and false bools, and raises an error if the string does not match any case. Parameters ...
def is_superincreasing(seq): """Return whether a given sequence is superincreasing. A sequence is superincreasing if each element is greater than the sum of all elements before it. Usage:: is_superincreasing([1, 1, 1, 1, 1]) # => False is_superincreasing([1, 3, 4, 9, 15, 90]) # => F...
def shellSort(data): """ Shell sort using Shell's (original) gap sequence: n/2, n/4, ..., 1. """ gap = len(data) // 2 # loop over the gaps while gap > 0: # do the insertion sort for i in range(gap, len(data)): val = data[i] j = i while j >= gap...
def hash_function(s): """ Naive hashing funciton -- do not use in production""" bytes_list = s.encode() #bytes_list = str(s).encode() this will take of numbers if they're gonna be used as a key total = 0 for b in bytes_list: #O(n) over the length of the key not the hash data, O(1) over the Hash dat...
def serialize_dict_1d(dict_in): """Convert list in dict to str. Args: dict_in (dict): input dict Returns: (dict): serialized dict """ assert isinstance(dict_in, dict) dict_out = dict_in for key, value in dict_out.items(): if isinstance(value, list): dic...
def overlap(a, b, min_length=3): """ Return length of longest suffix of 'a' matching a prefix of 'b' that is at least 'min_length' characters long. If no such overlap exists, return 0. """ start = 0 # start all the way at the left while True: start = a.find(b[:min_length], start) # look for b's suffx in a...
def guess_bytes(bstring): """ If you have some bytes in an unknown encoding, here's a reasonable strategy for decoding them, by trying a few common encodings that can be distinguished from each other. This is not a magic bullet. If the bytes are coming from some MySQL database with the "charact...
def kill_score(kills): """ kill_score : type kills: float : rtype kill_score: int """ if kills >= 2.95: kill_score = 100 elif kills >= 2.51: kill_score = 95 elif kills >= 2.04: kill_score = 90 elif kills >= 1.71: kill_score = 85 elif kills >= 1.38: kill_score = 80 elif kills >= 1.06: kill_scor...
def events_union(first_event, second_event): """ Merge in order two ordered sequence of events. """ if not first_event: return second_event elif not second_event: return first_event elif first_event[0] < second_event[0]: return [first_event[0]] + events_union(first_event[...
def make_residue_id(d): """Generates a residue ID for an atom. :param dict d: the atom dictionary to read. :rtype: ``str``""" # in MMCIF files, the "auth_seq_id" field is assigned by the authors and is not guaranteed to be positive, # sequential, or unique # "label_seq_id" is a unique identifi...
def variant_prefix(variant): """Return a filename prefix for variant.""" if variant is None: return '' return variant + '.'
def _interval_metric(v1, v2, **_kwargs): """Metric for interval data.""" return (v1 - v2) ** 2
def decode_dna_sequence(sequence): """ Translates dna sequence into amino acids string, you should find CDS (last 3 characters is stop codon :param sequence: dna sequence to translate :return: decoded protein (amino acids) sequence """ table = { 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG':...
def CommentPattern(lang_id=0): """Returns a list of characters used to comment a block of code @param lang_id: used to select a specific subset of comment pattern(s) """ return [u'#']
def set_dict_to_zero_with_list(dictionary, key_list): """ Set dictionary keys from given list value to zero Args: dictionary (dict): dictionary to filter key_list (list): keys to turn zero in filtered dictionary Returns: dictionary (dict): the filtered dictio...
def get_target_payload(timestamp, datapoints, target): """ Create the payload for dispatching data points to a target. @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a dictionary of data points to be dispatched to given targets @param target: a target to...
def scale_loss(loss, loss_scale): """Scales the loss by the loss scale.""" if callable(loss): return lambda: loss() * loss_scale else: return loss * loss_scale
def hog_pile(player_score, opponent_score): """Return the points scored by player due to Hog Pile. player_score: The total score of the current player. opponent_score: The total score of the other player. """ # BEGIN PROBLEM 4 if (player_score % 10) == (opponent_score % 10): return pl...
def escape_pw_for_look(string): """ escape a password for look cmd """ string = string.replace("\\", "\\\\") string = string.replace('"', '\\"') string = string.replace("'", "\\'") return string
def get_score_points(level: int, num_lines: int, dropped_grids: int = 0, hard: bool = False) -> int: """Determines how many points to award when lines are cleared""" mult = level + 1 temp = 0 if num_lines == 1: temp = 40 elif num_lines == 2: temp = 100 elif num_lines == 3: ...
def check_list_subset(list_large, list_small): """ Checks if one list of dictionaries is a subset of another. :param list_large: :param list_small: :return: """ list_large_copy = list_large.copy() sim_count = 0 for elem in list_small: for elem2 in list_large_copy: ...
def findElementInList(passedList, elements): """ :param passedList: column names of a data frame :param elements: elements to look for in the column names :return: index of first element found in the data frame column names """ for i, item in enumerate(passedList): for element in elemen...
def S_get_peaks_valleys_values(_data_list, _level=0.01, _distance=1): """ Returns all the peaks and valleys present in the data samples The level parameter defines the minimum level change required between consecutive peaks and valleys The distance parameter defines the minimum distance required between...
def float_or_dms(s): """Convert DMS to float. >>> round(float_or_dms('26:45:30'), 5) 26.75833 >>> round(float_or_dms('26:0:0.1'), 5) 26.00003 :param s: DMS value :return: float value """ if s[-1] in ['E', 'W', 'N', 'S']: s = s[:-1] return sum(float(x) / 60 ** n for (n,...
def check_in_arguments_predict(in_arg): """ Prints each of the command line arguments of 'predict.py' passed in as parameter in_arg, Parameters: in_arg -data structure that stores the command line arguments object Returns: Nothing - just prints to console """ if in_arg is N...
def to_utf8(s): """ unicode => str """ return s.encode("utf_8")
def fmt_jsdoc_union(type_strings): """ Returns a JSDoc union of the given type strings. """ return '(' + '|'.join(type_strings) + ')' if len(type_strings) > 1 else type_strings[0]
def identify_marzjson(origin, *args, **kwargs): """ Identify if the current file is a OzDES file """ file_obj = args[0] if file_obj.endswith(".json"): return True return False
def maprange(a, b, s): """ Mapping function """ (a1, a2), (b1, b2) = a, b return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
def line(x1, y1, x2, y2): """Returns a list of points in a line between the given points. Uses the Bresenham line algorithm. More info at: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm""" # Check for the special case where the start and end points are # certain neighbors, which this f...
def lower_case_words(dictionary): """ `lower_case_words()` lower-cases every word from the dictionary. * **dictionary** (*list*) : the input dictionary (while processing) * **return** (*list*) : the dictionary with each word lower-cased """ return ([word.lower() for word in dictionary])
def str2digit(s): """ string to digit """ if s.isdigit(): return int(s) return s
def are_equal(self, other): """ Return test of equality between two objects. The equality is true if two objects are the same or if one of the objects is equivalent to the dictionary format of the other. It's particularly written for Blueprint type objects. This function might not work with...
def _find_field(axisman, default, provided): """This is a utility function for the pattern where a default should be extracted from an AxisManager, unless an alternative key name has been passed in, or simply an alternative array of values. """ if provided is None: provided = default if...
def tf_a(tf, tfs): """Augmented term frequency.""" return 0.5 + (0.5 * tf) / (max(tfs))
def elementWise(A, B, operation): """ execute an operate element wise and return result A and B are lists of lists (all lists of same lengths) operation is a function of two arguments and one return value """ return [[operation(x, y) for x, y in zip(rowA, rowB)] for row...
def min_max_temp(cities_data): """Returns a list whose first and second elements are the min and the max temperatures of all the cities in cities_data. """ temps = [] for r in cities_data: temps.append(float(r['temperature'])) return [min(temps), max(temps)]
def min_operations(number): """ Return number of steps taken to reach a target number number: target number (as an integer) :returns: number of steps (as an integer) """ # Solution: # 1. The number of steps to reach a target number = number of steps take to make the target number 0 # 2....
def format_Kd(Kd): """Return formatted Kd.""" if Kd < 1e-14: return Kd * 1e15, 'fM' elif Kd < 1e-11: return Kd * 1e12, 'pM' elif Kd < 1e-7: return Kd * 1e9, 'nM' elif Kd < 1e-4: return Kd * 1e6, 'uM' elif Kd < 1e-1: return Kd * 1e3, 'mM' else: ...
def handle_error(error): """Error handler when a routed function raises unhandled error""" import traceback print(traceback.format_exc()) return 'Internal Server Error', 500
def RSAenc(m,e,N): # return m^e mod N """ Returns the RSA message of m encrypted with e and modulus N """ return pow(m,e,N)
def getKeyLevel(key:str) -> int: """ Sums the number of dots in the key ## Example getKeyLevel("Rocket") -> 0 getKeyLevel("Rocket.name") -> 1 """ if len(key) == 0: return -1 else: return len(key.split('.'))-1
def keyValueInDictList(key, value, dictList): """ Return a boolean whether a key-value data in dictList 'dictList' is a list whose elements are dicts """ if not isinstance(dictList, list): return False for item in dictList: if not isinstance(item, dict): conti...
def get_x2(oi, ei): """ Function to calculate the statistical test for the categorical data analysis, it is a chi squared value. Parameters: -------------------------- oi : list Frequency from the observed events. ei : list Frequency from the expected events. Re...
def parse_type_encoding(encoding): """Takes a type encoding string and outputs a list of the separated type codes. Currently does not handle unions or bitfields and strips out any field width specifiers or type specifiers from the encoding. For Python 3.2+, encoding is assumed to be a bytes object and ...
def construct_jolts_id( prefix="JT", sa="S", industry="000000", state="00", area="00000", size_class="00", element="QU", rate_level="R", ): """Helper function for constructing a JOLTS ID for API requests""" return ( prefix + sa + industry + state ...
def _process_attr(doc, attr_value): """ Generate attributes of an element @param doc: xml doc @param attr_value: attribute value @return: list of attributes """ attrs = [] for attr_name, attr_value in list(attr_value.items()): if isinstance(attr_value, dict): # FIXME:...
def sum_two_smallest_numbers(numbers): """Find two lowest positive integers and add them.""" return sorted(numbers)[0] + sorted(numbers)[1]
def get_common_form(placeholders): """ Extracts the common target form from a list of scalars while making sure that the given targets are equivalent. Args: placeholders: Placeholders with possibly differing target forms. Return: str: Common target form. """ target_form = N...
def generate_kubeconfig(context, cluster, user, default_name="k8s-job-runner"): """Format helper for generating individual cluster kubeconfigs Args: context (dict) - cluster (dict) - user (dict) - Returns: dict - """ if "name" not in context: ...
def trusted_division(a, b): """ Returns the quotient of a and b Used for testing as 'trusted' implemntation of division. """ return a * 1.0 / b
def percentile_s (p, sorted_seq) : """Return percentile `p` of `sorted_seq`. >>> l1 = [3, 6, 7, 8, 8, 10, 13, 15, 16, 20] >>> l2 = [3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20] >>> for l in (l1, l2) : ... for p in (0, 25, 50, 75, 100) : ... print ("%3s percentile of %s elements: %2s" % (p, le...
def can_play_stage(stamina, free_slots): """ Test to see if the player can play a stage. (Simulate a player looking at their stamina and free slots to determine if they can play a stage. For sake of simplicity, assume players don't want to play a stage if they don't have enough free slots to ho...
def is_multiline_comment_start(code, idx=0): """Position in string starts a multi-line comment.""" return idx >= 0 and idx+2 <= len(code) and code[idx:idx+2] == '/*'
def fast_non_dominated_sort(values1, values2): """ This function sorts the non dominated elements according to the values of the 2 objectives. Taken from https://github.com/haris989/NSGA-II :param values1: Values of first obj :param values2: Values of second obj :return: Sorted list of indexes """ S = [...
def format_value_for_db(value, cols, paramtype): """ Format integers for inserting/searching in the DB """ if isinstance(value, int) or "id" in cols: result = str(value) elif paramtype == "contains": result = "'%" + value + "%'" else: result = "'" + value + "'" return...
def search_codetree(tword,codetree): """ Stored in codetree with non-zero value in the terminal node """ pos = 0 while True: s = tword[pos] if s not in codetree: return 0 elif pos==len(tword)-1: return codetree[s][0] else: pos += 1 ...
def disorders_to_omim(disorders): """Extracts OMIM terms from a list of disorders of a patient Args: disorders(list): a list of disorders Returns: omim_terms(list): a list of OMIM terms. Example : ['MIM:616007', 'MIM:614665'] """ if disorders is None: return [] omim_ter...
def is_service(interface): """Return `True` if `interface` is a service.""" return hasattr(interface, 'Request') and hasattr(interface, 'Response')
def join(a, *p): """Taken from python posixpath.""" sep = '/' path = a if not p: path[:0] + sep for b in p: if b.startswith(sep): path = b elif not path or path.endswith(sep): path += b else: path += sep + b return path
def validUTF8(data): """ Method that determines if a given data set represents a valid UTF-8 encoding. Returns: True if data is a valid UTF-8 encoding, else return False. """ n_bytes = 0 for n in data: byte = format(n, '#010b')[-8:] if n_bytes == 0: if byte[0] =...
def returnsides(short_cathet): """ >>> returnsides(1) (2, 1.73) >>> returnsides(2) (4, 3.46) >>> returnsides(3) (6, 5.2) """ return 2*short_cathet, round((short_cathet**2 + 2*short_cathet**2)**(1/2),2)
def calc_sigma(sigma0, sigma1, d): """sigma0+sigma1*d """ return sigma0+sigma1*d
def natural_language_join(names): """ Given ["x", "y", "z"], return "x, y, and z". """ names = list(names) if len(names) == 0: raise ValueError("Nobody") elif len(names) == 1: return names[0] elif len(names) == 2: return names[0] + " and " + names[1] else: ...
def _get_data_list(data, key): """get key's value as list from request arg dict. If the value type is list, return it, otherwise return the list whos only element is the value got from the dict. Example: data = {'a': ['b'], 'b': 5, 'c': ['d', 'e'], 'd': []} _get_data_list(data, 'a') == ['...
def boolean(obj): """ Convert obj to a boolean value. If obj is string, obj will converted by case-insensitive way: * convert `yes`, `y`, `on`, `true`, `t`, `1` to True * convert `no`, `n`, `off`, `false`, `f`, `0` to False * raising TypeError if other values passed If obj is non...
def create_dico(item_list): """ Create a dictionary of items from a list of list of items. """ assert type(item_list) is list dico = {} for items in item_list: for item in items: if item not in dico: dico[item] = 1 else: dico[item] ...
def v0_is_anagram(word1, word2): """Return True if the given words are anagrams. That won't work for words that have the same letters but they occur a different number of times. """ return set(word1) == set(word2)
def blockchain_rpc_ports(blockchain_number_of_nodes, port_generator): """ A list of unique port numbers to be used by the blockchain nodes for the json-rpc interface. """ return [next(port_generator) for _ in range(blockchain_number_of_nodes)]
def tail(s): """ Takes an input string and returns its tail, i.e. everything except the first element. :type: str :rtype: str """ if len(s) > 0: return s[1:] # if s == "hi": # return "hello" else: return ""
def clamp(value, low, high): """Clamp the given value in the given range.""" return max(low, min(high, value))
def is_number(value): """Return if the passed value can be parsed to float.""" try: float(value) return True except ValueError: return False
def shot_type(t): """ """ ret = None if len(t) > 1: t = " ".join(t) ret = t else: ret = t[0] return ret
def _is_structured_label_vector(label_vector): """ Return whether the provided label vector is structured as a polynomial vector description appropriately or not. :param label_vector: A structured or unstructured description of a polynomial label vector. """ if not isinstance(label_vect...
def parsePort(filepath): """ Parse filepath for port number. Return port as integer. Note: Only the 1st line will be read. On any failure, None will be returned. """ port = None try: with open(filepath, "r") as port_info: port = port_info.readline().strip() port =...
def get_recipient_string(gamer_list): """ For a list or queryset of gamers, return the postman formatted recipient string. :returns: a string of usernames in postman syntax uname:uname:uname """ usernames = [g.username for g in gamer_list] return ":".join(usernames)
def colour_by_year(year, train_thresh, update1_thresh, update2_thresh, colours=None): """ Assign/return a colour depending on the year the data point was published. Parameters ---------- year : publication year of data point train_thresh : Last year threshold to assign to traini...
def duplicate_zeros(arr): """Modifies arr in place duplicating all zeros while maitining the original length.""" zeroes = 0 iteration = 0 size = len(arr) - 1 while zeroes + iteration < size: if arr[iteration] == 0: zeroes += 1 iteration += 1 while zeroes: if...
def add_new_user(network, user, games): """ Creates a new user profile and adds that user to the network, along with any game preferences specified in games. Assumes that the user has no connections to begin with. Arguments: network: the gamer network data structure. user: a string containin...
def gettimestamp(targetconnection, ymdhmsstr, default=None): """Converts a string of the form 'yyyy-MM-dd HH:mm:ss' to a Timestamp. The returned Timestamp is in the given targetconnection's format. Arguments: - targetconnection: a ConnectionWrapper whose underlying module's Timestamp...
def _GetNetworkMode(network): """Takes a network resource and returns the "mode" of the network.""" if network.get('IPv4Range', None) is not None: return 'legacy' if network.get('autoCreateSubnetworks', False): return 'auto' else: return 'custom'
def exists(label, ext = ""): """check if name exists and return a true or false response""" try: with open ('memory/' + label+str(ext), 'rb') as fp: return True except: return False
def task_pool_world(task): """ Create task pool identifier. """ if (task["world_name"] in ["Mercury", "Venus", "Earth", "Mars"]): pool = "inner" else: pool = "outer" if (task["world_name"]=="Pluto"): raise ValueError("no longer a valid world name") return pool
def is_identical(root1, root2): """ Determine if Two Trees are Identical """ # Both trees are empty if root1 is None and root2 is None: return True # Recursively compare them if both are non-empty if root1 != None and root2 != None: data_check = root1.data == root2.data left_check = is_identical(root1.le...
def filter_current_work(profile): """ Remove work_history objects that are not current Args: profile (dict): serialized user Profile Returns: dict: Profile with filtered current work_history list """ return { **profile, "work_history": [work for work in profile['w...
def concatDataHorizontally(data1, data2): """ Concats data2 to the right of data1 """ if len(data1) == 0: return data2 if len(data2) == 0: return data1 data1_height = len(data1) data2_height = len(data2) data_result_height = max(data1_height, data2_height) # data2 starts at the end of the...
def sort_balances(balances): """ Helper func to sort dictionaries of balances by value """ items = [(value, key) for key, value in balances.items()] items.sort() items.reverse() # so largest is first # Our dictionary has become a list of tuples to maintain order #return [(k, v) for v, k in items...
def return_first_element(wrapped, instance, args, kwargs): """Return only the first element of the list returned by the wrapped function. Raise error if wrapped function does not return a list or if a list contains none or more than one element. """ result = wrapped(*args, **kwargs) if not isi...
def sec2samples(time_in_seconds, rate): """ turn time in seconds into time in samples""" time_in_samples = int(round(time_in_seconds * rate)) if time_in_samples < 0: time_in_samples = 0 return time_in_samples
def _index_offset(shape, axis, offset, *index): """Compute the offset of index along one dimension.""" input_index = list(index) output_index = () for i, _ in enumerate(shape): if i == axis: input_index[i] = input_index[i] + offset output_index += (input_index[i],) retur...
def time2sec(timestr): """ Conver time specs to seconds """ # Skip numerics if type(timestr) in [int, float]: return timestr # Process strings if timestr[-1] == "s": return float(timestr[0:-1]) elif timestr[-1] == "m": return float(timestr[0:-1]) * 60 elif timestr[-1] == "h": return float(timestr[0:-...
def get_overlap(a, b): """ Determine if two intervals overlap list, list -> int """ a.sort(), b.sort() return max(0, min(a[1], b[1]) - max(a[0], b[0]))
def add_suffix(string,suffix): """if suffix, appends suffix to string with underscore. otherwise return it unchanged.""" if suffix is None: return string else: return "{}_{}".format(string, suffix)
def accuracy(pred_y, true_y): """ Calculate accuracy :param pred_y: predict result :param true_y: true result :return: """ if isinstance(pred_y[0], list): pred_y = [item[0] for item in pred_y] # print(pred_y) # print(true_y) corr = 0 for i in range(len(pred_y)): ...
def _truncate_in_space(lab_text, max_len_lab): """ This truncates a string to a given length but tries to cut at a space position instead of splitting a word. """ if len(lab_text) > max_len_lab: idx = lab_text.find(" ", max_len_lab) if idx < 0: idx = max_len_lab ...
def toflatten(pathX, pathY): """ Flatten list of paths""" flatten=[] for i in range(len(pathX)): for j in range(len(pathX[i])): flatten.append([pathX[i][j], pathY[i][j]]) return flatten
def compute_parent_nodes(root_node, stage, n_nodes): """ Computes the the parents nodes of the specified stage """ root_nodes = [root_node] for _ in range(1, stage): children = [] for r in root_nodes: for n in range(1, n_nodes + 1): child = '{}.{}'.format(r, n) ...
def greet(name=""): """ A function that takes a name and returns a greeting. Parameters ---------- name : str, optional The name to greet (default is "") Returns ------- str The greeting """ return "Hello %s" % (name)
def RendakuWorldBet(worldbet): """If the romaji is marked with '*' the form may undergo rendaku """ worldbet = worldbet.split() if worldbet[0] == 'h': return 'b ' + ' '.join(worldbet[1:]) if worldbet[0] == 't': return 'd ' + ' '.join(worldbet[1:]) if worldbet[0] == 'k': return 'g ' + ' '.join(worldbet[1:]) ...
def _sqrt_nearest(n, a): """Closest integer to the square root of the positive integer n. a is an initial approximation to the square root. Any positive integer will do for a, but the closer a is to the square root of n the faster convergence will be. """ if n <= 0 or a <= 0: raise Va...