content
stringlengths
42
6.51k
def polygon (points, extrude=0): """ Function translate return openscad polygon command @param points: points of the polygon """ if extrude > 0: extrude = "linear_extrude(height={})".format(extrude) else: extrude = "" return "{} polygon(points={});".format(extrude, points)
def create_equation_from_terms(terms): """ Create a string equation (right hand side) from a list of terms. >>> create_equation_from_terms(['x','y']) 'x+y' >>> create_equation_from_terms(['-x', 'y', '-z']) '-x+y-z' :param terms: list :return: str """ if len(terms) == 0: return '' for i in range(0, len(terms)): term = terms[i].strip() if not term[0] in ('+', '-'): term = '+' + term terms[i] = term if terms[0][0] == '+': terms[0] = terms[0].replace('+', '') eqn = ''.join(terms) return eqn
def extract_objective(objective_field): """Extract the objective field id from the model structure """ if isinstance(objective_field, list): return objective_field[0] return objective_field
def findAllOfStyle( cls, forms ) : """ Find all the occurences of a guven style class from a list of style classes. """ formsFound = [] for form in forms : if( isinstance( form, cls ) ) : formsFound.append( form ) return( formsFound )
def list_all_items_inside(_list, *items): """ is ALL of these items in a list? """ return all([x in _list for x in items])
def deriv1(x, y, i, n): """ Alternative way to smooth the derivative of a noisy signal using least square fit. In this method the slope in position 'i' is calculated by least square fit of 'n' points before and after position. Required Parameters ---------- x : array of x axis y : array of y axis n : smoothing factor i : position """ m_, x_, y_, xy_, x_2 = 0., 0., 0., 0., 0. for ix in range(i, i + n, 1): x_ = x_ + x[ix] y_ = y_ + y[ix] xy_ = xy_ + x[ix] * y[ix] x_2 = x_2 + x[ix]**2 m = ((n * xy_) - (x_ * y_))/(n * x_2 - (x_)**2) return(m)
def one(iterable): """Return the single element in iterable. Raise an error if there isn't exactly one element. """ item = None iterator = iter(iterable) try: item = next(iterator) except StopIteration: raise ValueError('Iterable is empty, must contain one item') try: next(iterator) except StopIteration: return item else: raise ValueError('object contains >1 items, must contain exactly one.')
def binary_search_by_recursion(sorted_collection, item, left, right): """Pure implementation of binary search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) 0 >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) 4 >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) 1 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) """ if right < left: return None midpoint = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1) else: return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
def parse_imag(data): """returns real and imaginary components""" real = [n.real for n in data] imag = [n.imag for n in data] return real, imag
def ravel(nlabel_list): """ only up to 2D for now. """ if not isinstance(nlabel_list, list): return nlabel_list raveled = [] for maybe_list in nlabel_list: if isinstance(maybe_list, list): for item in maybe_list: raveled.append(item) else: raveled.append(maybe_list) return raveled
def check_for_real_numbers(value): """check if inputed value is a real number""" val = value if value[0] == '-': val = value[1:len(value)] if val.find("."): if (val.replace(".", "1", 1)).isnumeric() is False: return False else: if val.isnumeric(): return False return True
def stability_selection_to_threshold(stability_selection, n_boots): """Converts user inputted stability selection to an array of thresholds. These thresholds correspond to the number of bootstraps that a feature must appear in to guarantee placement in the selection profile. Parameters ---------- stability_selection : int, float, or array-like If int, treated as the number of bootstraps that a feature must appear in to guarantee placement in selection profile. If float, must be between 0 and 1, and is instead the proportion of bootstraps. n_boots: int The number of bootstraps that will be used for selection """ # float, indicating proportion of bootstraps if isinstance(stability_selection, float): selection_threshold = int(stability_selection * n_boots) # int, indicating number of bootstraps elif isinstance(stability_selection, int): selection_threshold = stability_selection else: raise ValueError("Stability selection must be a valid float or int.") # ensure that ensuing list of selection thresholds satisfies # the correct bounds if not ( selection_threshold <= n_boots and selection_threshold >= 1 ): raise ValueError("Stability selection thresholds must be within " "the correct bounds.") return selection_threshold
def evaluate(x,y): """ Evaluates Rosenbrock function. @ In, x, float, value @ In, y, float, value @ Out, evaluate, value at x, y """ return (1- x)**2 + 100*(y-x**2)**2
def make_iterable(a): """ Check if a is iterable and if not, make it a one element tuple """ try: iter(a) return a except TypeError: return (a, )
def has_pattern(guesses, pattern): """Return True if `guesses` match `pattern`.""" result = len(guesses) >= len(pattern) if result: for guess, check in zip(guesses, pattern): result = result and guess.has(**check) if not result: break return result
def format_element(eseq): """Format a sequence element using FASTA format (split in lines of 80 chr). Args: eseq (string): element sequence. Return: string: lines of 80 chr """ k = 80 eseq = [eseq[i:min(i + k, len(eseq))]for i in range(0, len(eseq), k)] return("\n".join(eseq))
def score_seating(seating, preferences): """Score seating using preferences.""" score = 0 table_size = len(seating) for index, name in enumerate(seating): for seat_index in ((index - 1) % table_size, (index + 1) % table_size): seating_by = seating[seat_index] score += preferences.get(name, {}).get(seating_by, 0) return score
def run_length_encode(s): """ Return run-length-encoding of string s, e.g.:: 'CCC-BB-A' --> (('C', 3), ('-', 1), ('B', 2), ('-', 1), ('A', 1)) """ out = [] last = None n = 0 for c in s: if c == last: n += 1 else: if last is not None: out.append((last, n)) last = c n = 1 if last is not None: out.append((last, n)) return tuple(out)
def safeissubclass(cls, cls_or_tuple): """Like issubclass, but if `cls` is not a class, swallow the `TypeError` and return `False`.""" try: return issubclass(cls, cls_or_tuple) except TypeError: # "issubclass() arg 1 must be a class" pass return False
def split_section(input_file, section_suffix, test_function): """ Split a pipfile or a lockfile section out by section name and test function :param dict input_file: A dictionary containing either a pipfile or lockfile :param str section_suffix: A string of the name of the section :param func test_function: A test function to test against the value in the key/value pair >>> split_section(my_lockfile, 'vcs', is_vcs) { 'default': { "six": { "hashes": [ "sha256:832dc0e10feb1aa2c68dcc57dbb658f1c7e65b9b61af69048abc87a2db00a0eb", "sha256:70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9" ], "version": "==1.11.0" } }, 'default-vcs': { "e1839a8": { "editable": true, "path": "." } } } """ pipfile_sections = ('packages', 'dev-packages') lockfile_sections = ('default', 'develop') if any(section in input_file for section in pipfile_sections): sections = pipfile_sections elif any(section in input_file for section in lockfile_sections): sections = lockfile_sections else: # return the original file if we can't find any pipfile or lockfile sections return input_file for section in sections: split_dict = {} entries = input_file.get(section, {}) for k in list(entries.keys()): if test_function(entries.get(k)): split_dict[k] = entries.pop(k) input_file['-'.join([section, section_suffix])] = split_dict return input_file
def to_bytes(value): """ returns 8-byte big-endian byte order of provided value """ return value.to_bytes(8, byteorder='big', signed=False)
def remove_key(d, key): """ Remove an entry from a dictionary . """ r = d.copy() del r[key] return r
def is_gzipped(file_location): """ Determines whether or not the passed file appears to be in GZIP format. ARGUMENTS file_location (str): the location of the file to check RETURNS gzipped (bool): whether or not the file appears to be in GZIP format """ GZIP = ".gz" if file_location.endswith(GZIP): gzipped = True else: gzipped = False return gzipped
def ssh_url_to_https_url(url: str) -> str: """Convert git ssh url to https url :param url: ssh url to be converted :return: Returns git https url as string """ if ".git" in url[-4:]: return url.replace(":", "/", 1).replace("git@", "https://") return url.replace(":", "/", 1).replace("git@", "https://") + ".git"
def read_record(file_path, default=None): """ Reads the first line of a file and returns it. """ try: f = open(file_path, 'r') try: return f.readline().strip() finally: f.close() except IOError: return default
def cost_memory_removed(size12, size1, size2, k12, k1, k2): """The default heuristic cost, corresponding to the total reduction in memory of performing a contraction. """ return size12 - size1 - size2
def str_to_latex(string): """do replacements in ``string`` such that it most likely compiles with latex """ #return string.replace('\\', r'\textbackslash{}').replace('_', '\\_').replace(r'^', r'\^\,').replace(r'%', r'\%').replace(r'~', r'\ensuremath{\sim}').replace(r'#', r'\#') return string.replace('\\', r'\textbackslash{}').replace('_', ' ').replace(r'^', r'\^\,').replace(r'%', r'\%').replace(r'~', r'\ensuremath{\sim}').replace(r'#', r'\#')
def linear_approximation_complex(x, x1, y1, x2, y2): """Linear approximation for complex arguments""" return complex((y1.real - y2.real) / (x1 - x2) * x + (y2.real * x1 - x2 * y1.real) / (x1 - x2), (y1.imag - y2.imag) / (x1 - x2) * x + (y2.imag * x1 - x2 * y1.imag) / (x1 - x2))
def cleanup_authorizer(authorize): """Given a dictionary of a comment authorizer record, return a new dictionary for output as JSON.""" auth_data = authorize auth_data["id"] = str(auth_data["_id"]) auth_data["authorizer"] = str(auth_data["authorizer"]) auth_data["authorized"] = str(auth_data["authorized"]) del auth_data["_id"] return auth_data
def d(value): """ Discretizes variables that are > 0, sets them to zero if < 1 Args: alue(float): value to be discretized Returns (float): discretized value """ if value < 1: return 0 else: return value
def get_class_name(obj) -> str: """ Get an arbitrary objects name. :param obj: any object :return: name of the class of the given object """ return obj.__class__.__name__
def adjust_timestamp_from_js_to_python(jsTimestamp): """ javascript and python produce slightly different POSIX timestamps. This converts the javascript timestamps to python. args: jsTimestamp: this should come from the client. It will probably be the output of Date.now() returns: converted timestamp """ return float(jsTimestamp)/1000
def _tag_depth(path, depth=None): """Add depth tag to path.""" # All paths must start at the root if not path or path[0] != '/': raise ValueError("Path must start with /!") if depth is None: depth = path.count('/') return "{}{}".format(depth, path).encode('utf-8')
def serialize_func(fun, args): """ Serializes callable object with arguments :param fun: callable object :param args: arguments :return: dictionary with 'module', 'fun' and 'args' """ return { 'module': fun.__module__, 'fun': fun.__name__, 'args': args }
def TokenFromUrl(url): """Extracts the AuthSub token from the URL. Returns the raw token value. Args: url: str The URL or the query portion of the URL string (after the ?) of the current page which contains the AuthSub token as a URL parameter. """ if url.find('?') > -1: query_params = url.split('?')[1] else: query_params = url for pair in query_params.split('&'): if pair.startswith('token='): return pair[6:] return None
def msg_to_array(msg): """ convert string to lowercased items in list """ return [word.strip().lower() for word in msg.strip().split()]
def fixme_pattern(word): """ It is essential to have same pattern between build.py and mmd2doc.py, so keeping pattern construction here """ # **OPEN**: blah # OPEN[John Doe]: blah blah # **OPEN[John Doe]:** blah blah # <mark>OPEN[John Doe]:</mark> blah blah # <mark>OPEN[John Doe]</mark>: blah blah # OPEN - blah blah blah return r'(?i)(\b%s\b(?:\\?\[[^]]+\\?\]|</mark>|[ \t]*[:\-\*]+)+[ \t]*)(?=\S)'%word
def check_col(board, num_rows, num_cols): """check if any 4 are connected vertically(in 1 column) returns bool""" won = False for row in range(num_rows - 3): for col in range(num_cols): start = board[row][col] if start == " ": continue won = True for i in range(1, 4): if start != board[row + i][col]: won = False break if won: return won return won
def getValue(dictionary, key, value): """ Returns the value for the key in the dictionary or the default. :param dict dictionary: :param object key: :param object value: :return object: """ if not key in dictionary.keys(): return value else: return dictionary[key]
def check_managability(user, note, action): """ Determine if user can edit or delete this note. This note can be edited or deleted if at least one of the following criteria is met: - user is an admin - user is the author of the note - user is member of a group in groups AND note is proper permission is set - note is public and proper permission is set Args: user: django User object note: Note object action: (str) name of action to check for (edit or delete) Returns (bool): True if this note can be managed by the provided user False if this note can not be managed by the provided user """ if action not in 'editdelete': return False if user.is_superuser: return True if note.author == user: return True if note.scope == 'group' and \ any(i in user.groups.all() for i in note.groups.all()) and \ action in note.permissions: return True if note.scope == 'public' and action in note.permissions: return True return False
def to_list(value): """ Create an array from any kind of object """ if value is None: return [] initial_list = [x.strip() for x in value.translate(None, '!@#$[]{}\'"').split(',')] return [x for x in initial_list if x]
def to_csv_str(s: str): """Escapes a string that is supposed to be written to a csv file""" return s.replace('\n', '\\n')
def extract_z(lst): """ Extract z coordinate from list with x, y, z coordinates :param lst: list with [[x, y, z], ..., [x, y, z]] :return: list with z coordinates [x, ..., x] """ return [item[2] for item in lst]
def crunchHomopolymers(motifList): """ Take as input a list of target motifs, collapse poly-nucleotide tracks, return list of collapsed motifs. """ # List to catch all collapsed motifs. crunchList = list() # For each motif for motif in motifList: # Create empty list to catch not repeated bases. noReps = list() # Walk through original motif base-by-base. for base in motif: # If list of kept bases in empty, add first base. if not noReps: noReps.append(base) # If list exists and base is not same as last, store new base. elif base != noReps[-1]: noReps.append(base) # Convert list to string and store new motif crunchList.append(''.join(noReps)) # Convert to set to remove duplicates and return return list(set(crunchList))
def binarize(threshold=0.5): """ binarize the tensor with a fixed threshold, values above the threshold will be set to one, values below the threshold to zero """ dict_binarize = {'name': 'binarize', 'kwargs': {'threshold': threshold} } return dict_binarize
def q_to_nu(q): """Convert mass ratio (>= 1) to symmetric mass ratio.""" return q / (1. + q)**2.
def mag2counts(mag, band): """ Converts AB magnitudes to GALEX counts per second. See: http://asd.gsfc.nasa.gov/archive/galex/FAQ/counts_background.html :param mag: The AB magnitude to convert. :type mag: float :param band: The band to use, either 'FUV' or 'NUV'. :type band: str :returns: float -- The converted flux in counts per second. """ scale = 18.82 if band == 'FUV' else 20.08 return 10.**(-(mag-scale)/2.5)
def get_slice(seq, start=0, stop=None, step=1): """Get a slice of a sequence with variable step. Specify start,stop,step.""" if stop == None: stop = len(seq) item = lambda i: seq[i] return list(map(item,range(start,stop,step)))
def minmax(data): """ Return a pair (min, max) of list arg """ lo = 0 hi = 0 for i in data: if i > hi: hi = i if i < lo: lo = i return lo, hi
def parse_version(version): """convert version to int""" if version is None: raise ValueError("sbe:messageSchema/@version is required") return int(version)
def _inject_args(sig, types): """ A function to inject arguments manually into a method signature before it's been parsed. If using keyword arguments use 'kw=type' instead in the types array. sig the string signature types a list of types to be inserted Returns the altered signature. """ if '(' in sig: parts = sig.split('(') sig = '%s(%s%s%s' % ( parts[0], ', '.join(types), (', ' if parts[1].index(')') > 0 else ''), parts[1] ) else: sig = '%s(%s)' % (sig, ', '.join(types)) return sig
def addStationRiverID(station, riverIDs): """Adds river ID to station dictionary.""" stationID = station["id"] riverID = riverIDs.get(stationID) station["riverId"] = riverID return station
def rotate_list(l): """ Rotate a list of lists :param l: list of lists to rotate :return: """ return list(map(list, zip(*l)))
def format_discord_str(discord_id: int, type_chars: str) -> str: """Formats an ID into a Discord's representation of a channel / role / user mention.""" return f"<{type_chars}{discord_id}>"
def calculate_amortization_amount(principal: float, interest_rate: float, period: int) -> float: """ Calculates Amortization Amount per period :param principal: Principal amount :param interest_rate: Interest rate per period :param period: Total number of period :return: Amortization amount per period """ adjusted_interest = interest_rate / 12 x = (1 + adjusted_interest) ** period return round(principal * (adjusted_interest * x) / (x - 1), 2)
def reverse_string(s): """ Reverses order or characters in string s. """ return s[::-1]
def beta_expval(alpha, beta): """ Expected value of beta distribution. """ return 1.0 * alpha / (alpha + beta)
def _sort_and_merge_sub_arrays(left_array, right_array): """This method assumes elements in `left_array` and `right_array` are already sorted. Parameters ---------- left_array: list[int] right_array: list[int] Returns ------- list: merged and sorted list """ left_array_length = len(left_array) right_array_length = len(right_array) # Creating a placeholder with zeros. merged_array = (left_array_length + right_array_length) * [0] left_index = 0 right_index = 0 current_index = 0 while left_index < left_array_length or right_index < right_array_length: # merging by sorting. if left_index < left_array_length and right_index < right_array_length: if left_array[left_index] > right_array[right_index]: merged_array[current_index] = right_array[right_index] right_index += 1 elif left_array[left_index] <= right_array[right_index]: merged_array[current_index] = left_array[left_index] left_index += 1 else: # Left over elements. if left_index < left_array_length: merged_array[current_index:] = left_array[left_index:] current_index += len(left_array[left_index:]) left_index = left_array_length elif right_index < right_array_length: merged_array[current_index:] = right_array[right_index:] current_index += len(right_array[right_index:]) right_index = right_array_length current_index += 1 return merged_array
def listprepender(lista, field='user'): """ Prepend a first element to all elements in lista lista = ['A', 'B', 'C'] field = ['X'] returns -> [['X','A'], ['X', 'B'], ['X,'C']] """ out = [] for s in lista: s.insert(0, field) out.append(s) return out
def model_as_json(bot_entries): """ Casts a list of lists into a list of modeled dictionaries. New data format is JSON-like and suitable for MongoDB @param bot_entries (list) list of sub-lists @returns json_list (list) list of modeled dictionaries """ json_list = [] for bot_entry in bot_entries: json_object = { "_id": bot_entry[2], "Category": "Botnets", "Entity-Type": "IP", "IP": bot_entry[0], "Botscout-id": bot_entry[2], "Bot-Name": bot_entry[4], "Email": bot_entry[5], "TimestampUTC": bot_entry[6], "mongoDate": bot_entry[7], "DatetimeUTC": bot_entry[8], "TimestampUTC-CTI": bot_entry[9], "mongoDate-CTI": bot_entry[10], "DatetimeUTC-CTI": bot_entry[11], "Country": bot_entry[1], } json_list.append(json_object) return json_list
def str_lower(value: str) -> str: """Converts a string to all lower case. Parameters ---------- value : str The string to turn to lower case. Returns ------- str The lower case string. """ return value.lower()
def _check_variable_names(names): """ checks variable names :param names: list of names for each feature in a dataset. :return: """ assert isinstance(names, list), '`names` must be a list' assert all([isinstance(n, str) for n in names]), '`names` must be a list of strings' assert len(names) >= 1, '`names` must contain at least 1 element' assert all([len(n) > 0 for n in names]), 'elements of `names` must have at least 1 character' assert len(names) == len(set(names)), 'elements of `names` must be distinct' return True
def secs_to_human(seconds): """Convert a number of seconds to a human readable string, eg "8 days" """ assert isinstance(seconds, int) or isinstance(seconds, float) return "%d days ago" % int(seconds / 86400)
def generate_product_id(smooth, constant=None, initial_product_id='0000'): """ Parameters ---------- smooth: int constant: None or not None initial_product_id: str Returns ------- str new 4 chars product id. - 1st char: 'Z' if smooth >= 1, or 'C' if constant is not Nonee - 2-4 chars : smooth size or 00 if constant, in decimal int """ if constant is not None: res_id = 'C%0.3d' % constant else: res_id = 'Z%0.3d' % smooth return res_id
def _get_compute_id(local_ips, id_to_node_ips): """ Compute the instance ID of the local machine. Expectation is that our local IPs intersect with one (only) of the remote nodes' sets of IPs. :param set local_ips: The local machine's IPs. :param id_to_node_ips: Mapping from instance IDs to sets of IPs, as reported by OpenStack. :return: Instance ID of local machine. """ matching_instances = [] for server_id, api_addresses in id_to_node_ips.items(): if api_addresses.intersection(local_ips): matching_instances.append(server_id) # If we've got this correct there should only be one matching instance. # But we don't currently test this directly. See FLOC-2281. if len(matching_instances) == 1 and matching_instances[0]: return matching_instances[0] raise KeyError("Couldn't find matching node.")
def hello(msg="World"): """Function that prints a message. :param msg: message to say :type msg: string :returns: string :raises: something .. note:: You can note something here. .. warning:: You can warn about something here. >>> hello() Hello World! >>> hello(msg="there") Hello there! """ return "Hello {}!".format(msg)
def get_gimbal_data(rotate_order): """ Get detail information about the gimbal data based on the current rotate order @param rotate_order: (str) The current rotate order @return: dict of gimbal data """ return {"bend": rotate_order[0], "roll": rotate_order[1], "twist": rotate_order[2]}
def check_strands(hsp_objs, fwd_strand): """Return True if hsps in the list are not all on the same strand. """ hsps_on_different_strands = False for hsp in hsp_objs: x = True if hsp.hit_frame < 0: x = False if x != fwd_strand: hsps_on_different_strands = True return hsps_on_different_strands
def range_sub(amin, amax, bmin, bmax): """A - B""" if amin == bmin and amax == bmax: return None if bmax < amin or bmin > amax: return 1 if amin < bmin: if amax > bmax: return [(amin, bmin), (bmax, amax)] else: return [(amin, bmin)] else: if amax < bmax: return None else: return [(bmax, amax)]
def get_value(it): """ Simplest function for explicit outing of range :param it: parsing result :return: """ return it[0] if len(it) > 0 else ''
def plaintext2toc(plaintext: str) -> list: """ :param plaintext: plaintext :return: table of content -> DOCUMENT.get_toc() """ toc = [] contents = plaintext.split('\n') for content in contents: if len(content) != 0: c = content.split('-->') t = [len(c[0]), c[1], int(c[2])] toc.append(t) return toc
def make_command_summary_string(command_summaries): """Construct subcommand summaries :param command_summaries: Commands and their summaries :type command_summaries: list of (str, str) :returns: The subcommand summaries :rtype: str """ doc = '' for command, summary in command_summaries: doc += '\n\t{:15}\t{}'.format(command, summary.strip()) return doc
def different_ways_memoization(n): """Memoization implementation of different ways, O(n) time, O(n) max stack frames, O(n) pre-allocated space""" d = [0] * (n + 1) d[0] = 1 def different_ways_memoization_helper(k): if k < 0: return 0 if d[k] == 0: d[k] = different_ways_memoization_helper(k - 1) + different_ways_memoization_helper( k - 3) + different_ways_memoization_helper(k - 4) return d[k] return different_ways_memoization_helper(n)
def parse_maddr_str(maddr_str): """ The following line parses a row like: {/ip6/::/tcp/37374,/ip4/151.252.13.181/tcp/37374} into ['/ip6/::/tcp/37374', '/ip4/151.252.13.181/tcp/37374'] """ return maddr_str.replace("{", "").replace("}", "").split(",")
def xround(value: float, rounding: float = 0.) -> float: """ Extended rounding function, argument `rounding` defines the rounding limit: ======= ====================================== 0 remove fraction 0.1 round next to x.1, x.2, ... x.0 0.25 round next to x.25, x.50, x.75 or x.00 0.5 round next to x.5 or x.0 1.0 round to a multiple of 1: remove fraction 2.0 round to a multiple of 2: xxx2, xxx4, xxx6 ... 5.0 round to a multiple of 5: xxx5 or xxx0 10.0 round to a multiple of 10: xx10, xx20, ... ======= ====================================== Args: value: float value to round rounding: rounding limit """ if rounding == 0: return round(value) factor = 1. / rounding return round(value * factor) / factor
def _lwp3_uuid(short: int) -> str: """Get a 128-bit UUID from a ``short`` UUID. Args: short: The 16-bit UUID. Returns: The 128-bit UUID as a string. """ return f"0000{short:04x}-1212-efde-1623-785feabcd123"
def to_float(i): """Convert to a float.""" if isinstance(i, list): return [to_float(j) for j in i] if isinstance(i, tuple): return tuple(to_float(j) for j in i) return float(i)
def reverseDict(myDict): """Makes a new dictionary, but swaps keys with values""" keys = myDict.keys() values = myDict.values() retDict = dict() for k in keys: retDict[myDict[k]] = k return retDict
def is_integer(num): """ Returns True if the num argument is an integer, and False if it is not. """ try: num = float(num) except ValueError: return False return num.is_integer()
def mean(ls): """ Takes a list and returns the mean. """ return float(sum(ls))/len(ls)
def le_power_of_2(num): """ Gets a power of two less than or equal to num. Works for up to 64-bit numbers. """ num |= (num >> 1) num |= (num >> 2) num |= (num >> 4) num |= (num >> 8) num |= (num >> 16) num |= (num >> 32) return num - (num >> 1)
def _tls_version_check(version, min): """Returns if version >= min, or False if version == None""" if version is None: return False return version >= min
def setWordsProdosy(words, phons): """set word prosody according to phons break""" prosodys = ['#', '*', '$', '%'] new_words = [] for i in range(len(words)): cur_prosody = '' if phons[i][-1] in prosodys: cur_prosody = phons[i][-1] new_words.append(words[i] + cur_prosody) return new_words
def macro_link(*args) -> str: """Creates a clickable hyperlink. Note: Since this is a pretty new feature for terminals, its support is limited. """ *uri_parts, label = args uri = ":".join(uri_parts) return f"\x1b]8;;{uri}\x1b\\{label}\x1b]8;;\x1b\\"
def remove_null_fields(data): """Remove all keys with 'None' values""" for k, v in data.items(): if isinstance(v, dict): remove_null_fields(v) if isinstance(v, list): for element in v: remove_null_fields(element) if not data[k]: del data[k] return data
def sort_stack(stack_object: list) -> list: """ Sorts stack. :param stack_object: stack object, iterable object :return: sorted stack, iterable object """ tmp_stack = [] while stack_object: # complexity check print(f'stack 1') element = stack_object.pop(-1) while tmp_stack and tmp_stack[-1] > element: stack_object.append(tmp_stack.pop()) tmp_stack.append(element) return tmp_stack
def _write_text(file, text): """ Write to file in utf-8 encoding.""" with open(file, mode='w', encoding='utf-8') as f: return f.write(text)
def formatNumber(number): """Ensures that number is at least length 4 by adding extra 0s to the front. """ temp = str(number) while len(temp) < 4: temp = '0' + temp return temp
def is_unique(s: str) -> bool: """ >>> is_unique('ABCDE') True """ """ >>> is_unique('programmer') False """ arr = [False for _ in range(128)] #creating hashtable with False input for character in s: #iterate throughout the string char_value = ord(character) if arr[char_value]: return False else: arr[char_value] = True return True
def parse_number(number): """Parse the number.""" try: return int(number) except (TypeError, ValueError) as e: return {"zero": 0, "one": 1, "first": 0}.get(number, number)
def fib_memoized(n): """Find the n-th fibonacci number, recursively, but using memoization.""" if n < 1: return 0 fibs = [0, 1] + (n - 2) * [-1] def fib_inner(n): if fibs[n] == -1: fibs[n] = fib_inner(n - 1) + fib_inner(n - 2) return fibs[n] # note the n - 1, because the indexing starts at zero. return fib_inner(n - 1)
def ratio(value): """Returns single-digit ratio""" try: value = float(value) except (ValueError, TypeError, UnicodeEncodeError): return '' return '{0:0.1f}'.format(value)
def csvlist(value: str, index: int) -> str: """Returns a single value from a comma separated list of values""" return str(value).split(',')[index]
def calculate_jaccard(loads): """Compute the jaccard across all loads Must pass in just a list of load_sets without additional metadata """ union_all = set() intersection_all = loads[0] for load in loads: union_all = union_all.union(load) intersection_all = intersection_all.intersection(load) return len(intersection_all)/float(len(union_all))
def percentile_from_dict(D, P): """ Find the percentile of a list of values @parameter N - A dictionary, {observation: frequency} @parameter P - An integer between 0 and 100 @return - The percentile of the values. """ assert 0 < P <= 100, "Percentile must be in range (0, 100)" N = sum(D.values()) P = float(P)/100 n = int(N) * P i = 1 # The formula returns a 1-indexed number observation = None for observation in sorted(D.keys()): if i >= n: return observation i += D[observation] return observation # raise AssertionError("Didn't find percentile")
def rename_fields_from_feature_collection(feature_collection): """This function renames feature collection keys to leave it according to STAC 9.0 and it is returned""" if 'meta' in feature_collection: # rename 'meta' key to 'context' feature_collection['context'] = feature_collection.pop('meta') if 'found' in feature_collection['context']: # rename 'found' key to 'matched' feature_collection['context']['matched'] = feature_collection['context'].pop('found') return feature_collection
def _preprocess_dn(original_dn): """ Reverse the DN and replace slashes with commas """ # remove leading slash dn = original_dn[1:] dn = dn.split('/') dn = dn[::-1] dn = ", ".join(dn) return dn
def V0_rel_diff(v0w, b0w, b1w, v0f, b0f, b1f, config_string, prefact, weight_b0, weight_b1): """ Returns the relative difference in the volumes. THE SIGNATURE OF THIS FUNCTION HAS BEEN CHOSEN TO MATCH THE ONE OF ALL THE OTHER FUNCTIONS RETURNING A QUANTITY THAT IS USEFUL FOR COMPARISON, THIS SIMPLIFIES THE CODE LATER. Even though several inputs are useless here. """ return prefact*2*(v0w-v0f)/(v0w+v0f)
def add_next (res_comb): """ Generates all the possible permutations by calling itself""" l = [] for item in res_comb [0]: if len (res_comb) > 1: new = add_next (res_comb [1:]) for item2 in new: l.append (item + item2) else: l.append (item) return l
def subclasstree(cls): """Return dictionary whose first key is the class and whose value is a dict mapping each of its subclasses to their subclass trees recursively. """ classtree = {cls: {}} for subclass in type.__subclasses__(cls): # long version allows type classtree[cls].update(subclasstree(subclass)) return classtree