content
stringlengths
42
6.51k
def compute_over_actions(f, *args): """Runs f over all elements in the lists composing *args. Autoregressive actions are composed of many logits. We run losses functions over all sets of logits. """ return sum(f(*a) for a in zip(*args))
def create_display_name(diagnostic_name): """ Converts a diagnostic name to a more easily digestible name that can be used as a plot title or in a table of totals. Args: ----- diagnostic_name : str Name of the diagnostic to be formatted Returns: -------- display...
def groupby(iterable, key=None): """ Group items from iterable by key and return a dictionary where values are the lists of items from the iterable having the same key. :param key: function to apply to each element of the iterable. If not specified or is None key defaults to identity function and...
def getTS(z): """ Calculate the spin temperature at a given redshift Not a totally straightforward thing to work out. """ TS=1 return TS
def get_text_colour_analytics_sentiment(score): """ Returns RGB code text to represent the strength of negative or positive sentiment :param score: Sentiment score in range +/- 5.0 :return: Background RGB colour text string to use in sentiment text """ # Get our score into the range [0..4], whi...
def parabolic(f, x): """Quadratic interpolation for estimating the true position of an inter-sample maximum when nearby samples are known. f is a vector and x is an index for that vector. Returns (vx, vy), the coordinates of the vertex of a parabola that goes through point x and its two neighbors. ...
def mc_pow(data): """ Modulus calculation (square of) Calculated as: real^2+imag^2 """ return data.real**2+data.imag**2
def get_file_name_from_image_url(image_url: str): """Return the file name Args: image_url (str): Storage Account Url Returns: (str) : image file name """ #split and take out only the last part (file name) return image_url.split("/")[-1]
def check_floats(num): """Devuelve True si el string contiene un ".".""" if '.' in num: return True
def _probability(value, col_a_counts_map): """ p(a=value) = counts of a at value, dividied by total values of a """ sum=0 for key in col_a_counts_map.keys(): sum += col_a_counts_map[key] if col_a_counts_map[value] == 0: print("nothing:", value) return col_a_counts_map[value] / ...
def jaccard_distance(label1, label2): """Distance metric comparing set-similarity. """ return (len(label1.union(label2)) - len(label1.intersection(label2)))/len(label1.union(label2))
def z2lin(array): """dB to linear values (for np.array or single number)""" return 10 ** (array / 10.)
def get_contiguous_set(numbers, search, length = 2): """ Return a contiguous set of at least two numbers in a list of numbers which sum to a given number. """ for index in range(len(numbers) - length): # Get the contiguous set and organize it. contiguous_set = numbers[index: index...
def binary_insertion_sort(collection: list) -> list: """A Python implementation of insertion sort based on binary search :param collection: a mutable collection of comparable items :return: the same collection ordered by ascending Examples: >>> binary_insertion_sort([37, 23, 0, 17, 12, 72, 31, 46, ...
def get_years(start_time, stop_time): """Get years contained in a time period. Returns the list of years contained in between the provided start time and the stop time. :param start_time: Start time to determine list of years :type start_time: str :param stop_time: Stop time to determine list ...
def avg(iterable): """ Return the average value of an iterable of numbers """ # the iterable can be an iterator that gets exhausted # while `sum` and `len` will return 0 list_copy = list(iterable) if not list_copy: return None return sum(list_copy) / len(list_copy)
def is_unique(x): """Check that ``x`` has no duplicate elements. Args: x (list): elements to be compared. Returns: bool: True if ``x`` has duplicate elements, otherwise False """ return len(set(x)) == len(x)
def _dword_unpack(value): """Unpack a single DWORD-packed triaxial value""" # eezzzzzz zzzzyyyy yyyyyyxx xxxxxxxx exponent = value >> 30 x = ((((value ) & 0x3ff) ^ 0x0200) - 0x0200) << exponent y = ((((value >> 10) & 0x3ff) ^ 0x0200) - 0x0200) << exponent z = ((((value >> 20) & 0x3ff) ^ 0x0...
def has_edges(node_label, edges): """ Checks if given node name has any edges. Nodes with no edges are not added to the graph. """ return len([ k for k in edges.keys() if k[0] == node_label or k[1] == node_label]) > 0
def is_solvable_seed(seed): """Returns True if the given seed would generate a solvable pirellone instance, False otherwise.""" # We reserve those seed divisible by 3 to the NOT solvable instances return (seed % 3) != 0
def _is_dunder(function_name: str) -> bool: """Checks if a function is a dunder function.""" return function_name.startswith("__") and function_name.endswith("__")
def _guess_max_plate_nesting(model_trace): """ Guesses max_plate_nesting by using model trace. This optimistically assumes static model structure. """ sites = [site for site in model_trace.values() if site["type"] == "sample"] dims = [ frame.dim for site in sites for...
def get_default_options(num_machines=1, max_wallclock_seconds=1800, withmpi=False): """Return an instance of the options dictionary with the minimally required parameters for a CalcJob. Default values are set unless overridden through the arguments. :param num_machines: set the number of nodes, default=1 ...
def is_trivial_pair(p): """Is the critical pair trivial?""" u, v = p; return u == v
def intersection( f_inverted_index, s_inverted_index ) -> list: """ Operator "AND" :type f_inverted_index: list :type s_inverted_index: list """ if (not f_inverted_index) and (not s_inverted_index): return [] if not f_inverted_index: return s_inverted_index ...
def chunks(l, n): """ returns successive n-sized chunks from l. >>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'a', 'b', 'c', 'd', 'e', 'f'] >>> chunks(l, 5) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], ['a', 'b', 'c', 'd', 'e'], ['f']] >>> chunks(l, 1) [[1], [2], [3], [4], [5], [6], [7], [8], [9], [0], ['a'...
def nicer(string): """ >>> nicer("qjhvhtzxzqqjkmpb") True >>> nicer("xxyxx") True >>> nicer("uurcxstgmygtbstg") False >>> nicer("ieodomkazucvgmuy") False """ pair = False for i in range(0, len(string) - 3): for j in range(i + 2, len(string) - 1): if ...
def to_rgb(color: tuple) -> tuple: """Converts from biconal hsl space to cartesian rgb space. Color must be given as a 3D tuple representing a point in hsl space. Returns a 3D tuple representing a point in the rgb space. Each value is returned as an integer with precision 0. """ (h, s, l) = c...
def add_rbd_mirror_features(rbd_features): """Take a RBD Features bitmap and add the features required for Mirroring. :param rbd_features: Input bitmap :type rbd_features: int :returns: Bitmap bitwise OR'ed with the features required for Mirroring. :rtype: int """ RBD_FEATURE_EXCLUSIVE_LOCK...
def sectors_to_seconds(sectors: int) -> int: """Convert sectors to seconds rounded to the nearest second. :param sectors: number of sectors :type sectors: integer :rtype: integer """ SECTORS_PER_SECOND = 75 remainder = sectors % SECTORS_PER_SECOND return sectors // SECTORS_PER_SECOND +...
def listdict2dictlist(list_dict, flatten=False): """Function that takes a list of dict and converts it into a dict of lists Args: list_dict ([list]): The original list of dicts Returns: [dict]: A dict of lists """ keys = {key for tmp_dict in list_dict for key in tmp_dict} res =...
def concat(self, acc, arg=None, *args): """Just return the arg appended to the accumulator. One positional should be the arg. Two positional arguments should be accumulator, arg :param arg: object to append to a list :param acc: optional list to append to, if missing new list will be created ...
def ib_error(code): """Given an error code, return the error text. """ error_strings = [ \ "System error", \ "Function requires GPIB board to be CIC", \ "No Listeners on the GPIB", \ "GPIB board not addressed correctly", \ ...
def flatten(nested_list): """Flatten a nested list.""" return [item for sublist in nested_list for item in sublist]
def rect_offset(rect, offset): """ Offsets (grows) a rectangle in each direction. """ return (rect[0] - offset, rect[1] - offset, rect[2]+2*offset, rect[3]+2*offset)
def get_fibonacci_iterative(n: int) -> int: """ Calculate the fibonacci number at position 'n' in an iterative way :param n: position number :return: position n of Fibonacci series """ a = 0 b = 1 for i in range(n): a, b = b, a + b return a
def queensAttackFirstAttempt(n, k, r_q, c_q, obstacles): """ First attempt at a solution. Works wonderfully, but times out on large boards due to the number of possible moves. """ move_count = 0 # setup possible moves list, starting up and going clockwise possible_moves = [[1, 0], [1, 1], [0, ...
def get_subject(file): """ Get subject from BIDS file name :param file: :return: subject """ return file.split('_')[0]
def cleanupSlices(sList): """ the input slices are the parts of the fileContents that we want to get rid of, so we swap them to bits that we want to keep on output. """ # invert the slice info; we pad the slices with 1 in index space to remove # extra lines keep = [] start = 0 for thisSlice in ...
def get_and_apply(dictionary, key, default, fn): """ Fetches the value from the dictionary if it exists, applying the map function only if the result is not None (similar to the get method on `dict`) """ ret = dictionary.get(key, default) if ret: ret = fn(ret) return ret
def create_module_dict(name, used_io): """Returns dictionary containing relevant data""" m_dict = {} m_dict["name"] = name m_dict["di"] = used_io[0] m_dict["ai"] = used_io[1] m_dict["ui"] = used_io[2] m_dict["do"] = used_io[3] m_dict["ao"] = used_io[4] m_dict["co"] = used_io[5] r...
def _fahrenheit_to_kelvin(temp): """Convert temperature in Fahrenheit to Kelvin""" return (temp - 32) * 5 / 9 + 273.15
def transpose_table(table): """ Transpose any table of values stored as list of lists. Table must be rectangular. Returns: Transposed list of lists. """ n_table = [] while len(n_table) != len(table[0]): n_table += [[]] for col_ind in range(0, len(table[0])): for row_in...
def worldToImgPixelCoords(world_x, world_y, img_x, img_y, img_w, img_h, img_pixels_w, img_pixels_h, trun...
def get_cpg_content(seq): """ :param seq: :return: """ cpg = seq.count('cg') return round((cpg / len(seq) * 100) * 2, 3)
def hcf(A, B): """ Highest Common Factor by the Euclid method Note: math.gcd() is Python 3.5 and later """ if B == 0: return abs(A) return hcf(B, A % B)
def format_var_key(key: str) -> str: """ format key to ${key} :param key: key :type key: str :return: format key :rtype: str """ return "${%s}" % key
def _xbrli_decimal_item_type_validator(value): """XBRLI decimal validator.""" errors = [] if type(value) is str: try: result = float(value) except ValueError as ex: errors += ["'{}' is not a valid decimal value.".format(value)] elif type(value) is not int: ...
def load_metaparameters(param_dict=None): """ Parameters for bayesian optimizer. Default dictionary listed and updated by param_dict. """ metaparams = {'architecture': 'svm', 'log_gamma': -3, 'log_C': -2} if param_dict: metaparams.update(param_dict) r...
def squarePyrNum(base): """ This function gets the square pyramidal number with the given base. """ n = base return (2*n**3 + 3*n**2 + n)/6
def bezout(a, b): """returns u, v such as au+bv = pgcd(a,b)""" if b == 0: return (1, 0) else: (u, v) = bezout(b, a % b) return (v, u - (a // b) * v)
def split_by_equals(word, unused_lines, iline): """ splits 'x = 42' into 'x' and '42' """ if '=' not in word: msg = 'line %i: %r cannot be split by an equals sign (=)' % (iline, word) raise RuntimeError(msg) word_out, value = word.split('=') return word_out, value
def escape(src): """ Escape colon characters from feature names. @type src: str @param src: A feature name @rtype str @return The feature name escaped. """ return src.replace(':', '__COLON__')
def _rchild(i): """ Returns the right child node of the given node. """ return 2 * i + 2
def meters_formatter(f): """ Returns a float with 4 decimal digits and the unit 'm' as suffix. """ if f is None: return None return '%0.4f m' % f
def rivertemp(month): """River temperature, based on Fraser River, see Allen and Wolfe (2013). Temperature in NEMO is in Celsius. """ centerday = [ 15.5, 31 + 14, 31 + 28 + 15.5, 31 + 28 + 31 + 15, 31 + 28 + 31 + 30 + 15.5, 31 + 28 + 31 + 30 + 31 + 15, ...
def get_distortion_coeffs(degree, filter_info): """Do this with the grism file header input instead""" a_coeffs = {} b_coeffs = {} for key in filter_info: if key[0:2] == "A_" or key[0:2] == "B_": if "ORDER" in key: continue split_key = key.split("_") ...
def multiply_two(number): """Returns the given number multiplied by two The result is always a floating point number. This keyword fails if the given `number` cannot be converted to number. """ return float(number) * 2
def dig(key, array): """ Dict/list exporter. @param (str) key @param (dict|list) array @return (mixed) """ if key in array: return array[key] try: keys = key.split(".") key = keys.pop(0) if len(keys) > 0: return dig(".".join(keys), array[key]) re...
def _convert_to_bool(value): """ If the value is `true` or `false`, return the boolean equivalent form of the value. This method is case insensitive. :param value: the string value :type value: str :return: the string value or the boolean value :rtype: str or bool """ if isinstance(...
def checkdims(dims: tuple): """ Calculate the total number of elements :param dims: Dimension tuple :type dims: tuple :return: Number of elements :rtype: int """ number: int = 1 def multipy(dim: int): nonlocal number number = number * dim for dim in dims: ...
def p(item): """ For Debug purposes """ if not item: return item return { "type": "type" in item and item["type"], "key": "key" in item and item["key"], "props": "props" in item and item["props"], "dom": "dom" in item and item["dom"] and True, }
def parity(n): """ Returns 0 if n is even and 1 if n is odd """ return int((1 + (-1)**(n+1))/2)
def response_message(resp_json): """Pulls the error message out of a Waiter response""" if 'waiter-error' in resp_json and 'message' in resp_json['waiter-error']: message = resp_json['waiter-error']['message'] if not message.endswith('.'): message = f'{message}.' else: me...
def setdefault1(d, key): """ >>> d = {} >>> setdefault1(d, 1) >>> len(d) 1 >>> setdefault1(d, 1) >>> len(d) 1 >>> d[1] >>> setdefault1(d, Unhashable()) Traceback (most recent call last): TypeError: I am not hashable >>> len(d) 1 >>> h1 = setdefault1(d, Hashabl...
def _parse_imdb_id(imdb_id): """ Parse the int value from a imdb id format ttNNNNNN if the prefix is found on the input value. If the input is an int just return it. This method is used because if using the sql based imdb database it will expect an integer without the tt prefix. The http method will...
def remove_underscore(attrib): """Remove underscores and camel case attribute names""" index = 0 while index < len(attrib): if attrib[index] is '_': attrib[index+1] = attrib[index+1].upper() del attrib[index] index = index+ 1 else: index = ind...
def _depset_to_list(l): """Helper function to convert depset to list.""" iter_list = l.to_list() if type(l) == "depset" else l return iter_list
def rgb_tuple_from_csv(text: str): """ Returns a three-valued tuple, each in the range 0-255, from comma- separated text. """ values = text.split(",") if len(values) != 3: raise ValueError("Not a tuple of length 3") values = [int(v) for v in values] for v in values: if no...
def format_signing_data(api_key_id, host, url, method): """ Format the input data for signing to the exact specification. Mainly, handles case-sensitivity where it must be handled. >>> format_signing_data('0123456789abcdef', 'veracode.com', '/home', 'GET') 'id=0123456789abcdef&host=veracode.com&url=/h...
def encode(s): """ Run length encoding (str) -> str >>> encode('BWWWWWBWWWW') '1B5W1B4W' """ ret = '' grpSize = 0 grpChar = None for ch in s: if ch != grpChar: if grpSize: ret += "{}{}".format(grpSize, grpChar) grpSize = 1 ...
def int_to_upper_mask(mask): """ Convert an integer into an upper mask in IPv4 string format where the first mask bits are 1 and all remaining bits are 0 (e.g. 8 -> 255.0.0.0) :param mask: mask as integer, 0 <= mask <= 32 :return: IPv4 string representing an upper mask corresponding to mask """ ...
def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings ...
def are_equal_lists(list1, list2): """Check if two lists contain same items regardless of their orders.""" return len(list1) == len(list2) and all(list1.count(i) == list2.count(i) for i in list1)
def calc_nsplits(chunk_idx_to_shape): """ Calculate a tiled entity's nsplits :param chunk_idx_to_shape: Dict type, {chunk_idx: chunk_shape} :return: nsplits """ ndim = len(next(iter(chunk_idx_to_shape))) tileable_nsplits = [] # for each dimension, record chunk shape whose index is zero o...
def _is_slack_post(file_info: dict) -> bool: """Checks if the file type is a valid Slack post.""" return file_info['filetype'] in ('post', 'space', 'docs')
def square_mirror(square): """Mirrors the square vertically.""" return (9 - square // 9) * 9 + square % 9
def human_readable_bytes(bytes): """ 1 KibiByte == 1024 Bytes 1 Mebibyte == 1024*1024 Bytes 1 GibiByte == 1024*1024*1024 Bytes """ if bytes == 0: return "0 bytes" if bytes < 1024: return f"{bytes} bytes" if bytes < 1024*1024: return f"{float(round(bytes/(1024...
def eCF(i): """ Returns the first i terms of the (aperiodic) continued fraction representation of e. """ return [2] + [int((a+1) / 3 * 2) if a % 3 == 2 else 1 for a in range(1, i)]
def package_to_path(package): """ Convert a package (as found by setuptools.find_packages) e.g. "foo.bar" to usable path e.g. "foo/bar" No idea if this works on windows """ return package.replace('.', '/')
def print_percentage(number): """Given a number between 0 and 1, it returns a string indicating percentage: e.g. 10.2 %%""" return "%2.2f %%" % ((1.0 * number) * 100)
def lengthOfLongestSubstring(s: str) -> int: """Given a string s, returns the length of the longest substring without repeating characters.""" if s == '': return 0 max_start_ptr = 0 max_end_ptr = 1 start_ptr = 0 end_ptr = 1 for t in (s)[1:]: if t in (s)[start_ptr:end_ptr]: ...
def get_csv_headers(lol): """ """ headers = lol.pop(0) return (headers, lol)
def as_bytes(s): """ Convert an unicode string to bytes. :param s: Unicode / bytes string :return: bytes string """ try: s = s.encode() except (AttributeError, UnicodeDecodeError): pass return s
def parents_to_string(parent_tuple): """ Convert parent strings to a slash string """ return str(parent_tuple[0])+"/"+str(parent_tuple[1])
def within_bbox(pt_coord, bbox): """Tests if geom is within the bbox envelope. Bbox of form (minx, maxx, miny, maxy) - IE the result of an ogr GetEnvelope() call.""" result = False if pt_coord[0] >= bbox[0] and pt_coord[0] <= bbox[1] \ and pt_coord[1] >= bbox[2] and pt_coord[1] <= bbox[3]: ...
def make_breakable(text, maxlen): """ make a text breakable by inserting spaces into nonbreakable parts """ text = text.split(" ") newtext = [] for part in text: if len(part) > maxlen: while part: newtext.append(part[:maxlen]) part = part[maxlen:] ...
def find_all_indexes(text, pattern): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. Best and Worst Case Runtime: O(n*k) where n is the lenght of the text and k is the length of the pattern becuase the algorythm goes through the entire ...
def validIP(ipaddress): """ str -> bool Found this on http://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python The function takes the IP address as a string and splits it by ".". It then checks to see if there are 4 items in the list. If not, it's not valid. Next, it makes sure the last two ch...
def largest_possible_order(num_points: int, accuracy: int) -> int: """Compute the largest diffop order such that the given accuracy is satisfied. See ``required_points`` for details.""" order = num_points - accuracy assert order >= 0 # check if the next-larger order would be boosted: if (num_po...
def convert(s, t): """convert memory size of type """ assert t in 'BKM' if t == 'B': return int(s) elif t == 'K': return int(s * 1024) else: return int(s * 1024 * 1024)
def format_fill(justify, row, widths): """format a "row" of text with fixed column widths If one column is two wide corect the width for adjacent columns Asume all column data are strings Args: justify (string): 'left' or 'right' row (list) :string data to format widt...
def right_circ_shift(x: int, shift: int, n_bits: int) -> int: """ Does a right binary circular shift on the number x of n_bits bits :param x: A number :param shift: The number of bits to shift :param n_bits: The number of bits of x :return: The shifted result """ mask = (1 << n_bits) - 1...
def start_follower_callback(request, response): """ Start the robot. In other words, allow it to move (again) """ global should_move global right_mark_count global finalization_countdown should_move = True right_mark_count = 0 finalization_countdown = None return response
def mmult(a, b): """Matrix multiplication: mmult([[11, 12], [21, 22]], [[-1, 0], [0, 1]]) returns [[-11, 12], [-21, 22]]""" return [[sum([i*j for i, j in zip(row, col)]) for col in zip(*b)] for row in a]
def get_pixel(coord, min_coord, max_coord, size): """Transform abscissa from geographical coordinate to pixel For horizontal operations, 'min_coord', 'max_coord' and 'size' refer respectively to west and east coordinates and image width. For vertical operations, 'min_coord', 'max_coord' and 'size' ref...
def cluster_kubeconfig(name, server, ca_data): """Generate and return a cluster kubeconfig object.""" return { "name": name, "cluster": { "server": server, "certificate-authority-data": ca_data, }, }
def convertRelativesToLabels(tokens: list, uniqueNumber: int = 0) -> list: """ Takes sanitised, tokenised URCL code and optionally a unique number for the label name. Returns URCL code with all relatives converted into labels. """ for index in range(len(tokens)): line = tokens[ind...
def dot_to_dict(values): """Convert dot notation to a dict. For example: ["token.pos", "token._.xyz"] become {"token": {"pos": True, "_": {"xyz": True }}}. values (iterable): The values to convert. RETURNS (dict): The converted values. """ result = {} for value in values: path = res...
def get_active_sensors(connections: set, total_input_size: int): """Get a set of all the used input-sensors based on the connections. The distance sensor is always used.""" # Exploit the fact that sensor inputs have negative connection keys used = {a + total_input_size for (a, _) in connections if a < 0} ...