content
stringlengths
42
6.51k
def portfolio_stats(w: list, rt: list, std: list, coef: float, ra: float, rf: float) -> list: """ Store key portfolio statistics into a list. =========================================================== Parameters: - w: 1-D array contains weight of each asset - rt: 1-D array of each asset's expected return - std: 1-D array of each asset's volatility/risk - coef: Correlation coefficient between assets - ra: Risk aversion coefficient varies from different users - rf: Risk free rate at current time Returns: - w: float Asset weights - rp: float Portfolio's expected return - vp: float Portfolio's standard deviation - up: float Portfolio's utility - sp: float Portfolio's sharpe ratio """ rp = sum([w * rt for w, rt in zip(w, rt)]) # sum product of w and rt vp = ( (w[0] * std[0]) ** 2 + (w[1] * std[1]) ** 2 + 2 * w[0] * w[1] * std[0] * std[1] * coef ) ** 0.5 up = rp - 0.5 * ra * vp ** 2 sp = ((rp - rf) / vp) if round(vp, 5) != 0 else 0 # avoid zero division return [w[0], w[1], rp, vp, up, sp]
def sequence_to_accelerator(sequence): """Translates Tk event sequence to customary shortcut string for showing in the menu""" if not sequence: return "" if not sequence.startswith("<"): return sequence accelerator = (sequence .strip("<>") .replace("Key-", "") .replace("KeyPress-", "") .replace("Control", "Ctrl") ) # Tweaking individual parts parts = accelerator.split("-") # tkinter shows shift with capital letter, but in shortcuts it's customary to include it explicitly if len(parts[-1]) == 1 and parts[-1].isupper() and not "Shift" in parts: parts.insert(-1, "Shift") # even when shift is not required, it's customary to show shortcut with capital letter if len(parts[-1]) == 1: parts[-1] = parts[-1].upper() accelerator = "+".join(parts) # Post processing accelerator = (accelerator .replace("Minus", "-").replace("minus", "-") .replace("Plus", "+").replace("plus", "+")) return accelerator
def palindrome(d: int)-> str: """ Function is getting the digits of the number, left shifting it by multiplying it with 10 at each iteration and adding it the previous result. Input: Integer Output: String (Sentence telling if the number is palindrome or not) """ remainder = 0 revnum = 0 n = len(str(d)) copynum2 = d while copynum2 != 0: remainder = copynum2%10 revnum = revnum * 10 + remainder copynum2 //= 10 if d == revnum: return "Given Numer {} is palindrome".format(d) else: return "Given Numer {} is not palindrome".format(d)
def reverseGroups(head, k): """ :param head: head of the list :param k: group size to be reversed :return: None1 """ if k < 1: return prev = None cur = head next = None index = 0 while index < k and cur != None: next = cur.next cur.next = prev prev = cur cur = next index += 1 if cur != None: head.next = reverseGroups(cur, k) return prev
def normalizeHomogenious(points): """ Normalize a collection of points in homogeneous coordinates so that last row = 1. """ for row in points: row /= points[-1] return points
def convert_iiif_width(uri, width="full"): """ Utility to convert IIIF to image URI with given width or "full" """ uri_end = uri.split("//")[1].split("/") uri_end[4] = ("full" if width == "full" else str(width) + ",") return "https://" + "/".join(uri_end)
def is_pangram(string: str) -> bool: """ Checks if the given string is a pangram or not :param string: String to check :return: bool Example: >>> is_pangram("The quick, brown fox jumps over the lazy dog!") >>> True """ count = 0 for character in range(97, 123): if chr(character) in string or chr(character).upper() in string: count += 1 if count == 26: return True return False
def format_seconds(seconds: int) -> str: """ Convert seconds to a formatted string Convert seconds: 3661 To formatted: " 1:01:01" """ # print(seconds, type(seconds)) hours = seconds // 3600 minutes = seconds % 3600 // 60 seconds = seconds % 60 return f"{hours:4d}:{minutes:02d}:{seconds:02d}"
def select(S, i, key=lambda x: x): """ Select the element, x of S with rank i (i elements in S < x) in linear time Assumes that the elements in S are unique Complexity: O(n) Every step in this algorithm is approximately linear time, the sorting here only ever happens of lists of length <= 5 """ # Divide the list into columns of 5 sublists = [S[k:k+5] for k in range(0, len(S), 5)] # Find the medians of each column medians = [ sorted(sublist, key=key)[len(sublist) // 2] for sublist in sublists ] if len(medians) <= 5: # If the number of columns is less than 5 elements # return the median of medians x = medians[len(medians) // 2] else: # Otherwise recursively find the median of medians x = select(medians, len(medians) // 2) L = [y for y in S if y < x] R = [y for y in S if y > x] k = len(L) if k > i: return select(L, i) if k < i: return select(R, i - k) return x
def compact(lst): """Return a copy of lst with non-true elements removed. >>> compact([0, 1, 2, '', [], False, (), None, 'All done']) [1, 2, 'All done'] """ return [val for val in lst if val]
def flatten_item(item): """ Returns a flattened version of the item """ output = {} for key in item.keys(): if key not in ["status", "properties"]: output[key] = item[key] for status in item["status"]: output[status["status_name"]] = status["status_value"] for key, obj in item["properties"].items(): if key == "features": for feature_key, feature_obj in obj.items(): output[feature_key] = feature_obj else: output[key] = obj return output
def IoU(boxA: dict, boxB: dict) -> float: """ Calculate IoU Args: boxA: Bounding box A boxB: Bounding box B """ # determine the (x, y)-coordinates of the intersection rectangle xA = max(boxA['x1'], boxB['x1']) yA = max(boxA['y1'], boxB['y1']) xB = min(boxA['x2'], boxB['x2']) yB = min(boxA['y2'], boxB['y2']) surf_boxA = (boxA['x2'] - boxA['x1']) * (boxA['y2'] - boxA['y1']) surf_boxB = (boxB['x2'] - boxB['x1']) * (boxB['y2'] - boxB['y1']) # compute the area of intersection rectangle interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1) # compute the intersection over union by taking the intersection # area and dividing it by the sum of prediction + ground-truth # areas - the interesection area iou = interArea / float(surf_boxA + surf_boxB - interArea) # return the intersection over union value return iou
def match_snp(allele): """ return the complimentary nucleotide for an input string of a single nucleotide. missing bp (N) will return a N. """ allele = allele.upper() if allele == 'A': return 'T' elif allele == 'T': return 'A' elif allele == 'C': return 'G' elif allele == 'G': return 'C' elif allele == 'N': return 'N' else: raise ValueError( 'Need valid nucleotide (ATGC) or N\n %s was passed in ' % (allele))
def dms2dd(s): """convert lat and long to decimal degrees""" direction = s[-1] degrees = s[0:4] dd = float(degrees) if direction in ('S','W'): dd*= -1 return dd
def parse_filename(filename): """Parse python and platform according to PEP 427 for wheels.""" stripped_filename = filename.strip(".whl") try: proj, vers, build, pyvers, abi, platform = stripped_filename.split("-") except ValueError: # probably no build version available proj, vers, pyvers, abi, platform = stripped_filename.split("-") return (pyvers, platform)
def is_operator(token): """ return true if operator """ return token == "&" or token == "|"
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if len(options) > 1: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] } else: return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle }] }
def get_id_map_by_name(source_list, target_list): """ Args: source_list (list): List of links to compare. target_list (list): List of links for which we want a diff. Returns: dict: A dict where keys are the source model names and the values are the IDs of the target models with same name. It's useful to match a model from the source list to its relative in the target list based on its name. """ link_map = {} name_map = {} for model in target_list: name_map[model["name"].lower()] = model["id"] for model in source_list: if model["name"].lower() in name_map: link_map[model["id"]] = name_map[model["name"].lower()] return link_map
def normalize(lng): """normalizze language string pl => pl_PL en-us => en_US en_GB => en_GB """ lng = lng.replace("-", "_") if "_" in lng: pre, post = lng.split("_") lng = pre.lower() + "_" + post.upper() else: lng = lng.lower() + "_" + lng.upper() return lng
def FloorLog10Pow2(e): """Returns floor(log_10(2^e))""" assert e >= -1650 assert e <= 1650 return (int(e) * 78913) // 2**18
def load_distances(dx, dy, dz, ix, delx): """ Returns the load distances to where an element load is applied. Parameters ---------- dx, dy, dz : float The element distance vector. ix, : float The distance from the i node of the element to where the beginning of the loads are applied. dx : float The distance from the ix position toward the j node over which the loads are applied. """ l = (dx**2 + dy**2 + dz**2)**0.5 l1 = l * abs(ix) if ix < 0 else ix l2 = l * abs(delx) if delx < 0 else delx l2 = l - l1 - l2 if l1 > l or l1 < 0 or l2 > l or l2 < 0: raise ValueError('Load applied beyond element bounds.') return l, l1, l2
def file_type_by_extension( extension): """ Tries to guess the file type by looking up the filename extension from a table of known file types. Will return the type as string ("audio", "video" or "torrent") or None if the file type cannot be determined. """ types={ 'audio': [ 'mp3', 'ogg', 'wav', 'wma', 'aac', 'm4a' ], 'video': [ 'mp4', 'avi', 'mpg', 'mpeg', 'm4v', 'mov', 'divx', 'flv', 'wmv', '3gp' ], 'torrent': [ 'torrent' ], } if extension == '': return None if extension[0] == '.': extension=extension[1:] extension=extension.lower() for type in types: if extension in types[type]: return type return None
def partition_gps(entities): """Partition Photo entities by GPS lat/lon and datetime. Arguments: entities: sequence of Photo entities Returns complete_images: sequence of Photos containing both GPS lat/lon and datetime incomplete_images: sequence of Photos that do not contain both GPS lat/lon and datetime """ complete_images = [] incomplete_images = [] for entity in entities: has_lat = entity.has_key('lat') has_lon = entity.has_key('lon') has_datetime = entity.has_key('image_datetime') if has_lat and has_lon and has_datetime: complete_images.append(entity) else: incomplete_images.append(entity) return complete_images, incomplete_images
def print_line(l): """ print line if starts with ... """ print_lines = ['# STOCKHOLM', '#=GF', '#=GS', ' '] if len(l.split()) == 0: return True for start in print_lines: if l.startswith(start): return True return False
def getPhenotype(chromosome, items): """ Given a chromosome, returns a list of items in the bag :param chromosome: :param items: :return: list """ return [v for i, v in enumerate(items) if chromosome[i] == 1]
def add_homeruns(user, player_id, hrs): """Add a hr by a player Parameters: user: the dictionary of the user (dict) player_id: the player id (int) hrs: the number of hr hit (int) Returns: user: the update user (dict) """ for __ in range(0, hrs): user['game']['hr'].append(player_id) return user
def _format_mojang_uuid(uuid): """ Formats a non-hyphenated UUID into a whitelist-compatible UUID :param str uuid: uuid to format :return str: formatted uuid Example: >>> _format_mojang_uuid('1449a8a244d940ebacf551b88ae95dee') '1449a8a2-44d9-40eb-acf5-51b88ae95dee' Must have 32 characters: >>> _format_mojang_uuid('1') Traceback (most recent call last): ... ValueError: Expected UUID to have 32 characters """ if len(uuid) != 32: raise ValueError('Expected UUID to have 32 characters') return uuid[:8] + '-' + uuid[8:12] + '-' + uuid[12:16] + '-' + uuid[16:20] + '-' + uuid[20:]
def disp_corner(sc, L, ct=4): """ Nearest displacement along blocks of 4 """ return min(abs((x-L*ct) - sc) for x in range(ct))
def get_searched_index(graph): """ Returns a dictionary with a key for each node in the graph with a boolean initialized to False, to indicate whether they have not yet been searched. """ searched = {} for k in graph.keys(): searched[k] = False return searched
def is_number(s): """ Indicates if s is a number (True) or not (False) """ try: float(s) return True except ValueError: return False
def get_new_id(identifier, width): """ Given an identifier, gets the next identifier. :param identifier: the last identifier known. :param width: the width of the identifier. :return: the next identifier. """ if identifier.lstrip('0') == "": identifier = str(1) else: identifier = str(int(identifier.lstrip('0')) + 1) identifier = (width - len(identifier.lstrip('0'))) * "0" + identifier return identifier
def _quote_float(s): """Returns s quoted if s can be coverted to a float.""" try: float(s) except ValueError: return s else: return "'%s'" % s
def check_img_link(link): """Verify image link. Argument: Link as string. Link must end with "jpg", "jpeg", "png" or "gif". Return: Link or None. """ allowed_img = ('jpg', 'jpeg', 'png', 'gif') if '.' in link: splitlink = link.split('.') if splitlink[-1].lower() in allowed_img: return link return None
def lerp(a, b, i): """Linear enterpolate from a to b.""" return a+(b-a)*i
def _get_doi_from_text_body(body): """ Get the DOI from the body of a request. Args: body (str): The data Return: a str containing the DOI """ bits = body.split('url=', 1) if bits[0] != '': _doi = (bits[0].split('doi=')[1]).strip() else: bits = bits[1].split('doi=') _doi = bits[1].strip() return _doi
def my_kitchen_sink_fc(p1, p2, p3=3.0, p4="default"): """This should (in a few words) define what the function is for. @param: p1 - define what p1 is, and what type/range/values is expected @param: p2 - same again @param: p3 - and again @param: p4 - and again - but this one will default to the string "default" if you don't pass anything @returns: What does this function return? Both type and what it is conceptually""" # Notice the :0.2f - this says format this as a number with 2 decimal places return "name {0} value {1:0.2f}".format(p4, p3 * (p1 + p2))
def __int_desc(tries): """Return the inversion of the triad in a string.""" if tries == 1: return "" elif tries == 2: return ", first inversion" elif tries == 3: return ", second inversion" elif tries == 4: return ", third inversion"
def _mk_cache_instance(cache=None, assert_attrs=()): """Make a cache store (if it's not already) from a type or a callable, or just return dict. Also assert the presence of given attributes >>> _mk_cache_instance(dict(a=1, b=2)) {'a': 1, 'b': 2} >>> _mk_cache_instance(None) {} >>> _mk_cache_instance(dict) {} >>> _mk_cache_instance(list, ('__getitem__', '__setitem__')) [] >>> _mk_cache_instance(tuple, ('__getitem__', '__setitem__')) Traceback (most recent call last): ... AssertionError: cache should have the __setitem__ method, but does not: () """ if isinstance(assert_attrs, str): assert_attrs = (assert_attrs,) if cache is None: cache = {} # use a dict (memory caching) by default elif isinstance(cache, type) or ( # if caching_store is a type... not hasattr(cache, '__getitem__') # ... or is a callable without a __getitem__ and callable(cache) ): cache = ( cache() ) # ... assume it's a no-argument callable that makes the instance for method in assert_attrs or (): assert hasattr( cache, method ), f'cache should have the {method} method, but does not: {cache}' return cache
def MAPE(y_true, y_pred): """Mean Absolute Percentage Error Calculate the mape. # Arguments y_true: List/ndarray, ture data. y_pred: List/ndarray, predicted data. # Returns mape: Double, result data for train. """ y = [x for x in y_true if x > 0] y_pred = [y_pred[i] for i in range(len(y_true)) if y_true[i] > 0] num = len(y_pred) sums = 0 for i in range(num): tmp = abs(y[i] - y_pred[i]) / y[i] sums += tmp mape = sums * (100 / num) return mape
def parseCoords(coordList): """ Pass in a list of values from <coordinate> elements Return a list of (longitude, latitude, altitude) tuples forming the road geometry """ def parseCoordGroup(coordGroupStr): """ This looks for <coordinates> that form the road geometry, and then parses them into (longitude, latitude, altitude). Altitude is always 0. If the coordinate string is just the coordinates of a place, then return the empty list """ #print "coordGroupStr:", coordGroupStr coords = coordGroupStr.strip().split(" ") if len(coords) > 3: coords = map(lambda x: x.split(","), coords) coords = map(lambda x: tuple(map(float, x)), coords) coords = map(lambda x: (x[1], x[0]), coords) #print 'returning:', coords return coords else: return [] ret = [] #print "coordList:", coordList for coordGroup in coordList: ret += parseCoordGroup(coordGroup) return ret
def bleach(s: str): """Bleach the string of the atom names and element names. Replace '+' with 'p', '-' with 'n'. Strip all the characters except the number and letters. """ return ''.replace("+", "p").replace("-", "n").join((c for c in s if c.isalnum()))
def check_devicon_object(icon: dict): """ Check that the devicon object added is up to standard. :param icon: a dictionary containing info on an icon. Taken from the devicon.json. :return a string containing the error messages if any. """ err_msgs = [] try: for tag in icon["tags"]: if type(tag) != str: raise TypeError() except TypeError: err_msgs.append("- 'tags' must be an array of strings, not: " + str(icon["tags"])) except KeyError: err_msgs.append("- missing key: 'tags'.") try: if type(icon["versions"]) != dict: err_msgs.append("- 'versions' must be an object.") except KeyError: err_msgs.append("- missing key: 'versions'.") try: if type(icon["versions"]["svg"]) != list or len(icon["versions"]["svg"]) == 0: err_msgs.append("- must contain at least 1 svg version in a list.") except KeyError: err_msgs.append("- missing key: 'svg' in 'versions'.") try: if type(icon["versions"]["font"]) != list or len(icon["versions"]["svg"]) == 0: err_msgs.append("- must contain at least 1 font version in a list.") except KeyError: err_msgs.append("- missing key: 'font' in 'versions'.") try: if type(icon["color"]) != str or "#" not in icon["color"]: err_msgs.append("- 'color' must be a string in the format '#abcdef'") except KeyError: err_msgs.append("- missing key: 'color'.") try: if type(icon["aliases"]) != list: err_msgs.append("- 'aliases' must be an array.") except KeyError: err_msgs.append("- missing key: 'aliases'.") if len(err_msgs) > 0: message = "Error found in 'devicon.json' for '{}' entry: \n{}".format(icon["name"], "\n".join(err_msgs)) raise ValueError(message) return ""
def _cell_normal(c1, c2, c3, i, j, cylindrical): """ Return non-dimensional vector normal with magnitude equal to area. If there is no 'z' coordinate, `c1` will be None in cylindrical coordinates, otherwise `c3` will be None. """ # FIXME: built-in ghosts ip1 = i + 1 jp1 = j + 1 # upper-left - lower-right. diag_c11 = 0. if c1 is None else c1(i, jp1) - c1(ip1, j) diag_c21 = c2(i, jp1) - c2(ip1, j) diag_c31 = 0. if c3 is None else c3(i, jp1) - c3(ip1, j) # upper-right - lower-left. diag_c12 = 0. if c1 is None else c1(ip1, jp1) - c1(i, j) diag_c22 = c2(ip1, jp1) - c2(i, j) diag_c32 = 0. if c3 is None else c3(ip1, jp1) - c3(i, j) if cylindrical: r1 = (c2(i, jp1) + c2(ip1, j)) / 2. r2 = (c2(i, j) + c2(ip1, jp1)) / 2. else: r1 = 1. r2 = 1. sc1 = 0.5 * ( r2 * diag_c21 * diag_c32 - r1 * diag_c22 * diag_c31) sc2 = 0.5 * (-r2 * diag_c11 * diag_c32 + r1 * diag_c12 * diag_c31) sc3 = 0.5 * ( diag_c11 * diag_c22 - diag_c12 * diag_c21) return (sc1, sc2, sc3)
def _merge_parameters(primary_parameters, secondary_parameters): """ Merges two default parameters list, Parameters ---------- primary_parameters : `None` or `tuple` of `tuple` (`str`, `Any`) Priority parameters, which element's wont be removed. secondary_parameters : `None` or `tuple` of `tuple` (`str`, `Any`) Secondary parameters, which will be merged to `primary_parameters`. Returns ------- merged_parameters : `None` or `tuple` of `tuple` (`str`, `Any`) The merged parameters. """ if primary_parameters is None: return secondary_parameters if secondary_parameters is None: return primary_parameters extend_parameters = [] for secondary_item in secondary_parameters: parameter_name = secondary_item[0] for priority_item in primary_parameters: if priority_item[0] == parameter_name: break else: extend_parameters.append(secondary_item) if not extend_parameters: return primary_parameters return (*primary_parameters, *extend_parameters)
def code_to_md(source, metadata, language): """ Represent a code cell with given source and metadata as a md cell :param source: :param metadata: :param language: :return: """ options = [] if language: options.append(language) if 'name' in metadata: options.append(metadata['name']) return ['```{}'.format(' '.join(options))] + source + ['```']
def is_kind_of_class(obj, a_class): """checks if an object is an instance of, or if the object is an instance of a class that inherited from, the specified class""" return (isinstance(obj, a_class) or issubclass(type(obj), a_class))
def invertIntervalList(inputList, minValue, maxValue): """ Inverts the segments of a list of intervals e.g. [(0,1), (4,5), (7,10)] -> [(1,4), (5,7)] [(0.5, 1.2), (3.4, 5.0)] -> [(0.0, 0.5), (1.2, 3.4)] """ inputList = sorted(inputList) # Special case -- empty lists if len(inputList) == 0 and minValue is not None and maxValue is not None: invList = [ (minValue, maxValue), ] else: # Insert in a garbage head and tail value for the purpose # of inverting, in the range does not start and end at the # smallest and largest values if minValue is not None and inputList[0][0] > minValue: inputList.insert(0, (-1, minValue)) if maxValue is not None and inputList[-1][1] < maxValue: inputList.append((maxValue, maxValue + 1)) invList = [ (inputList[i][1], inputList[i + 1][0]) for i in range(0, len(inputList) - 1) ] # If two intervals in the input share a boundary, we'll get invalid intervals in the output # eg invertIntervalList([(0, 1), (1, 2)]) -> [(1, 1)] invList = [interval for interval in invList if interval[0] != interval[1]] return invList
def build_form_data(token, username, password): """Build POST dictionary""" return { '_token': token, 'tAccountName': username, 'tWebPassword': password, 'action': 'login' }
def attenuation(og, fg): """Attenuation Parameters ---------- og : float Original gravity, like 1.053 fg : float Final gravity, like 1.004 Returns ------- attenuation : float Attenuation, like 0.92. """ return (og - fg) / (og - 1.0)
def _try_type(value, dtype): """ Examples -------- >>> _try_type("1", int) 1 >>> _try_type(1.0, int) 1 >>> _try_type("ab", float) 'ab' """ try: return dtype(value) except ValueError: return value
def sub_reverse(current, previous, bpp): """ To reverse the effect of the Sub filter after decompression, output the following value: No need to copy as we are calculating Sub plus Raw and Raw is calculated on the fly. Sub(x) + Raw(x-bpp) :param current: byte array representing current scanline. :param previous: byte array representing the previous scanline (not used by this filter type) :param bpp: bytes per pixel :return: reverse-filtered byte array """ for x in range(len(current)): if x == 0: if current[0] != 1: raise IOError(f'{current[0]} passed to Sub reverse filter') continue current[x] = (current[x] + (current[x - bpp] if x - bpp > 0 else 0)) % 256 return current
def lastLetter (s): """Last letter. Params: s (string) Returns: (string) last letter of s """ return s[-1]
def insertion_sort(collection): """ Counts the number of comparisons (between two elements) and swaps between elements while performing an insertion sort :param collection: a collection of comparable elements :return: total number of comparisons and swaps """ comparisons, swaps = 0, 0 for x in range(1, len(collection)): # element currently being compared current = collection[x] # comparing the current element with the sorted portion and swapping while True: if x > 0 and collection[x - 1] > current: collection[x] = collection[x - 1] x -= 1 collection[x] = current comparisons += 1 swaps += 1 else: comparisons += 1 break return comparisons, swaps
def naka_rushton(c, a, b, c50, n): """ Naka-Rushton equation for modeling contrast-response functions. Where: c = contrast a = Rmax (max firing rate) b = baseline firing rate c50 = contrast response at 50% n = exponent """ return (a*(c**n)/((c50**n)+(c**n)) + b)
def to_pascal(string: str) -> str: """Convert a snake_case string into a PascalCase string. Parameters: string: The string to convert to PascalCase. """ return "".join(word.capitalize() for word in string.split("_"))
def PolicyConfig(name: str, configuration: dict, version: str = "builtin", enabled: bool = True) -> dict: """Creates policy config to be passed to API to policy chain Args: :param name: Policy name as known by 3scale :param version: Version of policy; default: 'builtin' :param enabled: Whether policy should be enabled; default: True :param configuration: a dict with configuration or particular policy""" return { "name": name, "version": version, "enabled": enabled, "configuration": configuration}
def argsort_for_list(s, reverse=False): """get index for a sorted list.""" return sorted(range(len(s)), key=lambda k: s[k], reverse=reverse)
def pad_cdb(cdb): """Pad a SCSI CDB to the required 12 bytes""" return (cdb + chr(0)*12)[:12]
def limit(num, minimum=1, maximum=255): """Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.""" return max(min(num, maximum), minimum)
def alternating_cache_event_filter(result): """ Filter that only returns alternating/changed events from cache. """ if result["value"]["_count"] != 1: return return result["value"]["event"]
def get_container_volumes(c): """Extract volume names. Extracts the volume names for a container. Args: c: Container dictionary from portainer api Returns: List of attached volume names """ return list(map(lambda x: x['Name'], filter(lambda x: x['Type'] == 'volume', c['Mounts'])))
def relabel_seg(seg, strand, side): """Relabel Junction, Intron, and Exon change points with APA or ATSS""" label1, label2 = seg[1].split('|') new_label_list = [] for this_label in [label1, label2]: if this_label == 'Junction': if strand == '+': new_label = 'JunctionAPA' if 'R' in side else 'JunctionATSS' elif strand == '-': new_label = 'JunctionAPA' if 'L' in side else 'JunctionATSS' else: new_label = this_label elif this_label == 'Intron': if strand == '+': new_label = 'IntronicAPA' if 'R' in side else 'IntronicATSS' elif strand == '-': new_label = 'IntronicAPA' if 'L' in side else 'IntronicATSS' else: new_label = this_label elif this_label == 'Exon': if strand == '+': new_label = 'ExonicAPA' if 'R' in side else 'ExonicATSS' elif strand == '-': new_label = 'ExonicAPA' if 'L' in side else 'ExonicATSS' else: new_label = this_label else: new_label = this_label new_label_list.append(new_label) seg[1] = '|'.join(new_label_list) return(seg)
def listify(obj): """Make lists from single objects. No changes are made for the argument of the 'list' type.""" if type(obj) is not list: return [obj] else: return obj
def getQuotes(lines): """Movie's quotes.""" quotes = [] qttl = [] for line in lines: if line and line[:2] == ' ' and qttl and qttl[-1] and \ not qttl[-1].endswith('::'): line = line.lstrip() if line: qttl[-1] += ' %s' % line elif not line.strip(): if qttl: quotes.append('::'.join(qttl)) qttl[:] = [] else: line = line.lstrip() if line: qttl.append(line) if qttl: quotes.append('::'.join(qttl)) return quotes
def _is_install_requirement(requirement): """ return True iff setup should install requirement :param requirement: (str) line of requirements.txt file :return: (bool) """ return not (requirement.startswith('-e') or 'git+' in requirement)
def normalize_path(url: str) -> str: """ normalize link to path :param url: path or url to normalize :type url: str :return: normalized path :rtype: str """ url = url.replace("http://", "http/").replace("https://", "https/") illegal_char = [":", "*", "?", '"', "<", ">", "|", "'"] for char in illegal_char: url = url.replace(char, "") if url.startswith("/"): return url[1:] else: return url
def _check_electrification_scenarios_for_download(es): """Checks the electrification scenarios input to :py:func:`download_demand_data` and :py:func:`download_flexibility_data`. :param set/list es: The input electrification scenarios that will be checked. Can be any of: *'Reference'*, *'Medium'*, *'High'*, or *'All'*. :return: (*set*) -- The formatted set of electrification scenarios. :raises TypeError: if es is not input as a set or list, or if the components of es are not input as str. :raises ValueError: if the components of es are not valid. """ # Check that the input is of an appropriate type if not isinstance(es, (set, list)): raise TypeError("Electrification scenarios must be input as a set or list.") # Check that the components of es are str if not all(isinstance(x, str) for x in es): raise TypeError("Individual electrification scenarios must be input as a str.") # Reformat components of es es = {x.capitalize() for x in es} if "All" in es: es = {"Reference", "Medium", "High"} # Check that the components of es are valid if not es.issubset({"Reference", "Medium", "High"}): invalid_es = es - {"Reference", "Medium", "High"} raise ValueError(f'Invalid electrification scenarios: {", ".join(invalid_es)}') # Return the reformatted es return es
def get_unique_elements(list_of_elements, param) -> list: """ Function to remove the redundant tweets in the list :param param: the parameter on which the dictionary should be sorted :param list_of_elements: takes in list of elements where each element is a dictionary :return returns the unique list of elements """ my_dict = {iterator[param]: iterator for iterator in reversed(list_of_elements)} unique_list_of_tweets = list(my_dict.values()) return unique_list_of_tweets
def progress_bar(items_total, items_progress, columns=40, base_char='.', progress_char='#', percentage=False, prefix='', postfix=''): """ Print a progress bar of width `columns` """ bins_total = int(float(items_total) / columns) + 1 bins_progress = int((float(items_progress) / float(items_total)) * bins_total) + 1 progress = prefix progress += progress_char * bins_progress progress += base_char * (bins_total - bins_progress) if percentage: progress_percentage = float(items_progress) / float(items_total) * 100 # Round the percentage to two decimals postfix = ' ' + str(round(progress_percentage, 2)) + '% ' + postfix progress += postfix return progress
def __get_app_package_path(package_type, app_or_model_class): """ :param package_type: :return: """ models_path = [] found = False if isinstance(app_or_model_class, str): app_path_str = app_or_model_class elif hasattr(app_or_model_class, '__module__'): app_path_str = app_or_model_class.__module__ else: raise RuntimeError('Unable to get module path.') for item in app_path_str.split('.'): if item in ['models', 'admin']: models_path.append(package_type) found = True break else: models_path.append(item) if not found: models_path.append(package_type) return '.'.join(models_path)
def is_git_repo(template_repo): """ Returns True if the template_repo looks like a git repository. """ return template_repo.startswith("git@") or \ template_repo.startswith("https://")
def adjust_box(box, size): """ function which try to adjust the box to fit it in a rectangle """ # test if it can fit at all if box[2] - box[0] > size[2] - size[0] or box[3] - box[1] > size[3] - size[1]: return None else: if box[0] < size[0]: delta = size[0] - box[0] box = (box[0] + delta, box[1], box[2] + delta, box[3]) elif box[2] > size[2]: delta = size[2] - box[2] box = (box[0] + delta, box[1], box[2] + delta, box[3]) if box[1] < size[1]: delta = size[1] - box[1] box = (box[0], box[1] + delta, box[2], box[3] + delta) elif box[3] > size[3]: delta = size[3] - box[3] box = (box[0], box[1] + delta, box[2], box[3] + delta) return box
def rankine2celcius(R): """ Convert Rankine Temperature to Celcius :param R: Temperature in Rankine :return: Temperature in Celcius """ return (R - 491.67) * 5.0 / 9
def pbParse(lines, data=None): """ Mini specificationless protobuf parser :param lines: list of lines to parse :param data: dict to update with data :return: protobuf string parsed as dict """ if data is None: data = {} while len(lines) > 0: line = lines[0] ld = line.split(" ") if ld[0].endswith(":"): # Parse key/value ld = line.split(" ") if ld[0].endswith(":"): key = ld[0][:-1] if ld[1].startswith('"') and ld[1].endswith('"'): value = ld[1][1:-1] else: value = float(ld[1]) data[key] = value elif ld[-1].endswith("{"): # Parse dict key = lines[0].split(" ")[0] count = 1 ix = 0 while count > 0: ix += 1 if lines[ix].endswith("}"): count -= 1 elif lines[ix].endswith("{"): count += 1 if key in data: if not isinstance(data[key], list): data[key] = [data[key]] data[key].append(pbParse(lines[1:ix])) else: data[key] = pbParse(lines[1:ix]) lines = lines[ix:] lines = lines[1:] return data
def f7(seq): """ Fast order-preserving elimination of duplicates """ seen = set() return [ x for x in seq if x not in seen and not seen.add(x)]
def formatDefinition(definition): """ :param definition: The definition to format :return: The definition with all existing markdown removed """ definition = definition.replace("[", "") definition = definition.replace("]", "") definition = definition.replace("\"", "") definition = definition.replace("\n\n", "\n") return definition
def quote_string(v): """ RedisGraph strings must be quoted, quote_string wraps given v with quotes incase v is a string. """ if isinstance(v, bytes): v = v.decode() elif not isinstance(v, str): return v if len(v) == 0: return '""' v = v.replace('"', '\\"') return f'"{v}"'
def parse_input(player_input, remaining): """Convert a string of numbers into a list of unique integers, if possible. Then check that each of those integers is an entry in the other list. Parameters: player_input (str): A string of integers, separated by spaces. The player's choices for which numbers to remove. remaining (list): The list of the numbers that still need to be removed before the box can be shut. Returns: A list of the integers if the input was valid. An empty list if the input was invalid. """ try: choices = [int(i) for i in player_input.split()] if len(set(choices)) != len(choices): raise ValueError if any([number not in remaining for number in choices]): raise ValueError return choices except ValueError: return []
def get_param_dict(job, model_keys): """ Get model parameters + hyperparams as dictionary. """ params = dict((" ".join(k.replace(".__builder__", "").split(".")), job.get("hyper_parameters." + k, None)) for k in model_keys) return params
def sanitiseList(parser, vals, img, arg): """Make sure that ``vals`` has the same number of elements as ``img`` has dimensions. Used to sanitise the ``--shape`` and ``--dim`` options. """ if vals is None: return vals nvals = len(vals) if nvals < 3: parser.error('At least three values are ' 'required for {}'.format(arg)) if nvals > img.ndim: parser.error('Input only has {} dimensions - too many values ' 'specified for {}'.format(img.ndim, arg)) if nvals < img.ndim: vals = list(vals) + list(img.shape[nvals:]) return vals
def validate_volume_type(volume_type): """ Property: VolumeConfiguration.VolumeType """ volume_types = ("standard", "io1", "gp2") if volume_type not in volume_types: raise ValueError( "VolumeType (given: %s) must be one of: %s" % (volume_type, ", ".join(volume_types)) ) return volume_type
def trim(line): """Trims any beginning non-alphabet letters. Args: line (str): The line to trim Returns: str: The sliced line, starting from the index of the first alphabetical character to the end """ index = 0 for i in range(len(line)): if line[i].isalpha(): break index = index + 1 return line[index:]
def remove_prefix(text, prefix): """ Remove prefix of a string. Ref: https://stackoverflow.com/questions/16891340/remove-a-prefix-from-a-string """ if text.startswith(prefix): return text[len(prefix):] return text
def __dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s
def mk_impl_expr(expr1, expr2): """ returns an or expression of the form (EXPR1 -> EXPR2) where EXPR1 and EXPR2 are expressions NOTE: Order of expr1 and expr2 matters here """ return {"type" : "impl", "expr1" : expr1 , "expr2" : expr2 }
def toiter(obj): """If `obj` is scalar, wrap it into a list""" try: iter(obj) return obj except TypeError: return [obj]
def scale_range(actual, actual_min, actual_max, wanted_min, wanted_max): """Scales a value from within a range to another range""" return (wanted_max - wanted_min) * ( (actual - actual_min) / (actual_max - actual_min) ) + wanted_min
def getHeaders(lst, filterOne, filterTwo): """ Find indexes of desired values. Gets a list and finds index for values which exist either in filter one or filter two. Parameters: lst (list): Main list which includes the values. filterOne (list): A list containing values to find indexes of in the main list. filterTwo (list): A list to check by for the same index of a value from filterOne if it does not exist in the main list. Returns: (list): A list containing indexes of values either from filterOne or filterTwo. """ headers = [] for i in range(len(filterOne)): if filterOne[i] in lst: headers.append(lst.index(filterOne[i])) else: headers.append(lst.index(filterTwo[i])) return headers
def _bigquery_type_to_charts_type(typename): """Convert bigquery type to charts type.""" typename = typename.lower() if typename == "integer" or typename == "float": return "number" if typename == "timestamp": return "date" return "string"
def calculate_zstats(fid, min, max, mean, median, sd, sum, count): """Calculating basic statistic, determining maximum height in segment""" names = ["id", "min", "max", "mean", "median", "sd", "sum", "count"] feat_stats = {names[0]: fid, names[1]: min, names[2]: max, names[3]: mean, names[4]: median, names[5]: sd, names[6]: sum, names[7]: count } return feat_stats
def constant_time_compare(val1, val2): """ Borrowed from Django! Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when they have different lengths. Since Django only uses it to compare hashes of known expected length, this is acceptable. """ if len(val1) != len(val2): return False result = 0 for x, y in zip(val1, val2): result |= ord(x) ^ ord(y) return result == 0
def rotc(ebit, debt, equity): """Computes return on total capital. Parameters ---------- ebit : int or float Earnins before interest and taxes debt : int or float Short- and long-term debt equity : int or float Equity Returns ------- out : int or float Return on total capital """ return ebit / (debt - equity)
def _is_hex_string(s: str) -> bool: """Returns True if the string consists exclusively of hexadecimal chars.""" hex_chars = '0123456789abcdefABCDEF' return all(c in hex_chars for c in s)
def check_seq_uniqueness(seq, start, stop): """Note: this is a terribly inefficient use of recursion!!!""" if stop - start <= 1: return True # at most one item in sequence. elif not check_seq_uniqueness(seq, start, stop-1): return False elif not check_seq_uniqueness(seq, start+1, stop): return False else: return seq[start] != seq[stop - 1]
def resolve_attr(obj, path): """A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a3... Raises: AttributeError: If there is no such attribute. """ if not path: return obj head, _, tail = path.partition('.') head_obj = getattr(obj, head) return resolve_attr(head_obj, tail)
def clip_scalar(value, vmin, vmax): """A faster numpy.clip ON SCALARS ONLY. See https://github.com/numpy/numpy/issues/14281 """ return vmin if value < vmin else vmax if value > vmax else value
def _xbrli_integer_item_type_validator(value): """Returns python int if value can be converted""" errors = [] if isinstance(value, int): value = int(value) elif isinstance(value, str): try: value = int(value) except: errors.append("'{}' is not a valid integer value.".format(value)) else: errors.append("'{}' is not a valid integer value.".format(value)) return value, errors
def from_contributor(pr_payload): """ If the PR comes from a fork, we can safely assumed it's from an external contributor. """ return pr_payload.get('head', {}).get('repo', {}).get('fork') is True
def build_texts_from_gems(keens): """ Collects available text from each gem inside each keen in a list and returns it :param keens: dict of iid: keen_iid :return: texts: dict of iid: list of strings with text collected from each gem. """ texts = {} for keen in keens.values(): for gem in keen.gems: sents = [gem.text, gem.link_title, gem.link_description] sents = [s for s in sents if s] # filters empty sentences if sents: texts[gem.gem_id] = sents return texts
def _coord_names(frame): """Name the coordinates based on the frame. Examples -------- >>> _coord_names('icrs')[0] 'ra' >>> _coord_names('altaz')[0] 'delta_az' >>> _coord_names('sun')[0] 'hpln' >>> _coord_names('galactic')[0] 'glon' >>> _coord_names('ecliptic')[0] 'elon' >>> _coord_names('turuturu')[0] Traceback (most recent call last): ... ValueError: turuturu: Unknown frame """ if frame in ["icrs", "fk5"]: hor, ver = "ra", "dec" elif frame == "altaz": hor, ver = "delta_az", "delta_el" elif frame == "sun": hor, ver = "hpln", "hplt" elif frame == "galactic": hor, ver = "glon", "glat" elif frame == "ecliptic": hor, ver = "elon", "elat" else: raise ValueError(f"{frame}: Unknown frame") return hor, ver