content
stringlengths
42
6.51k
def fb_lookup(dic, keys, default): """Do dict-lookup for multiple key, returning the first hit. """ for key in keys: if key in dic: return dic[key] else: return default
def intable(s): """Check if a string can be converted to an int""" try: int(s) return True except ValueError: return False
def isFloat(value): """Returns True if convertible to float""" try: float(value) return True except (ValueError, TypeError): return False
def bytes_to_num(data): """ *data* must be at least 4 bytes long, big-endian order. """ assert len(data) >= 4 num = data[3] num += ((data[2] << 8) & 0xff00) num += ((data[1] << 16) & 0xff0000) num += ((data[0] << 24) & 0xff000000) return num
def maybe_append_new_line(code): """ Append new line if code snippet is a Python code snippet """ lines = code.split("\n") if lines[0] in ["py", "python"]: # add new line before last line being ``` last_line = lines[-1] lines.pop() lines.append("\n" + last_line) ...
def update_corpus_statistics(cs, ds): """ Updates corpus-level statistics (cs) using document-level statistics (ds). """ cs['tna'] += ds['rna'] cs['tnc'] += ds['rnc'] cs['tnb'] += ds['rnb'] if ds['mnc'] > cs['mnc']: cs['la'] = ds['la'] cs['mnc'] = max(cs['mnc'], ds['mnc'])...
def format_mobileconfig_fix(mobileconfig): """Takes a list of domains and setting from a mobileconfig, and reformats it for the output of the fix section of the guide. """ rulefix = "" for domain, settings in mobileconfig.items(): if domain == "com.apple.ManagedClient.preferences": r...
def split_privacy_between_eigenvalues_and_vectors_uniformly(n, d, epsilon): """Split privacy budget between eigenvalues and eigenvectors equally.""" print("Ignoring parameters in budget splitting n:%d d:%d" % (n, d)) return (epsilon / 2.0, epsilon / 2.0)
def _find(node, data): """Return the node containing data, or else None.""" if not node or node.data == data: return node else: return (_find(node.left, data) if (data < node.data) else _find(node.right, data))
def dict_deep_update(target, update): """Recursively update a dict. Subdict's won't be overwritten but also updated. Args: target: Target dictionary to update. update: Parameters to update. Returns: dict: Updated dictionary. """ for key, value in update.items(): if k...
def goto_definition( obj, command_template='open -na "PyCharm.app" --args --line {lineno} "{filepath}"' ): """Opens the definition of the object in the file it was defined at the line it was defined. The default is set to use pycharm to open the file on a mac. To customize for your system/file_vie...
def can_check_isinstance(specified_type): """Checks that specified_type can be the second arg to isinstance without raising an exception.""" try: isinstance(5, specified_type) except TypeError: return False return True
def area(pts,absolute=False): """ Computes the clockwise area of the polygon defined by the points. Args: pts: list of (x,y) tuples. Assumes last and first vertex are different. Cannot handle if input points contain None coordinates. absolute: if true, returns the absolute value...
def visiblename(name): """ Checks whether a given name should be documented/displayed by ignoring builtin ones. """ return not (name.startswith('__') and name.endswith('__'))
def random(maximum: int=0, score: str='silvathor_RANDOM'): """ Return a random integer in range [0, maximum[. :param maximum: The maximum value of the random number (excluded). :param score: The name of the Minecraft score for the random number. :return: A random number. """ score.lower().r...
def ask_user(a, b): # preliminary """get answer from user: a*b = ?""" print('{:d}*{:d} = '.format(a, b)) return a*b
def interval(fermentername, seconds): """ gives back intervall as tuppel @return: (weeks, days, hours, minutes, seconds) formats string for line 2 returns the formatted string for line 2 of fermenter multiview """ WEEK = 60 * 60 * 24 * 7 DAY = 60 * 60 * 24 HOUR = 60 * 60 MINUTE =...
def nvl(value, defval="Unknown"): """ Provide a default value for empty/NULL/None. Parameters ---------- value: obj The value to verify. defval: obj The value to return if the provide value is None or empty. Returns ------- defval if value is None or empty, othe...
def url_from_user_input(url): """Return a normalized URL from user input. Take a URL from user input (eg. a URL input field or path parameter) and convert it to a normalized form. """ url = url.strip() if not url: return url if not (url.startswith("http://") or url.startswith("http...
def decodeString(s): """ "((A2B)2)2G2" -> 'AABAABAABAABGG' """ stack = [] digit = 0 for c in s: if c.isdigit(): digit = 10*digit + int(c) continue if digit != 0: stack[-1] = stack[-1]*digit digit = 0 if c == ')': ...
def volume_pyramid(area_dasar: float, tinggi: float) -> float: """ kalkulasi dari volume pyramid referensi https://en.wikipedia.org/wiki/Pyramid_(geometry) >>> volume_pyramid(10, 3) 10.0 >>> volume_pyramid(1.5, 3) 1.5 """ return area_dasar * tinggi / 3.0
def _rev_bits(bits, l=32): """ Reverse bits """ rev = 0 for i in range(l): if bits & (1 << i) != 0: rev |= 1 << (l-i - 1) return rev
def GetFlagFromDest(dest): """Returns a conventional flag name given a dest name.""" return '--' + dest.replace('_', '-')
def validate_entangler_map(entangler_map, num_qubits, allow_double_entanglement=False): """Validates a user supplied entangler map and converts entries to ints Args: entangler_map (dict) : An entangler map, keys are source qubit index (int), value is array of target qubit...
def asShortCode(epsg): """ convert EPSG code to short CRS ``EPSG:<code>`` notation """ return "EPSG:%d" % int(epsg)
def batch_size_per_device(batch_size: int, num_devices: int): """Return the batch size per device.""" per_device_batch_size, ragged = divmod(batch_size, num_devices) if ragged: msg = 'batch size must be divisible by num devices, got {} and {}.' raise ValueError(msg.format(per_device_batch_size, num_devic...
def _check_dict_format(_dict): """[Checks if the _dict are in the expected format for conversion] Returns: [bool]: [is ok] """ for key in _dict.keys(): if not set(_dict[key].keys()) == {"type", "dict"}: print("Dict should only have type and dict as dict elements.") ...
def _merge(iterable1, iterable2): """ Merge two slices into a single ordered one. Complexity: O(n), Where n = len(iterable1) + len(iterable2) :param iterable1: :param iterable2: :return: """ if not iterable1: return iterable2 if not iterable2: return iterable1 ...
def writeb(path, data): """Write data to a binary file. Args: path (str): Full path to file data (str): File bytes Returns: int: Number of bytes written """ with open(path, 'wb') as handle: return handle.write(data)
def identify(_line): """backend detection (simplified)""" _ident = "unknown" if "Joomla" in _line: _ident = "Joomla CMS" if "wp-content" in _line: _ident = "WordPress CMS" if 'content="Drupal"' in _line: _ident = "Drupal CMS" return _ident
def fib(n): """ Functional definition of Fibonacci numbers """ if n == 0 or n == 1: return n else: return fib(n - 1) + fib(n - 2)
def reflexive_closure_function(rel, universe): """ Function to return the reflexive closure of a relation on a set :param rel: A list that is a relation on set universe :param universe: A list that represents a set :return: A list that is the relexive closure of the relation rel on the set universe...
def product(pmt1, pmt2): """ the product of two permutations """ nelem = len(pmt1) assert sorted(pmt1) == sorted(pmt2) == list(range(nelem)) prod = tuple(pmt2[i] for i in pmt1) return prod
def allCharacters(word): """[Function look over the word looking for all character contained in it ] Args: word ([String]): [Word from which we want to exclude the characters ] Returns: [String]: [All characters contained in the word, in form of String] """ charactersInWord = [] ...
def ParseGitInfoOutput(output): """Given a git log, determine the latest corresponding svn revision.""" for line in output.split('\n'): tokens = line.split() if len(tokens) > 0 and tokens[0] == 'git-svn-id:': return tokens[1].split('@')[1] return None
def nExpPrioritize(nexp, base=20, award=2e6, penalty=-100): """adjust field priorities based on planned exps 1 exp: negative, 8 exp: super high """ assert nexp < 9 and nexp > 0, "invalid nexp" if nexp == 1: return penalty elif nexp == 8: return award elif nexp == 2: ...
def merge_dictionaries(row_data, default): """Merge d2 into d1, where d1 has priority for all values of d2 merge them into d1. If a value exists in d1 and in d2 keep the value from d1 :param d1: dictionary of values :param d2: dictionary of values :return: dictionary of unified values """ ...
def flatten_dict(deep_dict): """Turn `deep_dict` into a one-level dict keyed on `.`-joined path strings""" new_dict = {} for key, value in deep_dict.items(): if isinstance(value, dict): _dict = { ".".join([key, _key]): _value for _key, _value in flatte...
def bubble_sort(arr_raw): """ args: arr_raw: list to be sorted return: arr_sort: list sorted """ for i in range(1, len(arr_raw)): for ii in range(0, len(arr_raw) - i): if arr_raw[ii] > arr_raw[ii + 1]: arr_raw[ii], arr_raw[ii + 1] = arr_raw[ii + 1]...
def px_U(box_hwidth): """ Args: box_hwidth (float): Half-width of the analysis box, in arcsec Returns: float: p(x|U) """ box_sqarcsec = (2*box_hwidth)**2 #box_steradians = box_sqarcsec * sqarcsec_steradians # return 1./box_sqarcsec
def ceildiv(a, b): """ To get the ceiling of a division :param a: :param b: :return: """ return -(-a // b)
def integer(i): """ Parses an integer string into an int :param i: integer string :return: int """ try: return int(i) except (TypeError, ValueError): return i
def _var(i=0): """ Return a distinct variable name for each given value of i """ alphabet = "XYZABCDEFGHIJKLMNOPQRSTUVW" return alphabet[i] if i < len(alphabet) else "X{}".format(i)
def is_string_ignored(string, ignored_substrings=""): """Check if string contains substrings""" lstr = str.lower(string) return not all(str.lower(x) not in lstr for x in ignored_substrings.split(",") if len(x) > 0)
def gravityLossUpToAltitude(altitude): """gives the gravity loss up to a given altitude""" if 0 <= altitude and altitude <= 20000: return 1500 - 0.075*altitude # m/s else: raise Exception("Invalid at given altitude: {0}".format(altitude))
def SieveOfEratosthenes(*args): """ Returns prime numbers within a range (including lower and upper bounds) or prime numbers less than or equal to given input Parameters ---------- *args : tuple Expects one or two arguments as described below Other Parameters ---------------- 1...
def isfloat(value): """ Return True if all characters are part of a floating point value """ try: x = float(value) return True except ValueError: return False
def grades2map(gstring): """Convert a grade string from the database to a mapping: {sid -> grade} """ try: grades = {} for item in gstring.split(';'): k, v = item.split('=') grades[k.strip()] = v.strip() return grades except: if gstring: ...
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids): """ Ensures that the alternative id's in `nest_spec` are all in the universal choice set for this dataset. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. ...
def count_instance_of_str(string1, string2): """Counts characters in string1 that are also in string2.""" count = 0 #for each char in string1, check if it's in string2 for char in string1: if char in string2: count += 1 return count
def fahrenheit_to_celsius(f): """Convert a Celsius temperature to Fahrenheit.""" return (f - 32.0) * 5.0 / 9.0
def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims): """Helper for calculating broadcast shapes with core dimensions.""" return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims) for core_dims in list_of_core_dims]
def RemoveQuots(string): """ Remove quotes at both ends of a string :param str string: string :return: string(str) - string """ if string[:1] == '"' or string[:1] == "'": string=string[1:] if string[-1] == '"' or string[-1] == "'": string=string[:-1] return string
def group_objects_by_model(objects): """ Group objects by their models Args: objects (:obj:`list` of :obj:`Model`): list of model objects Returns: :obj:`dict`: dictionary with object grouped by their class """ grouped_objects = {} for obj in objects: if obj.__class__ no...
def u_to_all_ratio(data): """ :param data: wikipedia content to be pre-processed :return: upper to lower case ratio vandals use either too many upper case or lower case words tobe applied before upper to lower transformation """ chars = list(data) upper_count = sum([char.isupper() for ch...
def _matches_package_name(name, pkg_info): """ :param name: the name of the package :type name: str :param pkg_info: the package description :type pkg_info: dict :returns: True if the name is not defined or the package matches that name; False otherwise :rtype: bool """ ...
def get_lvl_index(levels, lvl): """index of a given level in levels""" for k, v in levels.items(): if v['level'] == lvl: return k, v
def valid_arguments(valip, valch, valii, valid): """ Valid the arguments """ bvalid = True # Type converssion valch = int(valch) valii = int(valii) # Valid the parameters # Valid - IP if valip == "": print("IP is invalid.") bvalid = False # Valid - Channel...
def remove_embed(text): """Removes the weird string from the end of genius results""" lyric = text.split('EmbedShare URLCopyEmbedCopy')[0] while lyric[-1].isnumeric(): lyric = lyric[:-1] return lyric
def concat(lists): """ Given a series of lists, combine all items in all lists into one flattened list """ result = [] for lst in lists: for item in lst: result += [item] return result
def get_backlinks(dictionary): """ Returns a reversed self-mapped dictionary @param dictionary: the forwardlinks """ o = dict() for key, values in dictionary.items(): try: for v in values: try: o[v].add(key) except KeyE...
def getcookies(cookiejar, host, path): """Get a dictionary of the cookies from 'cookiejar' that apply to the given request host and request path.""" cookies = {} for cdomain in cookiejar: if ('.' + host).endswith(cdomain): for cpath in cookiejar[cdomain]: if path.star...
def guess_rgb(shape): """If last dim is 3 or 4 assume image is rgb. """ ndim = len(shape) last_dim = shape[-1] if ndim > 2 and last_dim < 5: return True else: return False
def user_event_search(msg): """ search product """ iscmd = msg['MsgType'] == 'text' and msg['Content'].startswith("search:") return iscmd
def DivideIfPossibleOrZero(numerator, denominator): """Returns the quotient, or zero if the denominator is zero.""" if not denominator: return 0.0 else: return numerator / denominator
def decode(string): """Decode a Base X encoded string into the number Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for decoding """ BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" base = len(BASE62) strlen = len(string) ...
def error_porcentual(aceptado: float, experimental: float) -> str: """ Calcular error porcentual de un resultado experimental obtenido con respecto al aceptado """ porcentaje = abs(((aceptado - experimental) / aceptado) * 100) return "{:.8f}%".format(porcentaje)
def sci_notation(value, sig_figs=8): """ Print value in scientific notation with number of signficant digits specified by `sig_figs`. This filter is required as there are known issues when supplying some quantities (e.g. loop length) at arbitrarily high precision """ format_str = f'1.{sig_fi...
def getLanguage(langID, sublangID): """ Get Language Standard. Args: langID (str): Landguage ID sublangID (str): Sublanguage ID Returns: str: Language encoding. """ langdict = { 9: { 0: "en", 1: "en", 3: "en-au", 4...
def base36encode(number): """Converts an integer into a base36 string.""" ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz" base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <= number < len(ALPHABET): return sign + ALPHABET[number] while numbe...
def CleanTitle(title): """remove [graphic] from titles""" title = title.replace(' [graphic].', '') title = title.replace('[', '').replace(']','') return title
def flatten(lis): """indices = list(range(0, len(lis)))""" sortLis = list(sorted(lis)) m = {} for index, value in enumerate(sortLis): m[value] = index returnList = [] for value in lis: returnList.append(m[value]) """zippedSorted = list(zip(sortLis, indices)) newList ...
def avg(S,C): """This Function returns the average of the numbers given""" avg = 0 avg = S/C # Returns the rounded to 2 decimal places... return round(avg,2)
def _set_small_values_to_zero(tol, *values): """helper function to set infinitesimally small values to zero Parameters ---------- tol : float threshold. All numerical values below abs(tol) is set to zero *values : unflattened sequence of values Returns ------- ...
def calc_num_overlap_samples(samples_per_frame, percent_overlap): """Calculate the number of samples that constitute the overlap of frames Parameters ---------- samples_per_frame : int the number of samples in each window / frame percent_overlap : int, float either an integer ...
def html(title, body): """Wrap the body HTML in a mobile-friendly HTML5 page with given title and CSS file 'style.css' from the static content directory.""" return """<!DOCTYPE html> <HTML> <HEAD> <TITLE>{}</TITLE> <META name="viewport" content="width=device-width, initial-scale=1.0"> <LINK rel="stylesheet"...
def adjust_boundingbox(face, width, height, size): """ :param face: dlib face class :param width: frame width :param height: frame height :param size: set bounding box size :return: x, y, bounding_box_size in opencv form """ x1 = face[0] y1 = face[1] x2 = face[2] y2 = face[3]...
def multipart_geoms_query(schema, table): """Returns sql query to check multipart geometries of a table. Args: schema: Name of the schema. table: Name of the table. Returns: String sql query. """ return ( 'SELECT id, ST_NumGeometries(geom) ' 'FROM {}.{} ' 'WHERE ST_NumGeometries(geom...
def clean_tag(tag): """ Function to clean up human tagging mistakes. Non generalizable function. Need to edit in future to make more generalizeable """ tag = tag.upper().strip() if not tag.isalnum(): tag = '<Unknown>' elif 'MO' in tag or 'OL' in tag: tag = 'MOL' elif '...
def parse_requirements(r): """Determine which characters are required and the number of them that are required.""" req = {'d': 0, 'l': 0, 'u': 0, 's': 0} for c in r: if c == 'd': req['d'] += 1 elif c == 'l': req['l'] += 1 elif c == 'u': re...
def safe_div(numerator: int, denominator: int) -> float: """Divide without Zero Division Error. Args: numerator (integer): the number above the line in a vulgar fraction. denominator (integer): the number below the line in a vulgar fraction. Returns: float: Return value Usage: ...
def _trapz_2pt_error2(dy1, dy2, dx): """Squared error on the trapezoidal rule for two points. For errors dy1 and dy2 and spacing dx.""" return (0.5*dx)**2 * (dy1**2 + dy2**2)
def normalize(scope): """ Normalizes and returns tuple consisting of namespace, and action(s) """ parts = scope.split(":") return (parts[0], parts[1:])
def waterModis(ndvi, band7): """ # water.modis: Terra-MODIS water mapping tool # Xiao X., Boles S., Liu J., Zhuang D., Frokling S., Li C., Salas W., Moore III B. (2005). # Mapping paddy rice agriculture in southern China using multi-temporal MODIS images. # Remote Sensing of Environment 95:480-492. ...
def relate_objs(obj1_coords, obj2_coords, relation): """ Relates obj2 in relation to obj1, e.g. whether obj2 is behind obj1 or whether obj2 is right of obj1. :param obj1_coords: :param obj2_coords: :param relation: :return: """ relation_holds = False if relation == "behind" and obj1_...
def str_to_bool(string, truelist=None): """Returns a boolean according to a string. True if the string belongs to 'truelist', false otherwise. By default, truelist has "True" only. """ if truelist is None: truelist = ["True"] return string in truelist
def train(params, step, iters=1): """Executes several model parameter steps.""" for i in range(iters): params = step(params) return params
def flatten_list(_list): """Flatten a nested list""" return [x for el in _list for x in el]
def relpath(path): """Convert the given path to a relative path. This is the inverse of abspath(), stripping a leading '/' from the path if it is present. :param path: Path to adjust >>> relpath('/a/b') 'a/b' """ return path.lstrip('/')
def common_prefix(a, b): """:return: the longest common prefix between a and b.""" for i in range(min(len(a), len(b))): if a[i] != b[i]: return a[:i] return ''
def get_meta_data(file_name): """Helper function to retrieve a given file name's year, month, and zone. Takes a string file_name formatted as ``'AIS_yyyy_mm_Zone##.csv'`` and returns the numerical values of ``yyyy, mm, ##`` corresponding to year, month, and zone number as a tuple. Args: file_n...
def _merge_line_string(rel, startindex): """ takes a relation that might possibly be a bunch of ways that HAPPEN to be a single line, and transforms the MultiLineString object into a single LineString object """ #WARNING: THIS CURRENTLY "WORKS" BUT VIOLATES WINDINR ORDER FOR POLYGONS coordinate_...
def right_node(nodes, x, y): """ find the first right node and returns its position """ try: return str(nodes.index('0', x+1)) + " " + str(y) + " " except(KeyError, ValueError): return '-1 -1 '
def factorial(num): """ The factorial of a number. On average barely quicker than product(range(1, num)) """ # Factorial of 0 equals 1 if num == 0: return 1 # if not, it is the product from 1...num product = 1 for integer in range(1, num + 1): product *= integer ...
def debug(stmt, data): # pragma: no cover """Helpful debug function """ print(stmt) print(data) return data
def power(x,y): """returns x^y""" if(y==0): return 1 return x *power(x, y - 1)
def remove_whitespace_lines(text: str) -> str: """ Remove lines that only contains whitespace from a string. """ return "\n".join([line for line in text.splitlines() if line.strip()])
def adjacency_matrix(parent1, parent2): """Return the union of parent chromosomes adjacency matrices.""" neighbors = {} end = len(parent1) - 1 for parent in [parent1, parent2]: for k, v in enumerate(parent): if v not in neighbors: neighbors[v] = set() if...
def extract_group_ids(caps_directory): """Extract list of group IDs (e.g. ['group-AD', 'group-HC']) based on `caps_directory`/groups folder.""" import os try: group_ids = os.listdir(os.path.join(caps_directory, "groups")) except FileNotFoundError: group_ids = [""] return group_ids
def generate_deployment_ids(deployment_id, resources): """ Create a new deployment ID for a child deployment. :param deployment_id: An existing deployment ID. :type deployment_id: str :return: A new child deployment ID. :rtype: str """ return '{}-{}'.format(deployment_id, resources)