content
stringlengths
42
6.51k
def format_size(num, suffix="B"): """ Credit: Fred Cirera, http://stackoverflow.com/a/1094933 """ for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0
def min_max_indexes(seq): """ Uses enumerate, max, and min to return the indices of the values in a list with the maximum and minimum value: """ minimum = min(enumerate(seq), key=lambda s: s[1]) maximum = max(enumerate(seq), key=lambda s: s[1]) return minimum[0], maximum[0]
def AddSysPath(new_path): """ AddSysPath(new_path): adds a directory to Python's sys.path Does not add the directory if it does not exist or if it's already on sys.path. Returns 1 if OK, -1 if new_path does not exist, 0 if it was already on sys.path. """ import sys, os # Avoid adding nonexis...
def sdss_url(ra: float, dec: float): """ Construct URL for public Sloan Digital Sky Survey (SDSS) cutout. from SkyPortal """ return ( f"http://skyserver.sdss.org/dr12/SkyserverWS/ImgCutout/getjpeg" f"?ra={ra}&dec={dec}&scale=0.3&width=200&height=200" f"&opt=G&query=&Grid=on"...
def is_array(value): """Check if value is an array.""" return isinstance(value, list)
def _lax_friedrichs_flux(d_f, d_u, n_x, c): """Computes the Lax-Friedrichs flux.""" return 0.5 * n_x * d_f + 0.5 * c * d_u
def parse_arg_list_int(list_int): """Parse an argument as a list of integers.""" try: params = [int(param) for param in list_int.split(",")] except: raise AttributeError() return params
def make_population(population_size, solution_generator, *args, **kwargs): """Make a population with the supplied generator.""" return [ solution_generator(*args, **kwargs) for _ in range(population_size) ]
def compute_border_indices(log2_T, J, i0, i1): """ Computes border indices at all scales which correspond to the original signal boundaries after padding. At the finest resolution, original_signal = padded_signal[..., i0:i1]. This function finds the integers i0, i1 for all temporal subsamplings...
def open_file(input_file): """Check if the file format entered is supported""" try: teste = open(input_file, "r") teste.close() return True except FileNotFoundError: print('"%s"' % input_file, "not found. Type again: ") return False
def underscore_targets(targets): """ Takes in a list of targets and prefixes them with an underscore if they do not have one. """ result = [] for target in targets: t = target if target[0] != '_': t = '_' + t result.append(t) return result
def get_spanner_instance_config(project_id, config): """ Generate the instance config URL """ return "projects/{}/instanceConfigs/{}".format(project_id, config)
def get_resource_by_path(path, resources): """gets the resource that matches given path Args: path (str): path to find resources (list(str)): list of resources Returns: dict: resource that matches given path, None otherwise """ return next( (x for x in resources if ...
def generate_latex_label(label_id): """Generates a LaTeX label with the given ID""" return "\\label{%s}" % label_id
def get_tags(sections): """ Credit: https://www.kaggle.com/davidmezzetti/cord-19-analysis-with-sentence-embeddings Searches input sections for matching keywords. If found, returns the keyword tag. Args: sections: list of text sections Returns: tags """ keywords = ["2019-nco...
def generate_xmas_tree1(rows=10): """Generate a xmas tree of stars (*) for given rows (default 10). Each row has row_number*2-1 stars, simple example: for rows=3 the output would be like this (ignore docstring's indentation): * *** *****""" width = rows * 2 output = [] ...
def red(s): """ Return the given string (``s``) surrounded by the ANSI escape codes to print it in red. :param s: string to console-color red :type s: str :returns: s surrounded by ANSI color escapes for red text :rtype: str """ return "\033[0;31m" + s + "\033[0m"
def hasNumbers(inputString): """ Tests to see if the ticker has numbers. Param: inputString (any string) like "TSLA" or "INTC" """ return any(char.isdigit() for char in inputString)
def prepare_log(message, code=""): """ It gives a different look to your logs so that you can easily identify them. :param message: message you want to log :param code: error code if you want to log error (optional) :return: styled log message """ if code: message = f"|~| {messag...
def split_at_linelen(line, length): """Split a line at specific length for code blocks or other formatted RST sections. """ # Get number of splits we should have in line i = int(len(line)/length) p = 0 while i > 0: p = p+length # If position in string is not a space ...
def encode(number, base): """Encode given number in base 10 to digits in given base. number: int -- integer representation of number (in base 10) base: int -- base to convert to return: str -- string representation of number (in given base)""" # Handle up to base 36 [0-9a-z] assert 2 <= base <= ...
def get_as_subtext_field(field, field_title=None) -> str: """Get a certain variable as part of the subtext, along with a title for that variable.""" s = "" if field: s = f"{field} | " else: return "" if field_title: s = f"{field_title}: " + s return s
def Zip(*data, **kwargs): """Recursive unzipping of data structure Example: Zip(*[(('a',2), 1), (('b',3), 2), (('c',3), 3), (('d',2), 4)]) ==> [[['a', 'b', 'c', 'd'], [2, 3, 3, 2]], [1, 2, 3, 4]] Each subtree in the original data must be in the form of a tuple. In the **kwargs, you can set the funct...
def pres_text(trial): """ input: current presentation trial # (int) output: presentation instruction text (string) for given presentation trial """ pres1 = ' Now we will begin the main experiment! ' \ 'Again you will see cue icons, followed by a series of image pairs and letters...
def list_to_dict(object_list, key_attribute='id'): """Converts an object list to a dict :param object_list: list of objects to be put into a dict :type object_list: list :param key_attribute: object attribute used as index by dict :type key_attribute: str :return: dict containing the object...
def check_uniqueness_in_columns(board: list): """ Check buildings of unique height in each column. Return True if buildings in all columns column have unique height, False otherwise. >>> check_uniqueness_in_columns(['***21**', '412453*', '423145*', '*543215',\ '...
def make_name(url: str): """ Auxiliary function to retrieve CIF name from an URL Parameters ---------- url : An URL for a CIF in COD. Returns ------- A CIFname string from an URL from COD """ return url.split("/")[-1].split(".")[0] + ".cif"
def validate_image_choices(dep_var, x_dim, bs, splits, num_epochs, num_channels): """ Checks to see if user choices are consistent with expectations Returns failure message if it fails, None otherwise. """ splits = [float(num) for num in splits] if sum(splits) != 1: return 'Splits must ...
def get_all_keys(items): """Get all keys in a list of dictionary. Parameters ---------- items : list List of dictionaries. Returns ------- list List containing all keys in the dictionary. """ ret = [] if not hasattr(items, "__iter__"): return ret if ...
def cube_shade(x, y, z, n): """Return the color diference between the sides of the cube.""" return [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, # top 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, # bottom 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ...
def get_mirror_vertex_index(symmetry_table, vertex_index): """ Function that uses symmetry table to return symmetrical vertex index of the given 1; -1 if failed :param vertex_index: int :return: int """ mirror_index = -1 if not symmetry_table: return mirror_index for i in rang...
def circulation_default_extension_max_count(loan): """Return a default extensions max count.""" return float("inf")
def partition(array, start, end): """ sets up markers for pivot point, left marker and right marker then iteratively swap into place as the markers converge""" # initialize variables piv = array[start] left = start+1 right = end done = False # create switch while not done: ...
def count_offspring(cycle: int, days: int) -> int: """Counts how many offspring will be spawn over a given period""" if cycle >= days: return 1 if cycle == 0: return count_offspring(8, days - 1) + count_offspring(6, days - 1) return count_offspring(cycle - 1, days - 1)
def destination_index(circle): """ >>> destination_index([3, 2, 5, 4, 6, 7]) (2, 1) >>> destination_index([2, 5, 4, 6, 7, 3]) (7, 4) >>> destination_index([5, 8, 9, 1, 3, 2]) (3, 4) """ val_next = circle[0] - 1 while val_next not in circle: val_next -= 1 if val_ne...
def addprint(x: int, y: int): """Print and "added" representation of `x` and `y`.""" expr = x + y return "base addprint(x=%r, y=%r): %r" % (x, y, expr)
def latexify_n2col(x, nplaces=None, **kwargs): """Render a number into LaTeX in a 2-column format, where the columns split immediately to the left of the decimal point. This gives nice alignment of numbers in a table. """ if nplaces is not None: t = '%.*f' % (nplaces, x) else: t...
def create_login_role(username, password): """Helper method to construct SQL: create role.""" # "create role if not exists" is not valid syntax return f"DROP ROLE IF EXISTS {username}; CREATE ROLE {username} WITH CREATEROLE LOGIN PASSWORD '{password}';"
def identifyByCurrent(abfIDs, slopesDrug, slopesBaseline,threshold): """ Identify a responder by asking whether the change of current is BIGGER than a given threshold. """ responders=[] nonResponders=[] for i in range(len(abfIDs)): deltaCurrent = round(slopesDrug[i]-slopesBaseline[i],3) ...
def to_time_unit_string(seconds, friendlier=True): """Converts seconds to a (friendlier) time unit string, as 1h, 10m etc.)""" seconds_str = str(seconds).replace('.0', '') if seconds_str == '60': seconds_str = '1m' elif seconds_str == '600': seconds_str = '10m' elif seconds_str =...
def find_missing_number(array: list): """return the missing number in the continuous integer sequence""" array.sort() missing = 0 for index, number in enumerate(array): if index != number: missing = index print(f'Missing from the continuous sequence: {index}') break return missing
def parse_boolean(s): """Takes a string and returns the equivalent as a boolean value.""" s = s.strip().lower() if s in ("yes", "true", "on", "1"): return True elif s in ("no", "false", "off", "0", "none"): return False else: raise ValueError("Invalid boolean value %r" % s)
def grid_dist(pos1, pos2): """ Get the grid distance between two different grid locations :param pos1: first position (tuple) :param pos2: second position (tuple) :return: The `manhattan` distance between those two positions """ x1, y1 = pos1 x2, y2 = pos2 dy = y2 - y1 dx = x2 -...
def export_stop_mask_pft(pve_wm, pve_gm, pve_csf): """ full path to a nifti file containing the tractography stop mask """ return {"stop_file": [pve_wm, pve_gm, pve_csf]}
def gCallback(dataset, geneid, colors): """Callback to set initial value of green slider from dict. Positional arguments: dataset -- Currently selected dataset. geneid -- Not needed, only to register input. colors -- Dictionary containing the color values. """ colorsDict = colors try: ...
def false_discovery_rate(cm): """ false discovery rate (FDR) FDR = FP / (FP + TP) = 1 - PPV """ return cm[0][1] / float(cm[0][1] + cm[1][1])
def ordered(obj): """Helper function for dict comparison. Recursively orders a json-like dict or list of dicts. Args: obj: either a list or a dict Returns: either a sorted list of elements or sorted list of tuples """ if isinstance(obj, dict): return sorted((k, ordered...
def scale_ticks_params(tick_scale='linear'): """ Helper function for learning cureve plots. Args: tick_scale : available values are [linear, log2, log10] """ if tick_scale == 'linear': base = None label_scale = 'Linear Scale' else: if tick_scale == 'log2': ...
def inject_into_param(ptype, max_tests, inst_idxs, inst_params, prev_inj_insts, cur_inst_idx, common_params): """ Decide if the implicitly given parameter should be injected into. :param ptype: "GET" or "POST" :param max_tests: maximum times a parameter should be injected into :param inst_idxs: lis...
def replace_by_list(my_string, list_strs, new_value): """ Applies a character override to a string based on a list of strings """ for s in list_strs: my_string = my_string.replace(s, new_value) return my_string
def dependencyParseAndPutOffsets(parseResult): """ Args: parseResult: Returns: (rel, left{charStartOffset, charEndOffset, wordNumber}, right{charStartOffset, charEndOffset, wordNumber}) dependency parse of the sentence where each item is of the form """ dParse = parseResult[...
def remove_empty_from_dict(original): """get a new dict which removes keys with empty value :param dict original: original dict, should not be None :return: a new dict which removes keys with empty values """ return dict((k, v) for k, v in original.items() if v is not None and v != ...
def find_max_difference(array_1, array_2): """Find the maximum absolute difference between array_1[j] and array_2[j].""" return max([abs(array_1[j] - array_2[j]) for j in range(len(array_1))])
def is_proper_position(dimension, position): """ Check whether the given position is a proper position for any board with the given dimension. - The given position must be a tuple of length 2 whose elements are both natural numbers. - The first element identifies the ...
def map_module(mod): """Map module names as needed""" if mod == "lambda": return "awslambda" return mod
def _text_color(route_color: str): """Calculate if route_text_color should be white or black""" # This isn't perfect, but works for what we're doing red, green, blue = int(route_color[:2], base=16), int(route_color[2:4], base=16), int(route_color[4:6], base=16) yiq = 0.299 * red + 0.587 * green + 0.114 ...
def translate_dna_to_peptide(dna_str): """ Translate a DNA sequence encoding a peptide to amino-acid sequence via RNA. If 'N' is included in input dna, 'X' will be outputted since 'N' represents uncertainty. Also will output a flag indicating if has stop codon. Parameters ---------- dna_str: s...
def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float: """Return an linearly annealed epsilon Epsilon will decrease over time until it reaches `target_episode` (epsilon) | max_e ---|\ | \ | \ | \ mi...
def is_triangular(k): """ k, a positive integer returns True if k is triangular and False if not """ triangular_number = 0 for i in range(1, k+1): triangular_number = triangular_number + i if triangular_number == k: return True elif triangular_number > k: ...
def jinja2_split(env, s, ch): """Splits string 's' with character 'ch' as delimiter into a list of parts. """ return s.split(ch)
def isPowerOfTwo_ver2(n: int) -> bool: """ :type n: int :rtype: bool - returns true if n is power of 2, false otherwise """ return n > 0 and bin(n).count("1") == 1
def find_message(text): """Find a secret message""" return ''.join(a for a in text if ord(a) in range (65, 91))
def get_boolean(value) -> bool: """Convert a value to a boolean. Args: value: String value to convert. Return: bool: True if string.lower() in ["yes", "true"]. False otherwise. """ bool_val = False try: if value.lower() in ["yes", "true"]: bool_val = True ...
def maybe_download(train_data, test_data, train2_data=""): """Maybe downloads training data and returns train and test file names.""" if train_data: train_file_name = train_data else: train_file_name = "training_data.csv" if test_data: test_file_name = test_data else: #test_file_name = "./dat...
def read_image(filename): """Read in the file from path and return the opaque binary data :rtype: str """ with open(filename) as handle: return handle.read()
def deleteDuplicateLabels(tokens: list) -> list: """ Takes sanitised, tokenised URCL code. Returns URCL code with all duplicated labels removed. """ index = 0 while index < len(tokens) - 1: line = tokens[index] line2 = tokens[index + 1] if line[0].startswith(".") an...
def row_to_index(row): """ Returns the 0-based index of given row name. Parameters ---------- row : int or unicode Row name. Returns ------- int 0-based row index. Examples -------- >>> row_to_index('1') 0 """ row = int(row) assert row > 0...
def binary_search(lst, val): """This function will bring in a list and a value. Returns index of value or -1 if value not found.""" status = False for n in range(len(lst)): if lst[n] == val: status = True return n if status is False: return -1
def getlimit(code, aname): """ :param code: :param aname: :return: """ if code[:-1] == '15900' or code == '511880' or code == '511990' or code == '131810' or code == '204001': return 1000000 else: if aname == 'a1': return 0 # 10000#0 means except money fund, no...
def get_hour(day_str): """ UTILITY FUNCTION just returns the hour from the date string. USED in ((apply)) method to create a column of hours. """ return day_str[11:13]
def isfloat(value): """ Check input for float conversion. :param value: input value :type value:str :return: True if input_value is a number and False otherwise """ try: float(value) return True except ValueError: return False
def dict_to_one(dp_dict): """Input a dictionary, return a dictionary that all items are set to one. Used for disable dropout, dropconnect layer and so on. Parameters ---------- dp_dict : dictionary The dictionary contains key and number, e.g. keeping probabilities. """ return {x: ...
def print_matrix(matrix): """ :param matrix:print_matrix :return:None """ if not matrix: return None start = 0 row = len(matrix) col = len(matrix[0]) while row > start * 2 and col > start * 2: # one round col_end = col - start - 1 row_end = row - star...
def _get_module_name(module): """returns a module's name""" # multiprocessing imports the __main__ module into a new module called # __parents_main__ and then renames it. We need the modulename to # always be the same as the one in the parent process. if module.__name__ == "__parents_main__": ...
def compute_applicable_changes(previous_applicable_steps, applicable_steps): """ Computes and returns the new applicable steps and the no longer applicable steps from previous and current list of applicable steps """ new_applicable_steps = [] no_longer_applicable_steps = [] # new applicable...
def parse_nat_msg(msg): """ Parse a syslog message from the nat program into a python dictionary. :param msg: nat msg from syslog :return: a dictionary of nat related key value pairs """ dnat_in = '' out = '' mac = '' src = -1 dest = -1 len_ = -1 tos = -1 proc = -1 ...
def hex_to_rgb(col_hex): """Convert a hex colour to an RGB tuple""" col_hex = col_hex.lstrip("#") return bytearray.fromhex(col_hex)
def merge(left_array, right_array): """Merge two sorted lists into one sorted list Note: this function is a helper method for merge sort. It doesn't work correctly with unsorted input params. Implemented as a public function because of usage in multiprocess modification of a mer...
def make_list_slug(name): """Return the slug for use in url for given list name.""" slug = name.lower() # These characters are just stripped in the url for char in '!@#$%^*()[]{}/=?+\\|': slug = slug.replace(char, '') # These characters get replaced slug = slug.replace('&', 'and') sl...
def read_gtf(feature_filename, sources, types): """ Parse feature_filename and return: 1) a dictionary of features keyed by IDs and 2) a dictionary mapping features to IDs. :param feature_filename: :param sources: :param types: :return: """ types = set(types) features, feature_...
def where_to_go(point1, point2, separator): """ Takes in two integers, point1 and point2, and a string separator. Returns all the integers between point1 and point2 with the string separator separating each integer. Parameters: point1: Starting point/integer. point2: Ending point/in...
def truncate_down_to_maxlen(split_sentence, maxlen): """ function used to truncate a sentence down to maxlen words """ # truncate it truncated_split_sentence = split_sentence[:maxlen] # return the rejoined sentence return " ".join(truncated_split_sentence)
def make_baseurl(scheme, host, port=None): """Creates URL using given parameters. Args ----- scheme (str): http or https host (str): hostname port (int, optional): Port number as integer Returns ------- Formatted URL to use with http apis. """ base_url = Non...
def normalizeAngle(angle): """ :param angle: (float) :return: (float) the angle in [-pi, pi] """ # while angle > np.pi: # angle -= 2 * np.pi # while angle < -np.pi: # angle += 2 * np.pi # return angle return angle
def problem_1_3(left: str, right: str) -> bool: """ Given two strings, write a method to decide if one is a permutation of the other. So, I could iterate through a range of indicies and construct a single hashmap to store the counts of a character. We can add from one str and remove from the other. Thi...
def get_subclass_dict(cls): """Get a dictionary with the subclasses of class 'cls'. This method returns a dictionary with all the classes that inherit from class cls. Note that this method only works for new style classes :param cls: class to which we want to find all subclasses :type cls: cla...
def _get_perm_phase(order, phase): """Get the phase of the given permutation of points.""" n_points = len(order) return phase ** sum( 1 for i in range(n_points) for j in range(i + 1, n_points) if order[i] > order[j] )
def _ParseHeader(header): """Parses a str header into a (key, value) pair.""" key, _, value = header.partition(':') return key.strip(), value.strip()
def getCountsAndAverages(IDandRatingsTuple): """ Calculate average rating Args: IDandRatingsTuple: a single tuple of (MovieID, (Rating1, Rating2, Rating3, ...)) Returns: tuple: a tuple of (MovieID, (number of ratings, averageRating)) """ rateCnt = len(IDandRatingsTuple[1]) return...
def consume_token(s, token, l_trunc=0, r_trunc=0, strip_leading=True): """ :param s: String to scan :param token: Substring to target :param l_trunc: Truncate chars from left; Positive integer :param r_trunc: Truncate chars from right; Positive integer :param strip_leading: Remove leading whites...
def angleToInt(angle): """ Converts an angle to an integer the servo understands """ return int(angle/300.0*1023)
def titleToURL(wikiTitles:list): """ Observations: Function converts wikipadia titles to urls From observation, wikipedia urls are just https://en.wikipedia.org/wiki/ followed by title having their spaces replaced with "_" i.e. a wiki page with the title "C...
def y_gradient(y, constraint_set): """ Computes y gradient """ constraint_keys = constraint_set['constraints'] gradient = 0 for key in constraint_keys: current_constraint = constraint_set[key] a_matrix = current_constraint['A'] bound_loss = current_constraint['...
def strsize(b): """Return human representation of bytes b. A negative number of bytes raises a value error.""" if b < 0: raise ValueError("Invalid negative byte number") if b < 1024: return "%dB" % b if b < 1024 * 10: return "%dKB" % (b // 1024) if b < 1024 * 1024: ...
def kvp_string_to_rec(string): """Take an input string 'a=b,c=d,e=f' and return the record {'a':'b','c':'d','e':'f'}""" rec = {} for kvp in string.split(','): arr = kvp.split('=') if len(arr) > 2: raise Exception("Cannot convert %s to KVP" % string) rec[arr[0]] = arr[...
def validate_scale_increment(value, _): """Validate the `scale_increment` input.""" if value is not None and not 0 < value < 1: return 'scale increment needs to be between 0 and 1.'
def get_instance_data(sample_annotation_data: list): """Gets a dictionary mapping every instance token -> data about it Args: sample_annotation_data (list): a list of dictionaries with sample annotation information Returns: dict: a dictionary mapping instance_tokens to dicts ab...
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ z,o = 0,0 t = len(input_list) - 1 while o <= t: if input_list[o] == 0: input_list[o], input_list...
def jaccard(seq1, seq2): """ Computes the distance between two sequences using the formula below: D(X, Y) = 1 - |X intersection Y| / |X union Y| :type seq1: a list of of strings :param seq1: a sequence :type seq2: a list of of strings :param seq2: a sequence :return dist: the distance ...
def line_line_intersection(x1, y1, x2, y2, x3, y3, x4, y4, infinite=False): """ Determines the intersection point of two lines, or two finite line segments if infinite=False. When the lines do not intersect, returns an empty list. """ # Based on: P. Bourke, http://local.wasp.uwa.edu.au/~pbourke/geom...