code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
import pytest import os import numpy as np import pyscal.core as pc import pyscal.crystal_structures as pcs def test_q_4(): atoms, boxdims = pcs.make_crystal('bcc', repetitions = [4, 4, 4]) sys = pc.System() sys.atoms = atoms sys.box = boxdims #sys.get_neighbors(method = 'voronoi') sys.find_neighbors(method = 'cutoff', cutoff=0.9) sys.calculate_q([4, 6], averaged=True) q = sys.get_qvals([4, 6], averaged=True) assert np.round(np.mean(np.array(q[0])), decimals=2) == 0.51 , "Calculated q4 value is wrong!" assert np.round(np.mean(np.array(q[1])), decimals=2) == 0.63 , "Calculated q4 value is wrong!" q = sys.get_qvals([4, 6]) assert np.round(np.mean(np.array(q[0])), decimals=2) == 0.51 , "Calculated q4 value is wrong!" assert np.round(np.mean(np.array(q[1])), decimals=2) == 0.63 , "Calculated q4 value is wrong!"
[ "pyscal.crystal_structures.make_crystal", "numpy.array", "pyscal.core.System" ]
[((153, 199), 'pyscal.crystal_structures.make_crystal', 'pcs.make_crystal', (['"""bcc"""'], {'repetitions': '[4, 4, 4]'}), "('bcc', repetitions=[4, 4, 4])\n", (169, 199), True, 'import pyscal.crystal_structures as pcs\n'), ((213, 224), 'pyscal.core.System', 'pc.System', ([], {}), '()\n', (222, 224), True, 'import pyscal.core as pc\n'), ((489, 503), 'numpy.array', 'np.array', (['q[0]'], {}), '(q[0])\n', (497, 503), True, 'import numpy as np\n'), ((589, 603), 'numpy.array', 'np.array', (['q[1]'], {}), '(q[1])\n', (597, 603), True, 'import numpy as np\n'), ((722, 736), 'numpy.array', 'np.array', (['q[0]'], {}), '(q[0])\n', (730, 736), True, 'import numpy as np\n'), ((822, 836), 'numpy.array', 'np.array', (['q[1]'], {}), '(q[1])\n', (830, 836), True, 'import numpy as np\n')]
# Monitors a directory and if it sees a file or files newer that some time, # create a manifest and send a message to the message queue. from dirmon import checkDir from manifest import generateFileManifest import argparse import json import zmq context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://localhost:5555") # Parse args parser = argparse.ArgumentParser() parser.add_argument('-t','--time', help="Seconds to look back", required=True, type=int ) parser.add_argument('-d','--dir', help="Directory to look in", required=True, type=str ) args = vars(parser.parse_args()) print ("time = {}, dir = {}".format(args['time'], args['dir'])) # Check dir for modified files modified_files = checkDir(args['dir'], last_mtime=args['time']) # If modified files if len(modified_files) > 0: # Create manifest data = {} for f in modified_files: tmp = generateFileManifest(f) for key, value in tmp.items(): data[key] = value print (json.dumps(data, indent=4, sort_keys=True)) # Send message to queue socket.send_string(json.dumps(data)) #socket.send_json(data) repl = socket.recv() print(f"Got {repl}") # Done
[ "argparse.ArgumentParser", "dirmon.checkDir", "manifest.generateFileManifest", "json.dumps", "zmq.Context" ]
[((257, 270), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (268, 270), False, 'import zmq\n'), ((366, 391), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (389, 391), False, 'import argparse\n'), ((782, 828), 'dirmon.checkDir', 'checkDir', (["args['dir']"], {'last_mtime': "args['time']"}), "(args['dir'], last_mtime=args['time'])\n", (790, 828), False, 'from dirmon import checkDir\n'), ((958, 981), 'manifest.generateFileManifest', 'generateFileManifest', (['f'], {}), '(f)\n', (978, 981), False, 'from manifest import generateFileManifest\n'), ((1063, 1105), 'json.dumps', 'json.dumps', (['data'], {'indent': '(4)', 'sort_keys': '(True)'}), '(data, indent=4, sort_keys=True)\n', (1073, 1105), False, 'import json\n'), ((1159, 1175), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (1169, 1175), False, 'import json\n')]
"""Samples given according to http://oauth.net/core/1.0/#sig_base_example""" from __future__ import print_function import unittest from emailage import signature class SignatureTest(unittest.TestCase): def setUp(self): self.method = 'GET' self.url = 'http://photos.example.net/photos' self.params = dict( oauth_consumer_key='<KEY>', oauth_token='<PASSWORD>', oauth_signature_method='HMAC-SHA1', oauth_timestamp=1191242096, oauth_nonce='kllo9940pd9333jh', oauth_version=1.0, file='vacation.jpg', size='original' ) self.hmac_key = '<KEY>' self.test_query_email = '<EMAIL>' self.test_query_ip = '13.25.10.245' self.no_spaces_params = { 'firstname': 'Johann', 'lastname': 'Vandergrift', 'phone': '+14805559163' } self.spaces_params_first_name = { 'firstname': '<NAME>', 'lastname': 'Vandergrift', 'phone': '+14805559163' } self.spaces_params_last_name = { 'firstname': 'Johann', 'lastname': '<NAME>', 'phone': '+14805559163' } self.responseStatusSuccess = { 'status': 'success', 'errorCode': '0', 'description': '' } def _add_test_oauth_params_to_request_dict(self, request_dict): request_dict['oauth_consumer_key'] = 'dpf43f3p2l4k3l03' request_dict['oauth_token'] = '<PASSWORD>' request_dict['oauth_signature_method'] = 'HMAC-SHA1' request_dict['oauth_timestamp'] = 1191242096 request_dict['oauth_nonce'] = 'kllo9940pd9333jh' request_dict['oauth_version'] = 1.0 return request_dict def test_normalizes_query_parameters(self): query = signature.normalize_query_parameters(self.params) self.assertEqual(query, 'file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=<PASSWORD>&oauth_version=1.0&size=original') def test_normalizes_query_spaces_in_first_name(self): query_dict = self._add_test_oauth_params_to_request_dict(self.spaces_params_first_name) normalized_qs = signature.normalize_query_parameters(query_dict) self.assertTrue(normalized_qs.index('%20')) def test_generates_base_string_spaces_in_first_name(self): query_dict = self._add_test_oauth_params_to_request_dict(self.spaces_params_first_name) query_dict['query'] = self.test_query_email normalized_qs = signature.normalize_query_parameters(query_dict) base_string = signature.concatenate_request_elements(self.method, self.url, normalized_qs) self.assertTrue(base_string.index('%2520')) def test_generates_base_string(self): query = signature.normalize_query_parameters(self.params) base_string = signature.concatenate_request_elements(self.method, self.url, query) self.assertEqual(base_string, 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3D<PASSWORD>%26oauth_version%3D1.0%26size%3Doriginal') def test_calculates_signature_value(self): result = signature.create(self.method, self.url, self.params, self.hmac_key) self.assertEqual(result, 'tR3+Ty81lMeYAr/Fid0kMTYa/WM=') if __name__ == '__main__': unittest.main()
[ "unittest.main", "emailage.signature.concatenate_request_elements", "emailage.signature.create", "emailage.signature.normalize_query_parameters" ]
[((3630, 3645), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3643, 3645), False, 'import unittest\n'), ((1882, 1931), 'emailage.signature.normalize_query_parameters', 'signature.normalize_query_parameters', (['self.params'], {}), '(self.params)\n', (1918, 1931), False, 'from emailage import signature\n'), ((2345, 2393), 'emailage.signature.normalize_query_parameters', 'signature.normalize_query_parameters', (['query_dict'], {}), '(query_dict)\n', (2381, 2393), False, 'from emailage import signature\n'), ((2684, 2732), 'emailage.signature.normalize_query_parameters', 'signature.normalize_query_parameters', (['query_dict'], {}), '(query_dict)\n', (2720, 2732), False, 'from emailage import signature\n'), ((2755, 2831), 'emailage.signature.concatenate_request_elements', 'signature.concatenate_request_elements', (['self.method', 'self.url', 'normalized_qs'], {}), '(self.method, self.url, normalized_qs)\n', (2793, 2831), False, 'from emailage import signature\n'), ((2944, 2993), 'emailage.signature.normalize_query_parameters', 'signature.normalize_query_parameters', (['self.params'], {}), '(self.params)\n', (2980, 2993), False, 'from emailage import signature\n'), ((3016, 3084), 'emailage.signature.concatenate_request_elements', 'signature.concatenate_request_elements', (['self.method', 'self.url', 'query'], {}), '(self.method, self.url, query)\n', (3054, 3084), False, 'from emailage import signature\n'), ((3464, 3531), 'emailage.signature.create', 'signature.create', (['self.method', 'self.url', 'self.params', 'self.hmac_key'], {}), '(self.method, self.url, self.params, self.hmac_key)\n', (3480, 3531), False, 'from emailage import signature\n')]
from django.contrib import admin from .models import * admin.site.register(Artwork) admin.site.register(Category) admin.site.register(Artist) admin.site.register(Project)
[ "django.contrib.admin.site.register" ]
[((56, 84), 'django.contrib.admin.site.register', 'admin.site.register', (['Artwork'], {}), '(Artwork)\n', (75, 84), False, 'from django.contrib import admin\n'), ((85, 114), 'django.contrib.admin.site.register', 'admin.site.register', (['Category'], {}), '(Category)\n', (104, 114), False, 'from django.contrib import admin\n'), ((115, 142), 'django.contrib.admin.site.register', 'admin.site.register', (['Artist'], {}), '(Artist)\n', (134, 142), False, 'from django.contrib import admin\n'), ((143, 171), 'django.contrib.admin.site.register', 'admin.site.register', (['Project'], {}), '(Project)\n', (162, 171), False, 'from django.contrib import admin\n')]
import time import math import ast import pickle from collections import defaultdict from whr.player import Player from whr.game import Game from whr.utils import test_stability class Base: def __init__(self, config=None): if config is None: self.config = defaultdict(lambda: None) else: self.config = config if self.config.get("debug") is None: self.config["debug"] = False if self.config.get("w2") is None: self.config["w2"] = 300.0 if self.config.get("uncased") is None: self.config["uncased"] = False self.games = [] self.players = {} def print_ordered_ratings(self, current=False): """displays all ratings for each player (for each of his playing days) ordered Args: current (bool, optional): True to let only the last estimation of the elo, False gets all estimation for each day played """ players = [x for x in self.players.values() if len(x.days) > 0] players.sort(key=lambda x: x.days[-1].gamma()) for p in players: if len(p.days) > 0: if current: print(f"{p.name} => {p.days[-1].elo}") else: print(f"{p.name} => {[x.elo for x in p.days]}") def get_ordered_ratings(self, current=False, compact=False): """gets all ratings for each player (for each of his playing days) ordered Returns: list[list[float]]: for each player and each of his playing day, the corresponding elo Args: current (bool, optional): True to let only the last estimation of the elo, False gets all estimation for each day played compact (bool, optional): True to get only a list of elos, False to get the name before """ result = [] players = [x for x in self.players.values() if len(x.days) > 0] players.sort(key=lambda x: x.days[-1].gamma()) for p in players: if len(p.days) > 0: if current and compact: result.append(p.days[-1].elo) elif current: result.append((p.name, p.days[-1].elo)) elif compact: result.append([x.elo for x in p.days]) else: result.append((p.name, [x.elo for x in p.days])) return result def log_likelihood(self): """gets the likelihood of the current state the more iteration you do the higher the likelihood becomes Returns: float: the likelihood """ score = 0.0 for p in self.players.values(): if len(p.days) > 0: score += p.log_likelihood() return score def player_by_name(self, name): """gets the player object corresponding to the name Args: name (str): the name of the player Returns: Player: the corresponding player """ if self.config["uncased"]: name = name.lower() if self.players.get(name, None) is None: self.players[name] = Player(name, self.config) return self.players[name] def ratings_for_player(self, name, current=False): """gets all rating for each day played for the player Args: name (str): the player's name current (bool, optional): True to let only the last estimation of the elo and uncertainty, False gets all estimation for each day played Returns: list[list[int, float, float]]: for each day, the time_step the elo the uncertainty """ if self.config["uncased"]: name = name.lower() player = self.player_by_name(name) if current: return ( round(player.days[-1].elo), round(player.days[-1].uncertainty * 100), ) return [[d.day, round(d.elo), round(d.uncertainty * 100)] for d in player.days] def _setup_game(self, black, white, winner, time_step, handicap, extras=None): if extras is None: extras = {} if black == white: raise AttributeError("Invalid game (black player == white player)") white_player = self.player_by_name(white) black_player = self.player_by_name(black) game = Game(black_player, white_player, winner, time_step, handicap, extras) return game def create_game(self, black, white, winner, time_step, handicap, extras=None): """creates a new game to be added to the base Args: black (str): the black name white (str): the white name winner (str): "B" if black won, "W" if white won time_step (int): the day of the match from origin handicap (float): the handicap (in elo) extras (dict, optional): extra parameters Returns: Game: the added game """ if extras is None: extras = {} if self.config["uncased"]: black = black.lower() white = white.lower() game = self._setup_game(black, white, winner, time_step, handicap, extras) return self._add_game(game) def _add_game(self, game): game.white_player.add_game(game) game.black_player.add_game(game) if game.bpd is None: print("Bad game") self.games.append(game) return game def iterate(self, count): """do a number of "count" iterations of the algorithm Args: count (int): the number of iterations desired """ for _ in range(count): self._run_one_iteration() for player in self.players.values(): player.update_uncertainty() def auto_iterate(self, time_limit=10, precision=10e-3): """iterates automatically until it converges or reaches the time limit iterates iteratively ten by ten Args: time_limit (int, optional): the maximal time after which no more iteration are launched precision (float, optional): the precision of the stability desired Returns: tuple(int, bool): the number of iterations and True if it has reached stability, False otherwise """ start = time.time() self.iterate(10) a = self.get_ordered_ratings(compact=True) i = 10 while True: self.iterate(10) i += 10 b = self.get_ordered_ratings(compact=True) if test_stability(a, b, precision): return i, True if time.time() - start > time_limit: return i, False a = b def probability_future_match(self, name1, name2, handicap=0): """gets the probability of winning for an hypothetical match against name1 and name2 displays the probability of winning for name1 and name2 in percent rounded to the second decimal Args: name1 (str): name1's name name2 (str): name2's name handicap (int, optional): the handicap (in elo) extras (dict, optional): extra parameters Returns: tuple(int, int): the probability between 0 and 1 for name1 first then name2 """ # Avoid self-played games (no info) if self.config["uncased"]: name1 = name1.lower() name2 = name2.lower() if name1 == name2: raise AttributeError("Invalid game (black == white)") player1 = self.player_by_name(name1) player2 = self.player_by_name(name2) bpd_gamma = 1 bpd_elo = 0 wpd_gamma = 1 wpd_elo = 0 if len(player1.days) > 0: bpd = player1.days[-1] bpd_gamma = bpd.gamma() bpd_elo = bpd.elo if len(player2.days) != 0: wpd = player2.days[-1] wpd_gamma = wpd.gamma() wpd_elo = wpd.elo player1_proba = bpd_gamma / (bpd_gamma + 10 ** ((wpd_elo - handicap) / 400.0)) player2_proba = wpd_gamma / (wpd_gamma + 10 ** ((bpd_elo + handicap) / 400.0)) print( f"win probability: {name1}:{player1_proba*100:.2f}%; {name2}:{player2_proba*100:.2f}%" ) return player1_proba, player2_proba def _run_one_iteration(self): """runs one iteration of the whr algorithm """ for player in self.players.values(): player.run_one_newton_iteration() def load_games(self, games, separator=" "): """loads all games at once given a string representing the path of a file or a list of string representing all games, this function loads all games in the base all match must comply to this format: "black_name white_name winner time_step handicap extras" black_name (required) white_name (required) winner is B or W (required) time_step (required) handicap (optional: default 0) extras is a dict (optional) Args: games (str|list[str]): a path or a list of string representing games separator (str, optional): the separator between all elements of a game, space by default (every element will be trim eventually) """ data = None if isinstance(games, str): with open(games, "r") as f: data = f.readlines() else: data = games for line in data: handicap = 0 extras = None arguments = [x.strip() for x in line.split(separator)] is_correct = False if len(arguments) == 6: try: black, white, winner, time_step, handicap, extras = arguments extras = last = ast.literal_eval(extras) if isinstance(extras, dict): is_correct = True except Exception as e: raise ( AttributeError( f"the extras argument couldn't be evaluated as a dict: {extras}\n{e}" ) ) if len(arguments) == 5: black, white, winner, time_step, last = arguments try: eval_last = ast.literal_eval(last) if isinstance(eval_last, dict): extras = eval_last is_correct = True elif isinstance(eval_last, int): handicap = eval_last is_correct = True except Exception as e: raise ( AttributeError( f"the last argument couldn't be evaluated as an int or a dict: {last}\n{e}" ) ) if len(arguments) == 4: black, white, winner, time_step = arguments is_correct = True if not is_correct: raise ( AttributeError( f"loaded game must have this format: 'black_name white_name winner time_step handicap extras' with handicap (int or dict) and extras (dict) optional. the handicap|extras argument is: {last}" ) ) time_step, handicap = int(time_step), int(handicap) if self.config["uncased"]: black = black.lower() white = white.lower() self.create_game(black, white, winner, time_step, handicap, extras=extras) def save_base(self, path): """saves the current state of the base to a file at "path" Args: path (str): the path where to save the base """ pickle.dump([self.players, self.games, self.config["w2"]], open(path, "wb")) @staticmethod def load_base(path): """loads a saved base Args: path (str): the path to the saved base Returns: Base: the loaded base """ players, games, config = pickle.load(open(path, "rb")) result = Base() result.config["w2"], result.games, result.players = config, games, players return result
[ "whr.utils.test_stability", "whr.player.Player", "time.time", "collections.defaultdict", "whr.game.Game", "ast.literal_eval" ]
[((4485, 4554), 'whr.game.Game', 'Game', (['black_player', 'white_player', 'winner', 'time_step', 'handicap', 'extras'], {}), '(black_player, white_player, winner, time_step, handicap, extras)\n', (4489, 4554), False, 'from whr.game import Game\n'), ((6500, 6511), 'time.time', 'time.time', ([], {}), '()\n', (6509, 6511), False, 'import time\n'), ((283, 309), 'collections.defaultdict', 'defaultdict', (['(lambda : None)'], {}), '(lambda : None)\n', (294, 309), False, 'from collections import defaultdict\n'), ((3248, 3273), 'whr.player.Player', 'Player', (['name', 'self.config'], {}), '(name, self.config)\n', (3254, 3273), False, 'from whr.player import Player\n'), ((6742, 6773), 'whr.utils.test_stability', 'test_stability', (['a', 'b', 'precision'], {}), '(a, b, precision)\n', (6756, 6773), False, 'from whr.utils import test_stability\n'), ((6821, 6832), 'time.time', 'time.time', ([], {}), '()\n', (6830, 6832), False, 'import time\n'), ((10094, 10118), 'ast.literal_eval', 'ast.literal_eval', (['extras'], {}), '(extras)\n', (10110, 10118), False, 'import ast\n'), ((10618, 10640), 'ast.literal_eval', 'ast.literal_eval', (['last'], {}), '(last)\n', (10634, 10640), False, 'import ast\n')]
from rest_framework import viewsets from provider.models import Provider from provider.api.paginations import ProviderPagination from serializers import ProviderSerializer from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAuthenticatedOrReadOnly @permission_classes((IsAuthenticatedOrReadOnly,)) class ProviderViewSet(viewsets.ModelViewSet): queryset = Provider.objects.all() pagination_class = ProviderPagination serializer_class = ProviderSerializer
[ "rest_framework.decorators.permission_classes", "provider.models.Provider.objects.all" ]
[((297, 345), 'rest_framework.decorators.permission_classes', 'permission_classes', (['(IsAuthenticatedOrReadOnly,)'], {}), '((IsAuthenticatedOrReadOnly,))\n', (315, 345), False, 'from rest_framework.decorators import permission_classes\n'), ((407, 429), 'provider.models.Provider.objects.all', 'Provider.objects.all', ([], {}), '()\n', (427, 429), False, 'from provider.models import Provider\n')]
# -*- coding: utf-8 -*- """ Created on Sun May 15 22:37:00 2016 @author: <NAME> """ import random import time import numpy from solution import solution def PSO(objf, lb, ub, dim, popSize, iters): # PSO parameters vMax = 6 wMax = 0.9 wMin = 0.2 c1 = 2 c2 = 2 s = solution() if not isinstance(lb, list): lb = [lb] * dim if not isinstance(ub, list): ub = [ub] * dim ######################## Initializations vel = numpy.zeros((popSize, dim)) pBestScore = numpy.zeros(popSize) pBestScore.fill(float("inf")) pBest = numpy.zeros((popSize, dim)) gBest = numpy.zeros(dim) gBestScore = float("inf") pos = numpy.zeros((popSize, dim)) for i in range(dim): pos[:, i] = numpy.random.uniform(0, 1, popSize) * (ub[i] - lb[i]) + lb[i] convergenceCurve = numpy.zeros(iters) ############################################ print('PSO is optimizing "' + objf.__name__ + '"') timerStart = time.time() s.startTime = time.strftime("%Y-%m-%d-%H-%M-%S") for l in range(0, iters): for i in range(0, popSize): # pos[i,:]=checkBounds(pos[i,:],lb,ub) for j in range(dim): pos[i, j] = numpy.clip(pos[i, j], lb[j], ub[j]) # Calculate objective function for each particle fitness = objf(pos[i, :]) if pBestScore[i] > fitness: pBestScore[i] = fitness pBest[i, :] = pos[i, :].copy() if gBestScore > fitness: gBestScore = fitness gBest = pos[i, :].copy() # Update the W of PSO w = wMax - l * ((wMax - wMin) / iters) for i in range(0, popSize): for j in range(0, dim): r1 = random.random() r2 = random.random() vel[i, j] = ( w * vel[i, j] + c1 * r1 * (pBest[i, j] - pos[i, j]) + c2 * r2 * (gBest[j] - pos[i, j]) ) if vel[i, j] > vMax: vel[i, j] = vMax if vel[i, j] < -vMax: vel[i, j] = -vMax pos[i, j] = pos[i, j] + vel[i, j] convergenceCurve[l] = gBestScore if l % 1 == 0: print( [ "At iteration " + str(l + 1) + " the best fitness is " + str(gBestScore) ] ) timerEnd = time.time() s.endTime = time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime = timerEnd - timerStart s.convergence = convergenceCurve s.optimizer = "PSO" s.objfname = objf.__name__ return s
[ "numpy.random.uniform", "solution.solution", "numpy.zeros", "time.strftime", "numpy.clip", "time.time", "random.random" ]
[((303, 313), 'solution.solution', 'solution', ([], {}), '()\n', (311, 313), False, 'from solution import solution\n'), ((485, 512), 'numpy.zeros', 'numpy.zeros', (['(popSize, dim)'], {}), '((popSize, dim))\n', (496, 512), False, 'import numpy\n'), ((531, 551), 'numpy.zeros', 'numpy.zeros', (['popSize'], {}), '(popSize)\n', (542, 551), False, 'import numpy\n'), ((599, 626), 'numpy.zeros', 'numpy.zeros', (['(popSize, dim)'], {}), '((popSize, dim))\n', (610, 626), False, 'import numpy\n'), ((639, 655), 'numpy.zeros', 'numpy.zeros', (['dim'], {}), '(dim)\n', (650, 655), False, 'import numpy\n'), ((698, 725), 'numpy.zeros', 'numpy.zeros', (['(popSize, dim)'], {}), '((popSize, dim))\n', (709, 725), False, 'import numpy\n'), ((857, 875), 'numpy.zeros', 'numpy.zeros', (['iters'], {}), '(iters)\n', (868, 875), False, 'import numpy\n'), ((1000, 1011), 'time.time', 'time.time', ([], {}), '()\n', (1009, 1011), False, 'import time\n'), ((1030, 1064), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d-%H-%M-%S"""'], {}), "('%Y-%m-%d-%H-%M-%S')\n", (1043, 1064), False, 'import time\n'), ((2549, 2560), 'time.time', 'time.time', ([], {}), '()\n', (2558, 2560), False, 'import time\n'), ((2577, 2611), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d-%H-%M-%S"""'], {}), "('%Y-%m-%d-%H-%M-%S')\n", (2590, 2611), False, 'import time\n'), ((771, 806), 'numpy.random.uniform', 'numpy.random.uniform', (['(0)', '(1)', 'popSize'], {}), '(0, 1, popSize)\n', (791, 806), False, 'import numpy\n'), ((1244, 1279), 'numpy.clip', 'numpy.clip', (['pos[i, j]', 'lb[j]', 'ub[j]'], {}), '(pos[i, j], lb[j], ub[j])\n', (1254, 1279), False, 'import numpy\n'), ((1795, 1810), 'random.random', 'random.random', ([], {}), '()\n', (1808, 1810), False, 'import random\n'), ((1832, 1847), 'random.random', 'random.random', ([], {}), '()\n', (1845, 1847), False, 'import random\n')]
#!/usr/bin/env python3 import sys def is_low(grid: list, r: int, c: int) -> bool: rows = len(grid) cols = len(grid[0]) x = grid[r][c] return ( (r == 0 or grid[r - 1][c] > x) and (c == 0 or grid[r][c - 1] > x) and (r == rows - 1 or grid[r + 1][c] > x) and (c == cols - 1 or grid[r][c + 1] > x) ) def part1(input_txt: str) -> int: grid = [[int(x) for x in line] for line in input_txt.splitlines()] rows = len(grid) cols = len(grid[0]) tot = 0 for r in range(rows): for c in range(cols): x = grid[r][c] if is_low(grid, r, c): tot += 1 + x return tot def part2(input_txt: str) -> int: grid = [[int(x) for x in line] for line in input_txt.splitlines()] rows = len(grid) cols = len(grid[0]) basins = [{(r, c)} for r in range(rows) for c in range(cols) if is_low(grid, r, c)] for b in basins: while True: old_size = len(b) adj = set.union( *( { (r0, c0) for r0, c0 in [(r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)] if 0 <= r0 < rows and 0 <= c0 < cols and grid[r0][c0] > grid[r][c] and grid[r0][c0] != 9 } for (r, c) in b ) ) b |= adj if old_size == len(b): break s = sorted(basins, key=lambda b: len(b), reverse=True) return len(s[0]) * len(s[1]) * len(s[2]) def main(): input_txt = sys.stdin.read() print(part1(input_txt)) print(part2(input_txt)) if __name__ == "__main__": main()
[ "sys.stdin.read" ]
[((1667, 1683), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (1681, 1683), False, 'import sys\n')]
''' Library containing definitions relevent to GRBL-based controllers * List of Supported G-Codes in Grbl v1.1: - Non-Modal Commands: * G4: dwell for given period (X, U, or P) * G10 L2 P?: change G5? work coordinate system origin setting * G10 L20 P?: calculated G5? work coordinate system origin * G28: return to home -- machine zero (aka machine reference point) * G30: return to secondary home position -- machine zero * G28.1: change pre-defined machine home position * G30.1: change pre-defined secondary machine home position * G53: machine coordinate system (MCS), reference machine zero rather than program zero * G92: position register, programming of vector from part zero to tool tip * G92.1: clear position register - Motion Modes: * G0: rapid positioning, one to three axis moves * G1: linear interpolation between start and end points * G2: clockwise circular interpolation * G3: counter-clockwise circular interpolation * G38.2: probe toward workpiece, stop on contact, signal if failure * G38.3: probe toward workpiece, stop on contact * G38.4: probe away from workpiece, stop on loss of contact, signal if failure * G38.5: probe away from workpiece, stop on loss of contact * G80: cancel canned cycle - Feed Rate Modes: * G93: feedrate per minute * G94: fixed cycle, simple cycle, for roughing - Unit Modes: * G20: inches mode * G21: mm mode - Distance Modes: * G90: absolute mode * G91: incremental mode - Arc IJK Distance Modes: * G91.1: incremental IJK arc mode - Plane Select Modes: * G17: select XY plane * G18: select ZX plane * G19: select YZ plane - Tool Length Offset Modes: * G43.1: dynamic tool length offset * G49: tool length offset compensation cancel -- cancels G43 or G44 - Cutter Compensation Modes: * G40: tool radius compensation off -- cancels G41 or G42 - Coordinate System Modes: * G54: Work Coordinate System (WCS) #0 * G55: Work Coordinate System (WCS) #1 * G56: Work Coordinate System (WCS) #2 * G57: Work Coordinate System (WCS) #3 * G58: Work Coordinate System (WCS) #4 * G59: Work Coordinate System (WCS) #5 - Control Modes: * G61: exact stop check, modal, can be cancelled with G64 - Program Flow: * M0: pause running program,resumes when resume button pressed * M1: pause running program if stop switch is on, resumes when resume button pressed * M2: end the program, restart with Cycle Start command * M30*: exchange pallet shuttles and end the program, restart with Cycle Start command - Spindle Control: * M3: start spindle clockwise * M4: start spindle counter-clockwise * M5: stop spindle - Coolant Control: * M7*: turn on mist coolant * M8: turn on flood cooland * M9: turn off both flood and mist coolant - Valid Non-Command Words: * F: feed rate, in defined units * I: define arc center in X axis for G02 or G03 arc commands * J: define arc center in Y axis for G02 or G03 arc commands * K: define arc center in Z axis for G02 or G03 arc commands * L: fixed cycle loop count; register to edit using G10 * N: line/block number in program; system parameter to change using G10 * P: parameter address * R: size of arc radius, or retract height * S: spindle or surface speed, depending on mode (G97 or G96, respectively) * T: tool selection * X: absolute or incremental position of X axis * Y: absolute or incremental position of Y axis * Z: absolute or incremental position of Z axis * Grbl v1.1 "Dollar" Commands - '$$': view settings - '$<num>=<val>': set setting number <num> to <val> - '$#': view gcode parameters * offset values for G5? work coordinates, G28/G30 pre-defined positions, G92 coordinate offset, tool length offsets, and probing * persistent -- written to EEPROM when changed * responds with e.g., - [G54:4.000,0.000,0.000] ... - [G59:0.000,0.000,0.000] - [G28:1.000,2.000,0.000] - [G30:4.000,6.000,0.000] - [G92:0.000,0.000,0.000] - [TLO:0.000] # tool length offset for default z-axis - [PRB:0.000,0.000,0.000:?] # coordinates of last probe cycle, ':1' ending means success, ':0' means failure - '$G': view gcode parser state * shows modal state, organized by modal groups (modal group, member words) '*' is power-on default - Motion Mode: G0*, G1, G2, G3, G38.2, G38.3, G38.4, G38.5, G80 - Coordinate System Select: G54*, G55, G56, G57, G58, G59 - Plane Select: G17*, G18, G19 - * e.g., [GC:G0 G54 G17 G21 G90 G94 M0 M5 M9 T0 S0.0 F500.0] - '$I': view build info * can be (persistently) modified with '$I=<str>' command - '$N<num>': view startup blocks * can be (persistently) modified with '$N<num>=<str>' command - '$C': toggles check g-code mode on/off * process all given g-code, but don't move motors * automatically does soft-reset ('^X') when toggled off - '$X': kill alarm lock * comes up in this state if homing is enabled * shouldn't be used as machine doesn't know its position - should only use G91 and make short moves - do homing cycle asap * does not execute startup lines - '$H': run homing cycle * set G28 or G30 for post-homing start position - e.g., manually jog and then use G28.1/G30.1 to save current position * then G28/G30 to go there - '$J=<cmds>': jog * can queue multiple commands in planning buffer - queued commands are canceled with feed-hold command ('!') * returns 'ok' ack line once command is queued - returns 'error' if not valid or exceeds soft-limit * jog commands do not change g-code parser state * feed rate is interpreted in G94 units per minute * must provide one or more axes (i.e., 'X', 'Y', or 'Z') and feed rate ('F') * optional: G20 (inch), G21 (mm), G90 (absolute), G91 (incremental), G53 (machine coordinates) * example commands: $J=X10.0 Y-1.5 F500 - '$RST=<char>': restore Grbl settings and data to default values * <char> = '$': erase and restore "dollar" ('$$') settings to defaults * <char> = '#': erase and zero all G54-G59 work coordinate offsets and G28/G30 positions in EEPROM - easy way of clearing coordinate settings * <char> = '$': erase and restore all EEPROM settings to defaults - includes '$$' and '$#' settings, '$N' startup lines, and '$I' build info string - '$SLP': enable sleep mode * shut down spindle, coolant, and stepper enable pins * block all commands * exited by soft-reset or power-cycle * part machine in safe location before calling this * Grbl v1.1 Realtime Commands - characteristics * execute in O(10)msec * single character commands that can be sent at any time - no CR/LF required * not considered part of the streaming protocol -- independent - not queued, executed sequentially * tied to corrensponding input pins/buttons - '$': help * returns list of available commands - '[HLP:$$ $# $G $I $N $x=val $Nx=line $J=line $SLP $C $X $H ~ ! ? ctrl-x]' - '^X' (0x18): soft-reset * halts and resets Grbl without power cycle * throws alarm if in motion as position might be lost - if not in motion, retains position and don't have to rehome - '?': status report query * returns runtime data in a status report message * doesn't respond during homing cycle or in alarm state - '~': cycle start/resume * resumes after feed hold and M0 program pauses - otherwise ignored - '!': feed hold * puts Grbl into suspend/HOLD state - if in motion, decelerates and stops * works when in IDLE, RUN, or JOG state - ignored otherwise * does not disable spindle or coolant, only stops motion - 0x84: safety door - 0x85: jog cancel * ignored if not in JOG state - 0x90-0x94: feed rate overrides * immediately change feed rate - doesn't alter rapid rates -- e.g., G0, G28, G30, or jog motions * can't be greater than 200% * 0x90: 100% of programmed rate * 0x91: increase 10% * 0x92: decrease 10% * 0x93: increase 1% * 0x94: decrease 1% - 0x95-0x97: rapid overrides * immediately change rapid rate - only affects rapid rates -- i.e., G0, G28, and G30 * 0x95: set to 100% (full) rapid rate * 0x96: set to 50% of rapid rate * 0x97: set to 25% of rapid rate - 0x99-0x9D: spindle speed overrides * immediately change spindle speed - works even if spindle is not enabled at the time * can't be greater than 200% * 0x99: set to 100% (full) programmed spindle speed * 0x9A: increase spindle speed by 10% * 0x9B: decrease spindle speed by 10% * 0x9C: increase spindle speed by 1% * 0x9D: decrease spindle speed by 1% - 0x9E: toggle spindle stop * only works if machine is in HOLD mode - works even if spindle is not enabled at the time - ignored if in motion * after cycle start spindle state will be restored after 4 secs * can change override speed values while the spindle is stopped - 0xA0: toggle flood coolant * toggles flood coolant on/off * can be done any time in IDLE, RUN, or HOLD states - ignored otherwise * acts like M8/M9, but can be done while running - 0xA1: toggle mist coolant * toggles mist coolant on/off - must be enabled at compile-time, disabled by default * can be done any time in IDLE, RUN, or HOLD states - ignored otherwise * acts like M7/M9, but can be done while running * Grbl Build Options - default enabled * V: Variable Spindle -- No, don't have on my X-Carve * M: Mist Collant (M7) -- Yes, I'll use as vacuum control * C: CoreXY -- ? * P: Parking Motion -- ? * Z: Homing Force Origin -- ? * H: Homing Single Axis Commands -- ? * T: Two limit sitches on axis -- Yes * A: Allow feed rate overrides in probe cycles -- Yes * D: Use spindle direction as enable pin -- ? * 0: Spindle enable off when speed is zero -- ? * S: Software limit pin debouncing -- ? * R: Parking override control -- ? * +: Safety door input pin -- No, don't have on my X-Carve * 2: Dual axis motors -- ? - default disabled * *: Resore all EEPROM command -- ? * $: Restore EEPROM '$' settings command -- ? * #: Resore EEPROM parameter data command -- ? * I: Build info write user string command -- ? * E: Force sync upon EEPROM write -- ? * L: Homing initialization auto-lock -- ? * Grbl CLI - 'ok': command ack at end of execution - 'error:<code>': error of type <code> occurred - '<...>': enclose status report data - 'Grbl <X.Xx> ['$' for help]': startup message version X.Xx - 'ALARM:<code>': alarm of type <code> occurred, controller is now in alarm state - '$<reg>=<val>': set register <reg> to value <val> - '$N<reg>=<val>': set register <reg> to value <val> ???? - '[MSG: ... ]': feedback message given not in response to a query - '[GC: ... ]': message in response to a $G g-code state message query - '[HLP: ... ]': help message - '[G54:], [G55:], [G56:], [G57:], [G58:], [G59:], [G28:], [G30:], [G92:], [TLO:], and [PRB:]': messages with parameter data from $# query - '[VER: ... ]': version/build info from $I query - '[OPT: ... ]': compile time options from $I query - '[echo: ... ]': automated line echo from pre-parsed string prior to g-code parsing * this is a config.h option - '>G54G20:ok': open angle bracket indicates startup line execution * 'ok' means it executed correctly -- no new line required ''' from collections import namedtuple from parse import parse GRBL_VERSION = "1.1hJDN_0.0.1" GRBL_PROMPT = f"Grbl {GRBL_VERSION} ['$' for help]" RX_BUFFER_SIZE = 128 # List of supported G-Codes in V1.1 # N.B. M30 and M7 ???? GCODES = { 'NON_MODAL_CMDS': ["G4", "G10L2", "G10L20", "G28", "G30", "G28.1", "G30.1", "G53", "G92", "G92.1"], 'MOTION_MODES': ["G0", "G1", "G2", "G3", "G38.2", "G38.3", "G38.4", "G38.5", "G80"], 'FEED_MODES': (["G93", "G94"]), 'UNIT_MODES': (["G20", "G21"]), 'DISTANCE_MODES': ["G90", "G91"], 'ARC_MODES': ["G91.1"], 'PLANE_MODES': ["G17", "G18", "G19"], 'TOOL_LENGTH_MODES': ["G43.1", "G49"], 'CUTTER_MODES': ["G40"], 'COORDINATE_MODES': ["G54", "G55", "G56", "G57", "G58", "G59"], 'CONTROL_MODES': ["G61"], 'PROGRAM_FLOW': ["M0", "M1", "M2", "M30"], 'COOLANT_CONTROL': ["M7", "M8", "M9"], 'SPINDLE_CONTROL': ["M3", "M4", "M5"], 'NON_CMD_WORDS': ["F", "I", "J", "K", "L", "N", "P", "R", "S", "T", "X", "Y", "Z"] } ALL_GCODES = [item for sublist in GCODES.values() for item in sublist] ALARM_CODES = [ None, ("Hard limit", "Hard limit has been triggered. Machine position is likely lost due to sudden halt. Re-homing is highly recommended."), ("Soft limit", "Soft limit alarm. G-code motion target exceeds machine travel. Machine position retained. Alarm may be safely unlocked."), ("Abort during cycle", "Reset while in motion. Machine position is likely lost due to sudden halt. Re-homing is highly recommended."), ("Probe fail", "Probe fail. Probe is not in the expected initial state before starting probe cycle when G38.2 and G38.3 is not triggered and G38.4 and G38.5 is triggered."), ("Probe fail", "Probe fail. Probe did not contact the workpiece within the programmed travel for G38.2 and G38.4."), ("Homing fail", "Homing fail. The active homing cycle was reset."), ("Homing fail", "Homing fail. Safety door was opened during homing cycle."), ("Homing fail", "Homing fail. Pull off travel failed to clear limit switch. Try increasing pull-off setting or check wiring."), ("Homing fail", "Homing fail. Could not find limit switch within search distances. Try increasing max travel, decreasing pull-off distance, or check wiring."), ("Homing fail", "Homing fail. Second dual axis limit switch failed to trigger within configured search distance after first. Try increasing trigger fail distance or check wiring.") ] ERROR_CODES = [ None, ("Expected command letter", "G-code words consist of a letter and a value. Letter was not found."), ("Bad number format", "Missing the expected G-code word value or numeric value format is not valid."), ("Invalid statement", "Grbl '$' system command was not recognized or supported."), ("Value < 0", "Negative value received for an expected positive value."), ("Setting disabled", "Homing cycle failure. Homing is not enabled via settings."), ("Value < 3 usec", "Minimum step pulse time must be greater than 3usec."), ("EEPROM read fail. Using defaults", "An EEPROM read failed. Auto-restoring affected EEPROM to default values."), ("Not idle", "Grbl '$' command cannot be used unless Grbl is IDLE. Ensures smooth operation during a job."), ("G-code lock", "G-code commands are locked out during alarm or jog state."), ("Homing not enabled", "Soft limits cannot be enabled without homing also enabled."), ("Line overflow", "Max characters per line exceeded. Received command line was not executed."), ("Step rate > 30kHz", "Grbl '$' setting value cause the step rate to exceed the maximum supported."), ("Check Door", "Safety door detected as opened and door state initiated."), ("Line length exceeded", "Build info or startup line exceeded EEPROM line length limit. Line not stored."), ("Travel exceeded", "Jog target exceeds machine travel. Jog command has been ignored."), ("Invalid jog command", "Jog command has no '=' or contains prohibited g-code."), ("Setting disabled", "Laser mode requires PWM output."), ("Unsupported command", "Unsupported or invalid g-code command found in block."), ("Modal group violation", "More than one g-code command from same modal group found in block."), ("Undefined feed rate", "Feed rate has not yet been set or is undefined."), ("Invalid gcode ID:23", "G-code command in block requires an integer value."), ("Invalid gcode ID:24", "More than one g-code command that requires axis words found in block."), ("Invalid gcode ID:25", "Repeated g-code word found in block."), ("Invalid gcode ID:26", "No axis words found in block for g-code command or current modal state which requires them."), ("Invalid gcode ID:27", "Line number value is invalid."), ("Invalid gcode ID:28", "G-code command is missing a required value word."), ("Invalid gcode ID:29", "G59.x work coordinate systems are not supported."), ("Invalid gcode ID:30", "G53 only allowed with G0 and G1 motion modes."), ("Invalid gcode ID:31", "Axis words found in block when no command or current modal state uses them."), ("Invalid gcode ID:32", "G2 and G3 arcs require at least one in-plane axis word."), ("Invalid gcode ID:33", "Motion command target is invalid."), ("Invalid gcode ID:34", "Arc radius value is invalid."), ("Invalid gcode ID:35", "G2 and G3 arcs require at least one in-plane offset word."), ("Invalid gcode ID:36", "Unused value words found in block."), ("Invalid gcode ID:37", "G43.1 dynamic tool length offset is not assigned to configured tool length axis."), ("Invalid gcode ID:38", "Tool number greater than max supported value."), ] Setting = namedtuple("Setting", "default name units description") #### FIXME fix the default values SETTINGS = { 0: Setting(0, "Step pulse time", "microseconds", "Sets time length per step. Minimum 3usec."), 1: Setting(0, "Step idle delay", "milliseconds", "Sets a short hold delay when stopping to let dynamics settle before disabling steppers. Value 255 keeps motors enabled with no delay."), 2: Setting(0, "Step pulse invert", "mask", "Inverts the step signal. Set axis bit to invert (00000ZYX)."), 3: Setting(0, "Step direction invert", "mask", "Inverts the direction signal. Set axis bit to invert (00000ZYX)."), 4: Setting(0, "Invert step enable pin", "boolean", "Inverts the stepper driver enable pin signal."), 5: Setting(0, "Invert limit pins", "boolean", "Inverts the all of the limit input pins."), 6: Setting(0, "Invert probe pin", "boolean", "Inverts the probe input pin signal."), 10: Setting(0, "Status report options", "mask", "Alters data included in status reports."), 11: Setting(0, "Junction deviation", "millimeters", "Sets how fast Grbl travels through consecutive motions. Lower value slows it down."), 12: Setting(0, "Arc tolerance", "millimeters", "Sets the G2 and G3 arc tracing accuracy based on radial error. Beware: A very small value may effect performance."), 13: Setting(0, "Report in inches", "boolean", "Enables inch units when returning any position and rate value that is not a settings value."), 20: Setting(0, "Soft limits enable", "boolean", "Enables soft limits checks within machine travel and sets alarm when exceeded. Requires homing."), 21: Setting(0, "Hard limits enable", "boolean", "Enables hard limits. Immediately halts motion and throws an alarm when switch is triggered."), 22: Setting(0, "Homing cycle enable", "boolean", "Enables homing cycle. Requires limit switches on all axes."), 23: Setting(0, "Homing direction invert", "mask", "Homing searches for a switch in the positive direction. Set axis bit (00000ZYX) to search in negative direction."), 24: Setting(0, "Homing locate feed rate", "mm/min", "Feed rate to slowly engage limit switch to determine its location accurately."), 25: Setting(0, "Homing search seek rate", "mm/min", "Seek rate to quickly find the limit switch before the slower locating phase."), 26: Setting(0, "Homing switch debounce delay", "milliseconds", "Sets a short delay between phases of homing cycle to let a switch debounce."), 27: Setting(0, "Homing switch pull-off distance", "millimeters", "Retract distance after triggering switch to disengage it. Homing will fail if switch isn't cleared."), 30: Setting(0, "Maximum spindle speed", "RPM", "Maximum spindle speed. Sets PWM to 100% duty cycle."), 31: Setting(0, "Minimum spindle speed", "RPM", "Minimum spindle speed. Sets PWM to 0.4% or lowest duty cycle."), 32: Setting(0, "Laser-mode enable", "boolean", "Enables laser mode. Consecutive G1/2/3 commands will not halt when spindle speed is changed."), 100: Setting(0, "X-axis travel resolution", "step/mm", "X-axis travel resolution in steps per millimeter."), 101: Setting(0, "Y-axis travel resolution", "step/mm", "Y-axis travel resolution in steps per millimeter."), 102: Setting(0, "Z-axis travel resolution", "step/mm", "Z-axis travel resolution in steps per millimeter."), 110: Setting(0, "X-axis maximum rate", "mm/min", "X-axis maximum rate. Used as G0 rapid rate."), 111: Setting(0, "Y-axis maximum rate", "mm/min", "Y-axis maximum rate. Used as G0 rapid rate."), 112: Setting(0, "Z-axis maximum rate", "mm/min", "Z-axis maximum rate. Used as G0 rapid rate."), 120: Setting(0, "X-axis acceleration", "mm/sec^2", "X-axis acceleration. Used for motion planning to not exceed motor torque and lose steps."), 121: Setting(0, "Y-axis acceleration", "mm/sec^2", "Y-axis acceleration. Used for motion planning to not exceed motor torque and lose steps."), 122: Setting(0, "Z-axis acceleration", "mm/sec^2", "Z-axis acceleration. Used for motion planning to not exceed motor torque and lose steps."), 130: Setting(0, "X-axis maximum travel", "millimeters", "Maximum X-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances."), 131: Setting(0, "Y-axis maximum travel", "millimeters", "Maximum Y-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances."), 132: Setting(0, "Z-axis maximum travel", "millimeters", "Maximum Z-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances.") } REALTIME_COMMANDS = { 'CYCLE_START': 0x7e, # cycle start ('~') 'FEED_HOLD': 0x21, # feed hold ('!') 'STATUS': 0x3f, # current status ('?') 'RESET': 0x18, # reset GRBL (Ctrl-X) 'SAFETY_DOOR': 0x84, # SW equivalent of door switch 'JOG_CANCEL': 0x85, # cancels current jog state by Feed Hold and flushes jog commands in buffer 'FEED_100': 0x90, # set feed rate to 100% of programmed rate 'FEED_INCR_10': 0x91, # increase feed rate by 10% of programmed rate 'FEED_DECR_10': 0x92, # decrease feed rate by 10% of programmed rate 'FEED_INCR_1': 0x93, # increase feed rate by 1% of programmed rate 'FEED_DECR_1': 0x94, # decrease feed rate by 1% of programmed rate 'RAPID_100': 0x95, # set rapid rate to full 100% rapid rate 'RAPID_50': 0x96, # set rapid rate to 50% of rapid rate 'RAPID_25': 0x97, # set rapid rate to 25% of rapid rate 'TOGGLE_SPINDLE': 0x9e, # toggle spindle enable/disable -- only in HOLD state 'TOGGLE_FLOOD': 0xa0, # toggle flood coolant state 'TOGGLE_MIST': 0xa1 # toggle mist coolant state } ''' * Grbl v1.1 "Dollar" Commands that aren't just views (some take args): - '$<num>=<val>': set setting number <num> to <val> - '$N<num>=<str>': (persistently) modified startup line <num> - '$C': toggles check g-code mode on/off * returns a startup line (does a soft-reset?), then "[MSG:Enable]"/"[MSG:Disabled]", followed by 'ok' - '$X': kill alarm lock - '$H': run homing cycle - '$J=<cmds>': jog command - '$RST=<char>': restore Grbl settings and data to default values ''' DOLLAR_COMMANDS = { 'VIEW_SETTINGS': "$", # view Grbl settings 'VIEW_PARAMETERS': "#", # view '#' parameters 'VIEW_PARSER': "G", # view parser state 'VIEW_BUILD': "I", # view build info 'VIEW_STARTUPS': "N", # view startup blocks 'GCODE_MODE': "C", # check gcode mode 'KILL_ALARM': "X", # kill alarm lock 'RUN_HOMING': "H", # run homing cycle 'JOG_COMMAND': "J", # jog command 'RESTORE_DATA': "RST", # restore data 'SLEEP': "SLP", # put machine into sleep mode 'HELP': "" # print help message -- no command character, just '$' } def alarmDescription(msg, full=True): """Take a raw Alarm message from the controller and return its description. """ description = None res = parse("ALARM:{num:d}", msg) if res: try: description = ALARM_CODES[res['num']][1 if full else 0] except IndexError: pass return description def errorDescription(msg, full=True): """Take a raw Error message from the controller and return its description. """ description = None res = parse("error:{num:d}", msg) if res: try: description = ERROR_CODES[res['num']][1 if full else 0] except IndexError: pass return description class CommandGroups(): NON_MODAL_CMDS = 0 MOTION_MODES = 1 FEED_MODES = 2 UNIT_MODES = 3 DISTANCE_MODES = 4 ARC_MODES = 5 PLANE_MODES = 6 TOOL_LENGTH_MODES = 7 CUTTER_MODES = 8 COORDINATE_MODES = 9 CONTROL_MODES = 10 PROGRAM_FLOW = 11 COOLANT_CONTROL = 12 SPINDLE_CONTROL = 13 NON_CMD_WORDS = 14 COMMAND_GROUP_NAMES = [v for v in dir(CommandGroups) if not v.startswith('__')] # # TEST # if __name__ == '__main__': #### FIXME add real tests alarmMsg = "ALARM:5" # probe fail print(alarmDescription(alarmMsg)) print(alarmDescription(alarmMsg, False)) print(alarmDescription("ALAR:9")) # should fail errorMsg = "error:13" # check door print(errorDescription(errorMsg)) print(errorDescription(errorMsg, False)) print(errorDescription("eror:3")) # should fail
[ "parse.parse", "collections.namedtuple" ]
[((17554, 17609), 'collections.namedtuple', 'namedtuple', (['"""Setting"""', '"""default name units description"""'], {}), "('Setting', 'default name units description')\n", (17564, 17609), False, 'from collections import namedtuple\n'), ((26319, 26346), 'parse.parse', 'parse', (['"""ALARM:{num:d}"""', 'msg'], {}), "('ALARM:{num:d}', msg)\n", (26324, 26346), False, 'from parse import parse\n'), ((26667, 26694), 'parse.parse', 'parse', (['"""error:{num:d}"""', 'msg'], {}), "('error:{num:d}', msg)\n", (26672, 26694), False, 'from parse import parse\n')]
# Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import shlex, subprocess, time, os, socket, sys command = os.environ.get("LATENCY_TEST_BIN") # Best effort subscriber_proc = subprocess.Popen([command, "subscriber", "--seed", str(os.getpid()), "--hostname"]) publisher_proc = subprocess.Popen([command, "publisher", "--seed", str(os.getpid()), "--hostname", "--export_csv"]) subscriber_proc.communicate() publisher_proc.communicate() # Reliable subscriber_proc = subprocess.Popen([command, "subscriber", "-r", "reliable", "--seed", str(os.getpid()), "--hostname"]) publisher_proc = subprocess.Popen([command, "publisher", "-r", "reliable", "--seed", str(os.getpid()), "--hostname", "--export_csv"]) subscriber_proc.communicate() publisher_proc.communicate() quit()
[ "os.environ.get", "os.getpid" ]
[((676, 710), 'os.environ.get', 'os.environ.get', (['"""LATENCY_TEST_BIN"""'], {}), "('LATENCY_TEST_BIN')\n", (690, 710), False, 'import shlex, subprocess, time, os, socket, sys\n'), ((799, 810), 'os.getpid', 'os.getpid', ([], {}), '()\n', (808, 810), False, 'import shlex, subprocess, time, os, socket, sys\n'), ((899, 910), 'os.getpid', 'os.getpid', ([], {}), '()\n', (908, 910), False, 'import shlex, subprocess, time, os, socket, sys\n'), ((1107, 1118), 'os.getpid', 'os.getpid', ([], {}), '()\n', (1116, 1118), False, 'import shlex, subprocess, time, os, socket, sys\n'), ((1225, 1236), 'os.getpid', 'os.getpid', ([], {}), '()\n', (1234, 1236), False, 'import shlex, subprocess, time, os, socket, sys\n')]
#!/usr/bin/env python """Run a command in every package, in order of increasing dependency.""" import os import subprocess import sys PACKAGE_DEPENDENCY_LIST = [ # Order matters! Packages must be handled in dependency order (most # independent first) in order for them to resolve properly. "contract_addresses", "contract_artifacts", "contract_wrappers", "json_schemas", "sra_client", "order_utils", "middlewares", ] for package in PACKAGE_DEPENDENCY_LIST: print(f"Running command `{sys.argv[1:]}` in package {package}") os.chdir(package) subprocess.check_call(sys.argv[1:]) os.chdir("..")
[ "os.chdir", "subprocess.check_call" ]
[((571, 588), 'os.chdir', 'os.chdir', (['package'], {}), '(package)\n', (579, 588), False, 'import os\n'), ((593, 628), 'subprocess.check_call', 'subprocess.check_call', (['sys.argv[1:]'], {}), '(sys.argv[1:])\n', (614, 628), False, 'import subprocess\n'), ((633, 647), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (641, 647), False, 'import os\n')]
from trame import get_app_instance from trame.html import AbstractElement, Template try: import numpy as np from numbers import Number except: # dataframe_to_grid won't work pass # Make sure used module is available _app = get_app_instance() if "vuetify" not in _app.vue_use: _app.vue_use += ["vuetify"] type_mapper = { "b": ["textColumn"], "i": [], # ["numericColumn", "numberColumnFilter"], "u": [], # ["numericColumn", "numberColumnFilter"], "f": [], # ["numericColumn", "numberColumnFilter"], "c": [], "m": [], # ['timedeltaFormat'], "M": [], # ["dateColumnFilter", "shortDateTimeFormat"], "O": [], "S": [], "U": [], "V": [], } def cast_to_serializable(value): isoformat = getattr(value, "isoformat", None) if (isoformat) and callable(isoformat): return isoformat() elif isinstance(value, Number): if np.isnan(value) or np.isinf(value): return value.__str__() return value return value.__str__() def dataframe_to_grid(dataframe, options={}): """ Transform a dataframe for use with a VDataTable :param dataframe: A pandas dataframe :param options: Control which columns are sortable, filterable, grouped, aligned, etc. A dictionary where keys are the columns from the dataframe and values are Vuetify DataTableHeader objects. See more info |header_doc_link|. .. |header_doc_link| raw:: html <a href="https://vuetifyjs.com/en/api/v-data-table/#props-headers" target="_blank">here</a> >>> headers, rows = vuetify.dataframe_to_grid(dataframe) >>> VDataTable( ... headers=("table_headers", headers), ... items=("table_rows", rows)) """ headers = {} for col_name in dataframe.columns: headers[col_name] = {"text": col_name, "value": col_name} if options.get(col_name): headers[col_name].update(options.get(col_name)) return list(headers.values()), dataframe.applymap(cast_to_serializable).to_dict( orient="records" ) slot_names = [ "day-label", "group.header", "expanded-item", "item.data-table-expand", "group.summary", "body.append", "foot", "no-results", "badge", "category", "placeholder", "icon", "body", "selection", "progress", "day-month", "actions", "group", "header.<name>", "label", "append-outer", "page-text", "day-label-header", "counter", "extension", "close", "prepend-item", "img", "loader", "footer.page-text", "day-header", "prepend", "prev", "item", "interval", "item.data-table-select", "default", "divider", "no-data", "footer", "top", "thumb-label", "opposite", "append-item", "body.prepend", "appendIcon", "prepend-inner", "loading", "header.data-table-select", "activator", "day-body", "header", "event", "item.<name>", "message", "footer.prepend", "prependIcon", "next", "input", "append", "day", "action", ] Template.slot_names.update(slot_names) class VApp(AbstractElement): """ Vuetify's VApp component. See more info and examples |VApp_vuetify_link|. .. |VApp_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-app" target="_blank">here</a> :param id: Sets the DOM id on the component :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-app", children, **kwargs) self._attr_names += [ "id", ] class VAppBar(AbstractElement): """ Vuetify's VAppBar component. See more info and examples |VAppBar_vuetify_link|. .. |VAppBar_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-app-bar" target="_blank">here</a> :param absolute: Applies position: absolute to the component. :type boolean: :param app: See description |VAppBar_vuetify_link|. :type boolean: :param bottom: Aligns the component towards the bottom. :type boolean: :param clipped_left: Designates that the application's `v-navigation-drawer` that is positioned on the left is below the app-bar. :type boolean: :param clipped_right: Designates that the application's `v-navigation-drawer` that is positioned on the right is below the app-bar. :type boolean: :param collapse: Puts the toolbar into a collapsed state reducing its maximum width. :type boolean: :param collapse_on_scroll: Puts the app-bar into a collapsed state when scrolling. :type boolean: :param color: See description |VAppBar_vuetify_link|. :type string: :param dark: See description |VAppBar_vuetify_link|. :type boolean: :param dense: Reduces the height of the toolbar content to 48px (96px when using the **prominent** prop). :type boolean: :param elevate_on_scroll: Elevates the app-bar when scrolling. :type boolean: :param elevation: See description |VAppBar_vuetify_link|. :type ['number', 'string']: :param extended: Use this prop to increase the height of the toolbar _without_ using the `extension` slot for adding content. May be used in conjunction with the **extension-height** prop, and any of the other props that affect the height of the toolbar, e.g. **prominent**, **dense**, etc., **WITH THE EXCEPTION** of **height**. :type boolean: :param extension_height: Specify an explicit height for the `extension` slot. :type ['number', 'string']: :param fade_img_on_scroll: When using the **src** prop or `img` slot, will fade the image when scrolling. :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param flat: Removes the toolbar's box-shadow. :type boolean: :param floating: Applies **display: inline-flex** to the component. :type boolean: :param height: Designates a specific height for the toolbar. Overrides the heights imposed by other props, e.g. **prominent**, **dense**, **extended**, etc. :type ['number', 'string']: :param hide_on_scroll: Hides the app-bar when scrolling. Will still show the `extension` slot. :type boolean: :param inverted_scroll: Hides the app-bar when scrolling down and displays it when scrolling up. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param prominent: Increases the height of the toolbar content to 128px. :type boolean: :param rounded: See description |VAppBar_vuetify_link|. :type ['boolean', 'string']: :param scroll_off_screen: Hides the app-bar when scrolling. Will **NOT** show the `extension` slot. :type boolean: :param scroll_target: Designates the element to target for scrolling events. Uses `window` by default. :type string: :param scroll_threshold: The amount of scroll distance down before **hide-on-scroll** activates. :type ['string', 'number']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param short: Reduce the height of the toolbar content to 56px (112px when using the **prominent** prop). :type boolean: :param shrink_on_scroll: Shrinks a **prominent** toolbar to a **dense** or **short** (default) one when scrolling. :type boolean: :param src: Image source. See `v-img` for details :type ['string', 'object']: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the component's **border-radius**. :type boolean: :param value: Controls whether the component is visible or hidden. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-app-bar", children, **kwargs) self._attr_names += [ "absolute", "app", "bottom", "clipped_left", "clipped_right", "collapse", "collapse_on_scroll", "color", "dark", "dense", "elevate_on_scroll", "elevation", "extended", "extension_height", "fade_img_on_scroll", "fixed", "flat", "floating", "height", "hide_on_scroll", "inverted_scroll", "light", "max_height", "max_width", "min_height", "min_width", "outlined", "prominent", "rounded", "scroll_off_screen", "scroll_target", "scroll_threshold", "shaped", "short", "shrink_on_scroll", "src", "tag", "tile", "value", "width", ] class VAppBarNavIcon(AbstractElement): """ Vuetify's VAppBarNavIcon component. See more info and examples |VAppBarNavIcon_vuetify_link|. .. |VAppBarNavIcon_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-app-bar-nav-icon" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-app-bar-nav-icon", children, **kwargs) class VAppBarTitle(AbstractElement): """ Vuetify's VAppBarTitle component. See more info and examples |VAppBarTitle_vuetify_link|. .. |VAppBarTitle_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-app-bar-title" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-app-bar-title", children, **kwargs) class VAlert(AbstractElement): """ Vuetify's VAlert component. See more info and examples |VAlert_vuetify_link|. .. |VAlert_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-alert" target="_blank">here</a> :param border: Puts a border on the alert. Accepts **top** \| **right** \| **bottom** \| **left**. :type string: :param close_icon: Change the default icon used for **dismissible** alerts. :type string: :param close_label: See description |VAlert_vuetify_link|. :type string: :param color: See description |VAlert_vuetify_link|. :type string: :param colored_border: Applies the defined **color** to the alert's border. :type boolean: :param dark: See description |VAlert_vuetify_link|. :type boolean: :param dense: Decreases component's height. :type boolean: :param dismissible: Adds a close icon that can hide the alert. :type boolean: :param elevation: See description |VAlert_vuetify_link|. :type ['number', 'string']: :param height: Sets the height for the component. :type ['number', 'string']: :param icon: Designates a specific icon. :type ['boolean', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param mode: See description |VAlert_vuetify_link|. :type string: :param origin: See description |VAlert_vuetify_link|. :type string: :param outlined: Makes the background transparent and applies a thin border. :type boolean: :param prominent: Displays a larger vertically centered icon to draw more attention. :type boolean: :param rounded: See description |VAlert_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param text: Applies the defined **color** to text and a low opacity background of the same. :type boolean: :param tile: Removes the component's border-radius. :type boolean: :param transition: See description |VAlert_vuetify_link|. :type string: :param type: Specify a **success**, **info**, **warning** or **error** alert. Uses the contextual color and has a pre-defined icon. :type string: :param value: Controls whether the component is visible or hidden. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: Events :param input: The updated bound model """ def __init__(self, children=None, **kwargs): super().__init__("v-alert", children, **kwargs) self._attr_names += [ "border", "close_icon", "close_label", "color", "colored_border", "dark", "dense", "dismissible", "elevation", "height", "icon", "light", "max_height", "max_width", "min_height", "min_width", "mode", "origin", "outlined", "prominent", "rounded", "shaped", "tag", "text", "tile", "transition", "type", "value", "width", ] self._event_names += [ "input", ] class VAutocomplete(AbstractElement): """ Vuetify's VAutocomplete component. See more info and examples |VAutocomplete_vuetify_link|. .. |VAutocomplete_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-autocomplete" target="_blank">here</a> :param allow_overflow: Allow the menu to overflow off the screen :type boolean: :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param append_outer_icon: Appends an icon to the outside the component's input, uses same syntax as `v-icon` :type string: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param auto_select_first: When searching, will always highlight the first option :type boolean: :param autofocus: Enables autofocus :type boolean: :param background_color: Changes the background-color of the input :type string: :param cache_items: Keeps a local _unique_ copy of all items that have been passed through the **items** prop. :type boolean: :param chips: Changes display of selections to chips :type boolean: :param clear_icon: Applied when using **clearable** and the input is dirty :type string: :param clearable: Add input clear functionality, default icon is Material Design Icons **mdi-clear** :type boolean: :param color: See description |VAutocomplete_vuetify_link|. :type string: :param counter: Creates counter for input length; if no number is specified, it defaults to 25. Does not apply any validation. :type ['boolean', 'number', 'string']: :param counter_value: :type function: :param dark: See description |VAutocomplete_vuetify_link|. :type boolean: :param deletable_chips: Adds a remove icon to selected chips :type boolean: :param dense: Reduces the input height :type boolean: :param disable_lookup: Disables keyboard lookup :type boolean: :param disabled: Disables the input :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param filled: Applies the alternate filled input style :type boolean: :param filter: See description |VAutocomplete_vuetify_link|. :type function: :param flat: Removes elevation (shadow) added to element when using the **solo** or **solo-inverted** props :type boolean: :param full_width: Designates input type as full-width :type boolean: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hide_no_data: Hides the menu when there are no options to show. Useful for preventing the menu from opening before results are fetched asynchronously. Also has the effect of opening the menu when the `items` array changes if not already open. :type boolean: :param hide_selected: Do not display in the select menu items that are already selected :type boolean: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param item_color: Sets color of selected items :type string: :param item_disabled: Set property of **items**'s disabled value :type ['string', 'array', 'function']: :param item_text: Set property of **items**'s text value :type ['string', 'array', 'function']: :param item_value: See description |VAutocomplete_vuetify_link|. :type ['string', 'array', 'function']: :param items: Can be an array of objects or array of strings. When using objects, will look for a text, value and disabled keys. This can be changed using the **item-text**, **item-value** and **item-disabled** props. Objects that have a **header** or **divider** property are considered special cases and generate a list header or divider; these items are not selectable. :type array: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param menu_props: Pass props through to the `v-menu` component. Accepts either a string for boolean props `menu-props="auto, overflowY"`, or an object `:menu-props="{ auto: true, overflowY: true }"` :type ['string', 'array', 'object']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Changes select to multiple. Accepts array for value :type boolean: :param no_data_text: Display text when there is no data :type string: :param no_filter: Do not apply filtering when searching. Useful when data is being filtered server side :type boolean: :param open_on_clear: When using the **clearable** prop, once cleared, the select menu will either open or stay open, depending on the current state :type boolean: :param outlined: Applies the outlined style to the input :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param persistent_placeholder: Forces placeholder to always be visible :type boolean: :param placeholder: Sets the input's placeholder text :type string: :param prefix: Displays prefix text :type string: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param prepend_inner_icon: Prepends an icon inside the component's input, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param return_object: Changes the selection behavior to return the object directly rather than the value specified with **item-value** :type boolean: :param reverse: Reverses the input orientation :type boolean: :param rounded: Adds a border radius to the input :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param search_input: Search value. Can be used with `.sync` modifier. :type string: :param shaped: Round if `outlined` and increase `border-radius` if `filled`. Must be used with either `outlined` or `filled` :type boolean: :param single_line: Label does not move on focus/dirty :type boolean: :param small_chips: Changes display of selections to chips with the **small** property :type boolean: :param solo: Changes the style of the input :type boolean: :param solo_inverted: Reduces element opacity until focused :type boolean: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param suffix: Displays suffix text :type string: :param type: Sets input type :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param value_comparator: See description |VAutocomplete_vuetify_link|. :type function: Events :param blur: Emitted when the input is blurred :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_append_outer: Emitted when appended outer icon is clicked :param click_clear: Emitted when clearable icon clicked :param click_prepend: Emitted when prepended icon is clicked :param click_prepend_inner: Emitted when prepended inner icon is clicked :param focus: Emitted when component is focused :param input: The updated bound model :param keydown: Emitted when **any** key is pressed :param update_error: The `error.sync` event :param update_list_index: Emitted when menu item is selected using keyboard arrows :param update_search_input: The `search-input.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-autocomplete", children, **kwargs) self._attr_names += [ "allow_overflow", "append_icon", "append_outer_icon", "attach", "auto_select_first", "autofocus", "background_color", "cache_items", "chips", "clear_icon", "clearable", "color", "counter", "counter_value", # JS functions unimplemented "dark", "deletable_chips", "dense", "disable_lookup", "disabled", "eager", "error", "error_count", "error_messages", "filled", "filter", # JS functions unimplemented "flat", "full_width", "height", "hide_details", "hide_no_data", "hide_selected", "hint", "id", "item_color", "item_disabled", # JS functions unimplemented "item_text", # JS functions unimplemented "item_value", # JS functions unimplemented "items", "label", "light", "loader_height", "loading", "menu_props", "messages", "multiple", "no_data_text", "no_filter", "open_on_clear", "outlined", "persistent_hint", "persistent_placeholder", "placeholder", "prefix", "prepend_icon", "prepend_inner_icon", "readonly", "return_object", "reverse", "rounded", "rules", "search_input", "shaped", "single_line", "small_chips", "solo", "solo_inverted", "success", "success_messages", "suffix", "type", "validate_on_blur", "value", "value_comparator", # JS functions unimplemented ] self._event_names += [ "blur", "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_append_outer", "click:append-outer"), ("click_clear", "click:clear"), ("click_prepend", "click:prepend"), ("click_prepend_inner", "click:prepend-inner"), "focus", "input", "keydown", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ("update_list_index", "update:list-index"), ("update_search_input", "update:search-input"), ] class VAvatar(AbstractElement): """ Vuetify's VAvatar component. See more info and examples |VAvatar_vuetify_link|. .. |VAvatar_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-avatar" target="_blank">here</a> :param color: See description |VAvatar_vuetify_link|. :type string: :param height: Sets the height for the component. :type ['number', 'string']: :param left: See description |VAvatar_vuetify_link|. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param right: See description |VAvatar_vuetify_link|. :type boolean: :param rounded: See description |VAvatar_vuetify_link|. :type ['boolean', 'string']: :param size: Sets the height and width of the component. :type ['number', 'string']: :param tile: Removes the component's **border-radius**. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-avatar", children, **kwargs) self._attr_names += [ "color", "height", "left", "max_height", "max_width", "min_height", "min_width", "right", "rounded", "size", "tile", "width", ] class VBadge(AbstractElement): """ Vuetify's VBadge component. See more info and examples |VBadge_vuetify_link|. .. |VBadge_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-badge" target="_blank">here</a> :param avatar: Removes badge padding for the use of the `v-avatar` in the **badge** slot. :type boolean: :param bordered: Applies a **2px** by default and **1.5px** border around the badge when using the **dot** property. :type boolean: :param bottom: Aligns the component towards the bottom. :type boolean: :param color: See description |VBadge_vuetify_link|. :type string: :param content: Any content you want injected as text into the badge. :type any: :param dark: See description |VBadge_vuetify_link|. :type boolean: :param dot: Reduce the size of the badge and hide its contents :type boolean: :param icon: Designates a specific icon used in the badge. :type string: :param inline: Moves the badge to be inline with the wrapping element. Supports the usage of the **left** prop. :type boolean: :param label: The **aria-label** used for the badge :type string: :param left: Aligns the component towards the left. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mode: See description |VBadge_vuetify_link|. :type string: :param offset_x: Offset the badge on the x-axis. :type ['number', 'string']: :param offset_y: Offset the badge on the y-axis. :type ['number', 'string']: :param origin: See description |VBadge_vuetify_link|. :type string: :param overlap: Overlaps the slotted content on top of the component. :type boolean: :param tile: Removes the component's border-radius. :type boolean: :param transition: See description |VBadge_vuetify_link|. :type string: :param value: Controls whether the component is visible or hidden. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-badge", children, **kwargs) self._attr_names += [ "avatar", "bordered", "bottom", "color", "content", "dark", "dot", "icon", "inline", "label", "left", "light", "mode", "offset_x", "offset_y", "origin", "overlap", "tile", "transition", "value", ] class VBanner(AbstractElement): """ Vuetify's VBanner component. See more info and examples |VBanner_vuetify_link|. .. |VBanner_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-banner" target="_blank">here</a> :param app: When used inside of `v-main`, will calculate top based upon application `v-toolbar` and `v-system-bar`. :type boolean: :param color: See description |VBanner_vuetify_link|. :type string: :param dark: See description |VBanner_vuetify_link|. :type boolean: :param elevation: See description |VBanner_vuetify_link|. :type ['number', 'string']: :param height: Sets the height for the component. :type ['number', 'string']: :param icon: Designates a specific icon. :type string: :param icon_color: Designates a specific icon color. :type string: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param mobile_breakpoint: Sets the designated mobile breakpoint for the component. :type ['number', 'string']: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param rounded: See description |VBanner_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param single_line: Forces the banner onto a single line. :type boolean: :param sticky: See description |VBanner_vuetify_link|. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the component's **border-radius**. :type boolean: :param value: Controls whether the component is visible or hidden. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-banner", children, **kwargs) self._attr_names += [ "app", "color", "dark", "elevation", "height", "icon", "icon_color", "light", "max_height", "max_width", "min_height", "min_width", "mobile_breakpoint", "outlined", "rounded", "shaped", "single_line", "sticky", "tag", "tile", "value", "width", ] class VBottomNavigation(AbstractElement): """ Vuetify's VBottomNavigation component. See more info and examples |VBottomNavigation_vuetify_link|. .. |VBottomNavigation_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-bottom-navigation" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param active_class: See description |VBottomNavigation_vuetify_link|. :type string: :param app: See description |VBottomNavigation_vuetify_link|. :type boolean: :param background_color: Changes the background-color for the component. :type string: :param color: See description |VBottomNavigation_vuetify_link|. :type string: :param dark: See description |VBottomNavigation_vuetify_link|. :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param grow: See description |VBottomNavigation_vuetify_link|. :type boolean: :param height: Sets the height for the component. :type ['number', 'string']: :param hide_on_scroll: Will transition the navigation off screen when scrolling up. :type boolean: :param horizontal: See description |VBottomNavigation_vuetify_link|. :type boolean: :param input_value: Controls whether the component is visible or hidden. Supports the **.sync** modifier. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param scroll_target: Designates the element to target for scrolling events. Uses `window` by default. :type string: :param scroll_threshold: The amount of scroll distance down before **hide-on-scroll** activates. :type ['string', 'number']: :param shift: See description |VBottomNavigation_vuetify_link|. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param value: See description |VBottomNavigation_vuetify_link|. :type any: :param width: Sets the width for the component. :type ['number', 'string']: Events :param change: The value of currently selected button. If no value is assigned, will be the current index of the button. :param update_input_value: The event used for `input-value.sync`. """ def __init__(self, children=None, **kwargs): super().__init__("v-bottom-navigation", children, **kwargs) self._attr_names += [ "absolute", "active_class", "app", "background_color", "color", "dark", "fixed", "grow", "height", "hide_on_scroll", "horizontal", "input_value", "light", "mandatory", "max_height", "max_width", "min_height", "min_width", "scroll_target", "scroll_threshold", "shift", "tag", "value", "width", ] self._event_names += [ "change", ("update_input_value", "update:input-value"), ] class VBottomSheet(AbstractElement): """ Vuetify's VBottomSheet component. See more info and examples |VBottomSheet_vuetify_link|. .. |VBottomSheet_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-bottom-sheet" target="_blank">here</a> :param activator: Designate a custom activator when the `activator` slot is not used. String can be any valid querySelector and Object can be any valid Node. :type any: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param close_delay: Milliseconds to wait before closing component. :type ['number', 'string']: :param content_class: Applies a custom class to the detached element. This is useful because the content is moved to the beginning of the `v-app` component (unless the **attach** prop is provided) and is not targetable by classes passed directly on the component. :type string: :param dark: See description |VBottomSheet_vuetify_link|. :type boolean: :param disabled: Disables the ability to open the component. :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param fullscreen: Changes layout for fullscreen display. :type boolean: :param hide_overlay: Hides the display of the overlay. :type boolean: :param inset: Reduces the sheet content maximum width to 70%. :type boolean: :param internal_activator: Detaches the menu content inside of the component as opposed to the document. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param max_width: Sets the maximum width for the component. :type ['string', 'number']: :param no_click_animation: Disables the bounce effect when clicking outside of a `v-dialog`'s content when using the **persistent** prop. :type boolean: :param open_delay: Milliseconds to wait before opening component. :type ['number', 'string']: :param open_on_focus: :type boolean: :param open_on_hover: Designates whether component should activate when its activator is hovered. :type boolean: :param origin: See description |VBottomSheet_vuetify_link|. :type string: :param overlay_color: Sets the overlay color. :type string: :param overlay_opacity: Sets the overlay opacity. :type ['number', 'string']: :param persistent: Clicking outside of the element or pressing **esc** key will not deactivate it. :type boolean: :param retain_focus: Tab focus will return to the first child of the dialog by default. Disable this when using external tools that require focus such as TinyMCE or vue-clipboard. :type boolean: :param return_value: :type any: :param scrollable: See description |VBottomSheet_vuetify_link|. :type boolean: :param transition: See description |VBottomSheet_vuetify_link|. :type string: :param value: Controls whether the component is visible or hidden. :type any: :param width: Sets the width for the component. :type ['string', 'number']: """ def __init__(self, children=None, **kwargs): super().__init__("v-bottom-sheet", children, **kwargs) self._attr_names += [ "activator", "attach", "close_delay", "content_class", "dark", "disabled", "eager", "fullscreen", "hide_overlay", "inset", "internal_activator", "light", "max_width", "no_click_animation", "open_delay", "open_on_focus", "open_on_hover", "origin", "overlay_color", "overlay_opacity", "persistent", "retain_focus", "return_value", "scrollable", "transition", "value", "width", ] class VBreadcrumbs(AbstractElement): """ Vuetify's VBreadcrumbs component. See more info and examples |VBreadcrumbs_vuetify_link|. .. |VBreadcrumbs_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-breadcrumbs" target="_blank">here</a> :param dark: See description |VBreadcrumbs_vuetify_link|. :type boolean: :param divider: Specifies the dividing character between items. :type string: :param items: An array of objects for each breadcrumb. :type array: :param large: Increase the font-size of the breadcrumb item text to 16px (14px default). :type boolean: :param light: Applies the light theme variant to the component. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-breadcrumbs", children, **kwargs) self._attr_names += [ "dark", "divider", "items", "large", "light", ] class VBreadcrumbsItem(AbstractElement): """ Vuetify's VBreadcrumbsItem component. See more info and examples |VBreadcrumbsItem_vuetify_link|. .. |VBreadcrumbsItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-breadcrumbs-item" target="_blank">here</a> :param active_class: See description |VBreadcrumbsItem_vuetify_link|. :type string: :param append: See description |VBreadcrumbsItem_vuetify_link|. :type boolean: :param disabled: Removes the ability to click or target the component. :type boolean: :param exact: See description |VBreadcrumbsItem_vuetify_link|. :type boolean: :param exact_active_class: See description |VBreadcrumbsItem_vuetify_link|. :type string: :param exact_path: See description |VBreadcrumbsItem_vuetify_link|. :type boolean: :param href: Designates the component as anchor and applies the **href** attribute. :type ['string', 'object']: :param link: Designates that the component is a link. This is automatic when using the **href** or **to** prop. :type boolean: :param nuxt: See description |VBreadcrumbsItem_vuetify_link|. :type boolean: :param replace: See description |VBreadcrumbsItem_vuetify_link|. :type boolean: :param ripple: See description |VBreadcrumbsItem_vuetify_link|. :type ['boolean', 'object']: :param tag: Specify a custom tag used on the root element. :type string: :param target: Designates the target attribute. This should only be applied when using the **href** prop. :type string: :param to: See description |VBreadcrumbsItem_vuetify_link|. :type ['string', 'object']: """ def __init__(self, children=None, **kwargs): super().__init__("v-breadcrumbs-item", children, **kwargs) self._attr_names += [ "active_class", "append", "disabled", "exact", "exact_active_class", "exact_path", "href", "link", "nuxt", "replace", "ripple", "tag", "target", "to", ] class VBreadcrumbsDivider(AbstractElement): """ Vuetify's VBreadcrumbsDivider component. See more info and examples |VBreadcrumbsDivider_vuetify_link|. .. |VBreadcrumbsDivider_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-breadcrumbs-divider" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-breadcrumbs-divider", children, **kwargs) class VBtn(AbstractElement): """ Vuetify's VBtn component. See more info and examples |VBtn_vuetify_link|. .. |VBtn_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-btn" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param active_class: See description |VBtn_vuetify_link|. :type string: :param append: See description |VBtn_vuetify_link|. :type boolean: :param block: Expands the button to 100% of available space. :type boolean: :param bottom: Aligns the component towards the bottom. :type boolean: :param color: See description |VBtn_vuetify_link|. :type string: :param dark: See description |VBtn_vuetify_link|. :type boolean: :param depressed: Removes the button box shadow. :type boolean: :param disabled: Removes the ability to click or target the component. :type boolean: :param elevation: See description |VBtn_vuetify_link|. :type ['number', 'string']: :param exact: See description |VBtn_vuetify_link|. :type boolean: :param exact_active_class: See description |VBtn_vuetify_link|. :type string: :param exact_path: See description |VBtn_vuetify_link|. :type boolean: :param fab: Designates the button as a floating-action-button. Button will become _round_. :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param height: Sets the height for the component. :type ['number', 'string']: :param href: Designates the component as anchor and applies the **href** attribute. :type ['string', 'object']: :param icon: Designates the button as icon. Button will become _round_ and applies the **text** prop. :type boolean: :param input_value: Controls the button's active state. :type any: :param large: Makes the component large. :type boolean: :param left: Aligns the component towards the left. This should be used with the **absolute** or **fixed** props. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param link: Designates that the component is a link. This is automatic when using the **href** or **to** prop. :type boolean: :param loading: Adds a loading icon animation. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param nuxt: See description |VBtn_vuetify_link|. :type boolean: :param outlined: Makes the background transparent and applies a thin border. :type boolean: :param plain: Removes the default background change applied when hovering over the button. :type boolean: :param replace: See description |VBtn_vuetify_link|. :type boolean: :param retain_focus_on_click: Don't blur on click. :type boolean: :param right: Aligns the component towards the right. This should be used with the **absolute** or **fixed** props. :type boolean: :param ripple: See description |VBtn_vuetify_link|. :type ['boolean', 'object']: :param rounded: Applies a large border radius on the button. :type boolean: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param small: Makes the component small. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param target: Designates the target attribute. This should only be applied when using the **href** prop. :type string: :param text: Makes the background transparent. When using the **color** prop, the color will be applied to the button text instead of the background. :type boolean: :param tile: Removes the component's **border-radius**. :type boolean: :param to: See description |VBtn_vuetify_link|. :type ['string', 'object']: :param top: Aligns the content towards the top. :type boolean: :param type: Set the button's **type** attribute. :type string: :param value: Controls whether the component is visible or hidden. :type any: :param width: Sets the width for the component. :type ['number', 'string']: :param x_large: Makes the component extra large. :type boolean: :param x_small: Makes the component extra small. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-btn", children, **kwargs) self._attr_names += [ "absolute", "active_class", "append", "block", "bottom", "color", "dark", "depressed", "disabled", "elevation", "exact", "exact_active_class", "exact_path", "fab", "fixed", "height", "href", "icon", "input_value", "large", "left", "light", "link", "loading", "max_height", "max_width", "min_height", "min_width", "nuxt", "outlined", "plain", "replace", "retain_focus_on_click", "right", "ripple", "rounded", "shaped", "small", "tag", "target", "text", "tile", "to", "top", "type", "value", "width", "x_large", "x_small", ] self._event_names += [ # click, #Implemented in AbstractElement parent class ] class VBtnToggle(AbstractElement): """ Vuetify's VBtnToggle component. See more info and examples |VBtnToggle_vuetify_link|. .. |VBtnToggle_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-btn-toggle" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param background_color: Changes the background-color for the component. :type string: :param borderless: Removes the group's border. :type boolean: :param color: See description |VBtnToggle_vuetify_link|. :type string: :param dark: See description |VBtnToggle_vuetify_link|. :type boolean: :param dense: Reduces the button size and padding. :type boolean: :param group: See description |VBtnToggle_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param rounded: Round edge buttons :type boolean: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the component's border-radius. :type boolean: :param value: The designated model value for the component. :type any: Events :param change: Emitted when the input is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-btn-toggle", children, **kwargs) self._attr_names += [ "active_class", "background_color", "borderless", "color", "dark", "dense", "group", "light", "mandatory", "max", "multiple", "rounded", "shaped", "tag", "tile", "value", ] self._event_names += [ "change", ] class VCalendar(AbstractElement): """ Vuetify's VCalendar component. See more info and examples |VCalendar_vuetify_link|. .. |VCalendar_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-calendar" target="_blank">here</a> :param categories: Specifies what categories to display in the `category` view. This controls the order of the categories as well. If the calendar uses events any categories specified in those events not specified in this value are dynamically rendered in the view unless `category-hide-dynamic` is true. :type ['array', 'string']: :param category_days: The number of days to render in the `category` view. :type ['number', 'string']: :param category_for_invalid: The category to place events in that have invalid categories. A category is invalid when it is not a string. By default events without a category are not displayed until this value is specified. :type string: :param category_hide_dynamic: Sets whether categories specified in an event should be hidden if it's not defined in `categories`. :type boolean: :param category_show_all: Set whether the `category` view should show all defined `categories` even if there are no events for a category. :type boolean: :param category_text: If categories is a list of objects, you can use this to determine what property to print out as the category text on the calendar. You can provide a function to do some logic or just define the prop name. It's similar to item-text on v-select :type ['string', 'function']: :param color: See description |VCalendar_vuetify_link|. :type string: :param dark: See description |VCalendar_vuetify_link|. :type boolean: :param day_format: Formats day of the month string that appears in a day to a specified locale :type function: :param end: The ending date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param event_category: Set property of *event*'s category. Instead of a property a function can be given which takes an event and returns the category. :type ['string', 'function']: :param event_color: A background color for all events or a function which accepts an event object passed to the calendar to return a color. :type ['string', 'function']: :param event_end: Set property of *event*'s end timestamp. :type string: :param event_height: The height of an event in pixels in the `month` view and at the top of the `day` views. :type number: :param event_margin_bottom: Margin bottom for event :type number: :param event_more: Whether the more 'button' is displayed on a calendar with too many events in a given day. It will say something like '5 more' and when clicked generates a `click:more` event. :type boolean: :param event_more_text: The text to display in the more 'button' given the number of hidden events. :type string: :param event_name: Set property of *event*'s displayed name, or a function which accepts an event object passed to the calendar as the first argument and a flag signalling whether the name is for a timed event (true) or an event over a day. :type ['string', 'function']: :param event_overlap_mode: One of `stack`, `column`, or a custom render function :type ['string', 'function']: :param event_overlap_threshold: A value in minutes that's used to determine whether two timed events should be placed in column beside each other or should be treated as slightly overlapping events. :type ['string', 'number']: :param event_ripple: Applies the `v-ripple` directive. :type ['boolean', 'object']: :param event_start: Set property of *event*'s start timestamp. :type string: :param event_text_color: A text color for all events or a function which accepts an event object passed to the calendar to return a color. :type ['string', 'function']: :param event_timed: If Dates or milliseconds are used as the start or end timestamp of an event, this prop can be a string to a property on the event that is truthy if the event is a timed event or a function which takes the event and returns a truthy value if the event is a timed event. :type ['string', 'function']: :param events: An array of event objects with a property for a start timestamp and optionally a name and end timestamp. If an end timestamp is not given, the value of start will be used. If no name is given, you must provide an implementation for the `event` slot. :type array: :param first_interval: The first interval to display in the `day` view. If `intervalMinutes` is set to 60 and this is set to 9 the first time in the view is 9am. :type ['number', 'string']: :param first_time: The first time to display in the `day` view. If specified, this overwrites any `firstInterval` value specified. This can be the number of minutes since midnight, a string in the format of `HH:mm`, or an object with number properties hour and minute. :type ['number', 'string', 'object']: :param hide_header: If the header at the top of the `day` view should be visible. :type boolean: :param interval_count: The number of intervals to display in the `day` view. :type ['number', 'string']: :param interval_format: Formats time of day string that appears in the interval gutter of the `day` and `week` view to specified locale :type function: :param interval_height: The height of an interval in pixels in the `day` view. :type ['number', 'string']: :param interval_minutes: The number of minutes the intervals are in the `day` view. A common interval is 60 minutes so the intervals are an hour. :type ['number', 'string']: :param interval_style: Returns CSS styling to apply to the interval. :type function: :param interval_width: The width of the interval gutter on the left side in the `day` view. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param locale: The locale of the calendar. :type string: :param locale_first_day_of_year: Sets the day that determines the first week of the year, starting with 0 for **Sunday**. For ISO 8601 this should be 4. :type ['string', 'number']: :param max_days: The maximum number of days to display in the custom calendar if an `end` day is not set. :type number: :param min_weeks: The minimum number of weeks to display in the `month` or `week` view. :type any: :param month_format: Formats month string that appears in a day to specified locale :type function: :param now: Override the day & time which is considered now. This is in the format of `YYYY-MM-DD hh:mm:ss`. The calendar is styled according to now. :type string: :param short_intervals: If true, the intervals in the `day` view will be 9 AM as opposed to 09:00 AM :type boolean: :param short_months: Whether the short versions of a month should be used (Jan vs January). :type boolean: :param short_weekdays: Whether the short versions of a weekday should be used (Mon vs Monday). :type boolean: :param show_interval_label: Checks if a given day and time should be displayed in the interval gutter of the `day` view. :type function: :param show_month_on_first: Whether the name of the month should be displayed on the first day of the month. :type boolean: :param show_week: Whether week numbers should be displayed when using the `month` view. :type boolean: :param start: The starting date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param type: A string which is one of `month`, `week`, `day`, `4day`, `custom-weekly`, `custom-daily`, and `category`. The custom types look at the `start` and `end` dates passed to the component as opposed to the `value`. :type string: :param value: A date in the format of `YYYY-MM-DD` which determines what span of time for the calendar. :type ['string', 'number', 'date']: :param weekday_format: Formats day of the week string that appears in the header to specified locale :type function: :param weekdays: Specifies which days of the week to display. To display Monday through Friday only, a value of `[1, 2, 3, 4, 5]` can be used. To display a week starting on Monday a value of `[1, 2, 3, 4, 5, 6, 0]` can be used. :type ['array', 'string']: Events :param change: The range of days displayed on the calendar changed. This is triggered on initialization. The event passed is an object with start and end date objects. :param click_date: The click event on the day of the month link. The event passed is the day & time object. :param click_day: The click event on a day. The event passed is the day object. :param click_day_category: The click event on a day in the `category` view. The event passed is the day object. :param click_event: The click event on a specific event. The event passed is the day & time object. :param click_interval: The click event at a specific interval label in the `day` view. The event passed is the day & time object. :param click_more: The click event on the `X more` button on views with too many events in a day. :param click_time: The click event at a specific time in the `day` view. The event passed is the day & time object. :param click_time_category: The click event at a specific time in the `category` view. The event passed is the day & time object. :param contextmenu_date: The right-click event on the day of the month link. The event passed is the day & time object. :param contextmenu_day: The right-click event on a day. The event passed is the day object. :param contextmenu_day_category: The right-click event on a day in the `category` view. The event passed is the day object. :param contextmenu_event: The right-click event on an event. The event passed is the day & time object. :param contextmenu_interval: The right-click event at a specific interval label in the `day` view. The event passed is the day & time object. :param contextmenu_time: The right-click event at a specific time in the `day` view. The event passed is the day & time object. :param contextmenu_time_category: The right-click event at a specific time in the `category` view. The event passed is the day & time object. :param input: An alias to the `click:date` event used to support v-model. :param mousedown_day: The mousedown event on a day. The event passed is the day object. :param mousedown_day_category: The mousedown event on a day in the `category` view. The event passed is the day object. :param mousedown_event: The mousedown event on an event. The event passed is the day & time object. :param mousedown_interval: The mousedown event at a specific interval label in the `day` view. The event passed is the day & time object. :param mousedown_time: The mousedown event at a specific time in the `day` view. The event passed is the day & time object. :param mousedown_time_category: The mousedown event at a specific time in the `category` view. The event passed is the day & time object. :param mouseenter_day: The mouseenter event on a day. The event passed is the day object. :param mouseenter_day_category: The mouseenter event on a day in the `category` view. The event passed is the day object. :param mouseenter_event: The mouseenter event on an event. The event passed is the day & time object. :param mouseenter_interval: The mouseenter event at a specific interval label in the `day` view. The event passed is the day & time object. :param mouseenter_time: The mouseenter event at a specific time in the `day` view. The event passed is the day & time object. :param mouseenter_time_category: The mouseenter event at a specific time in the `category` view. The event passed is the day & time object. :param mouseleave_day: The mouseleave event on a day. The event passed is the day object. :param mouseleave_day_category: The mouseleave event on a day in the `category` view. The event passed is the day object. :param mouseleave_event: The mouseleave event on an event. The event passed is the day & time object. :param mouseleave_interval: The mouseleave event at a specific interval label in the `day` view. The event passed is the day & time object. :param mouseleave_time: The mouseleave event at a specific time in the `day` view. The event passed is the day & time object. :param mouseleave_time_category: The mouseleave event at a specific time in the `category` view. The event passed is the day & time object. :param mousemove_day: The mousemove event on a day. The event passed is the day object. :param mousemove_day_category: The mousemove event on a day in the `category` view. The event passed is the day object. :param mousemove_event: The mousemove event on an event. The event passed is the day & time object. :param mousemove_interval: The mousemove event at a specific interval label in the `day` view. The event passed is the day & time object. :param mousemove_time: The mousemove event at a specific time in the `day` view. The event passed is the day & time object. :param mousemove_time_category: The mousemove event at a specific time in the `category` view. The event passed is the day & time object. :param mouseup_day: The mouseup event on a day. The event passed is the day object. :param mouseup_day_category: The mouseup event on a day in the `category` view. The event passed is the day object. :param mouseup_event: The mouseup event on an event. The event passed is the day & time object. :param mouseup_interval: The mouseup event at a specific interval label in the `day` view. The event passed is the day & time object. :param mouseup_time: The mouseup event at a specific time in the `day` view. The event passed is the day & time object. :param mouseup_time_category: The mouseup event at a specific time in the `category` view. The event passed is the day & time object. :param moved: One of the functions `next`, `prev`, and `move` was called. The event passed is the day object calculated for the movement. :param touchend_day: The touchend event on a day. The event passed is the day object. :param touchend_day_category: The touchend event on a day in the `category` view. The event passed is the day object. :param touchend_event: The touchend event on am view. The event passed is the day & time object. :param touchend_interval: The touchend event at a specific interval label in the `day` view. The event passed is the day & time object. :param touchend_time: The touchend event at a specific time in the `day` view. The event passed is the day & time object. :param touchend_time_category: The touchend event at a specific time in the `category` view. The event passed is the day & time object. :param touchmove_day: The touchmove event on a day. The event passed is the day object. :param touchmove_day_category: The touchmove event on a day in the `category` view. The event passed is the day object. :param touchmove_event: The touchmove event on an `event` view. The event passed is the day & time object. :param touchmove_interval: The touchmove event at a specific interval label in the `day` view. The event passed is the day & time object. :param touchmove_time: The touchmove event at a specific time in the `day` view. The event passed is the day & time object. :param touchmove_time_category: The touchmove event at a specific time in the `category` view. The event passed is the day & time object. :param touchstart_day: The touchstart event on a day. The event passed is the day object. :param touchstart_day_category: The touchstart event on a day in the `category` view. The event passed is the day object. :param touchstart_event: The touchstart event on an event` view. The event passed is the day & time object. :param touchstart_interval: The touchstart event at a specific interval label in the `day` view. The event passed is the day & time object. :param touchstart_time: The touchstart event at a specific time in the `day` view. The event passed is the day & time object. :param touchstart_time_category: The touchstart event at a specific time in the `category` view. The event passed is the day & time object. """ def __init__(self, children=None, **kwargs): super().__init__("v-calendar", children, **kwargs) self._attr_names += [ "categories", "category_days", "category_for_invalid", "category_hide_dynamic", "category_show_all", "category_text", # JS functions unimplemented "color", "dark", "day_format", # JS functions unimplemented "end", "event_category", # JS functions unimplemented "event_color", # JS functions unimplemented "event_end", "event_height", "event_margin_bottom", "event_more", "event_more_text", "event_name", # JS functions unimplemented "event_overlap_mode", # JS functions unimplemented "event_overlap_threshold", "event_ripple", "event_start", "event_text_color", # JS functions unimplemented "event_timed", # JS functions unimplemented "events", "first_interval", "first_time", "hide_header", "interval_count", "interval_format", # JS functions unimplemented "interval_height", "interval_minutes", "interval_style", # JS functions unimplemented "interval_width", "light", "locale", "locale_first_day_of_year", "max_days", "min_weeks", "month_format", # JS functions unimplemented "now", "short_intervals", "short_months", "short_weekdays", "show_interval_label", # JS functions unimplemented "show_month_on_first", "show_week", "start", "type", "value", "weekday_format", # JS functions unimplemented "weekdays", ] self._event_names += [ "change", ("click_date", "click:date"), ("click_day", "click:day"), ("click_day_category", "click:day-category"), ("click_event", "click:event"), ("click_interval", "click:interval"), ("click_more", "click:more"), ("click_time", "click:time"), ("click_time_category", "click:time-category"), ("contextmenu_date", "contextmenu:date"), ("contextmenu_day", "contextmenu:day"), ("contextmenu_day_category", "contextmenu:day-category"), ("contextmenu_event", "contextmenu:event"), ("contextmenu_interval", "contextmenu:interval"), ("contextmenu_time", "contextmenu:time"), ("contextmenu_time_category", "contextmenu:time-category"), "input", ("mousedown_day", "mousedown:day"), ("mousedown_day_category", "mousedown:day-category"), ("mousedown_event", "mousedown:event"), ("mousedown_interval", "mousedown:interval"), ("mousedown_time", "mousedown:time"), ("mousedown_time_category", "mousedown:time-category"), ("mouseenter_day", "mouseenter:day"), ("mouseenter_day_category", "mouseenter:day-category"), ("mouseenter_event", "mouseenter:event"), ("mouseenter_interval", "mouseenter:interval"), ("mouseenter_time", "mouseenter:time"), ("mouseenter_time_category", "mouseenter:time-category"), ("mouseleave_day", "mouseleave:day"), ("mouseleave_day_category", "mouseleave:day-category"), ("mouseleave_event", "mouseleave:event"), ("mouseleave_interval", "mouseleave:interval"), ("mouseleave_time", "mouseleave:time"), ("mouseleave_time_category", "mouseleave:time-category"), ("mousemove_day", "mousemove:day"), ("mousemove_day_category", "mousemove:day-category"), ("mousemove_event", "mousemove:event"), ("mousemove_interval", "mousemove:interval"), ("mousemove_time", "mousemove:time"), ("mousemove_time_category", "mousemove:time-category"), ("mouseup_day", "mouseup:day"), ("mouseup_day_category", "mouseup:day-category"), ("mouseup_event", "mouseup:event"), ("mouseup_interval", "mouseup:interval"), ("mouseup_time", "mouseup:time"), ("mouseup_time_category", "mouseup:time-category"), "moved", ("touchend_day", "touchend:day"), ("touchend_day_category", "touchend:day-category"), ("touchend_event", "touchend:event"), ("touchend_interval", "touchend:interval"), ("touchend_time", "touchend:time"), ("touchend_time_category", "touchend:time-category"), ("touchmove_day", "touchmove:day"), ("touchmove_day_category", "touchmove:day-category"), ("touchmove_event", "touchmove:event"), ("touchmove_interval", "touchmove:interval"), ("touchmove_time", "touchmove:time"), ("touchmove_time_category", "touchmove:time-category"), ("touchstart_day", "touchstart:day"), ("touchstart_day_category", "touchstart:day-category"), ("touchstart_event", "touchstart:event"), ("touchstart_interval", "touchstart:interval"), ("touchstart_time", "touchstart:time"), ("touchstart_time_category", "touchstart:time-category"), ] class VCalendarDaily(AbstractElement): """ Vuetify's VCalendarDaily component. See more info and examples |VCalendarDaily_vuetify_link|. .. |VCalendarDaily_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-calendar-daily" target="_blank">here</a> :param color: See description |VCalendarDaily_vuetify_link|. :type string: :param dark: See description |VCalendarDaily_vuetify_link|. :type boolean: :param day_format: Formats day of the month string that appears in a day to a specified locale :type function: :param end: The ending date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param first_interval: The first interval to display in the `day` view. If `intervalMinutes` is set to 60 and this is set to 9 the first time in the view is 9am. :type ['number', 'string']: :param first_time: The first time to display in the `day` view. If specified, this overwrites any `firstInterval` value specified. This can be the number of minutes since midnight, a string in the format of `HH:mm`, or an object with number properties hour and minute. :type ['number', 'string', 'object']: :param hide_header: If the header at the top of the `day` view should be visible. :type boolean: :param interval_count: The number of intervals to display in the `day` view. :type ['number', 'string']: :param interval_format: Formats time of day string that appears in the interval gutter of the `day` and `week` view to specified locale :type function: :param interval_height: The height of an interval in pixels in the `day` view. :type ['number', 'string']: :param interval_minutes: The number of minutes the intervals are in the `day` view. A common interval is 60 minutes so the intervals are an hour. :type ['number', 'string']: :param interval_style: Returns CSS styling to apply to the interval. :type function: :param interval_width: The width of the interval gutter on the left side in the `day` view. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param locale: The locale of the calendar. :type string: :param max_days: The maximum number of days to display in the custom calendar if an `end` day is not set. :type number: :param now: Override the day & time which is considered now. This is in the format of `YYYY-MM-DD hh:mm:ss`. The calendar is styled according to now. :type string: :param short_intervals: If true, the intervals in the `day` view will be 9 AM as opposed to 09:00 AM :type boolean: :param short_weekdays: Whether the short versions of a weekday should be used (Mon vs Monday). :type boolean: :param show_interval_label: Checks if a given day and time should be displayed in the interval gutter of the `day` view. :type function: :param start: The starting date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param weekday_format: Formats day of the week string that appears in the header to specified locale :type function: :param weekdays: Specifies which days of the week to display. To display Monday through Friday only, a value of `[1, 2, 3, 4, 5]` can be used. To display a week starting on Monday a value of `[1, 2, 3, 4, 5, 6, 0]` can be used. :type ['array', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-calendar-daily", children, **kwargs) self._attr_names += [ "color", "dark", "day_format", # JS functions unimplemented "end", "first_interval", "first_time", "hide_header", "interval_count", "interval_format", # JS functions unimplemented "interval_height", "interval_minutes", "interval_style", # JS functions unimplemented "interval_width", "light", "locale", "max_days", "now", "short_intervals", "short_weekdays", "show_interval_label", # JS functions unimplemented "start", "weekday_format", # JS functions unimplemented "weekdays", ] class VCalendarWeekly(AbstractElement): """ Vuetify's VCalendarWeekly component. See more info and examples |VCalendarWeekly_vuetify_link|. .. |VCalendarWeekly_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-calendar-weekly" target="_blank">here</a> :param color: See description |VCalendarWeekly_vuetify_link|. :type string: :param dark: See description |VCalendarWeekly_vuetify_link|. :type boolean: :param day_format: Formats day of the month string that appears in a day to a specified locale :type function: :param end: The ending date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param hide_header: If the header at the top of the `day` view should be visible. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param locale: The locale of the calendar. :type string: :param locale_first_day_of_year: Sets the day that determines the first week of the year, starting with 0 for **Sunday**. For ISO 8601 this should be 4. :type ['string', 'number']: :param min_weeks: The minimum number of weeks to display in the `month` or `week` view. :type any: :param month_format: Formats month string that appears in a day to specified locale :type function: :param now: Override the day & time which is considered now. This is in the format of `YYYY-MM-DD hh:mm:ss`. The calendar is styled according to now. :type string: :param short_months: Whether the short versions of a month should be used (Jan vs January). :type boolean: :param short_weekdays: Whether the short versions of a weekday should be used (Mon vs Monday). :type boolean: :param show_month_on_first: Whether the name of the month should be displayed on the first day of the month. :type boolean: :param show_week: Whether week numbers should be displayed when using the `month` view. :type boolean: :param start: The starting date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param weekday_format: Formats day of the week string that appears in the header to specified locale :type function: :param weekdays: Specifies which days of the week to display. To display Monday through Friday only, a value of `[1, 2, 3, 4, 5]` can be used. To display a week starting on Monday a value of `[1, 2, 3, 4, 5, 6, 0]` can be used. :type ['array', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-calendar-weekly", children, **kwargs) self._attr_names += [ "color", "dark", "day_format", # JS functions unimplemented "end", "hide_header", "light", "locale", "locale_first_day_of_year", "min_weeks", "month_format", # JS functions unimplemented "now", "short_months", "short_weekdays", "show_month_on_first", "show_week", "start", "weekday_format", # JS functions unimplemented "weekdays", ] class VCalendarMonthly(AbstractElement): """ Vuetify's VCalendarMonthly component. See more info and examples |VCalendarMonthly_vuetify_link|. .. |VCalendarMonthly_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-calendar-monthly" target="_blank">here</a> :param color: See description |VCalendarMonthly_vuetify_link|. :type string: :param dark: See description |VCalendarMonthly_vuetify_link|. :type boolean: :param day_format: Formats day of the month string that appears in a day to a specified locale :type function: :param end: The ending date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param hide_header: If the header at the top of the `day` view should be visible. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param locale: The locale of the calendar. :type string: :param locale_first_day_of_year: Sets the day that determines the first week of the year, starting with 0 for **Sunday**. For ISO 8601 this should be 4. :type ['string', 'number']: :param min_weeks: The minimum number of weeks to display in the `month` or `week` view. :type any: :param month_format: Formats month string that appears in a day to specified locale :type function: :param now: Override the day & time which is considered now. This is in the format of `YYYY-MM-DD hh:mm:ss`. The calendar is styled according to now. :type string: :param short_months: Whether the short versions of a month should be used (Jan vs January). :type boolean: :param short_weekdays: Whether the short versions of a weekday should be used (Mon vs Monday). :type boolean: :param show_month_on_first: Whether the name of the month should be displayed on the first day of the month. :type boolean: :param show_week: Whether week numbers should be displayed when using the `month` view. :type boolean: :param start: The starting date on the calendar (inclusive) in the format of `YYYY-MM-DD`. This may be ignored depending on the `type` of the calendar. :type ['string', 'number', 'date']: :param weekday_format: Formats day of the week string that appears in the header to specified locale :type function: :param weekdays: Specifies which days of the week to display. To display Monday through Friday only, a value of `[1, 2, 3, 4, 5]` can be used. To display a week starting on Monday a value of `[1, 2, 3, 4, 5, 6, 0]` can be used. :type ['array', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-calendar-monthly", children, **kwargs) self._attr_names += [ "color", "dark", "day_format", # JS functions unimplemented "end", "hide_header", "light", "locale", "locale_first_day_of_year", "min_weeks", "month_format", # JS functions unimplemented "now", "short_months", "short_weekdays", "show_month_on_first", "show_week", "start", "weekday_format", # JS functions unimplemented "weekdays", ] class VCard(AbstractElement): """ Vuetify's VCard component. See more info and examples |VCard_vuetify_link|. .. |VCard_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-card" target="_blank">here</a> :param active_class: See description |VCard_vuetify_link|. :type string: :param append: See description |VCard_vuetify_link|. :type boolean: :param color: See description |VCard_vuetify_link|. :type string: :param dark: See description |VCard_vuetify_link|. :type boolean: :param disabled: Removes the ability to click or target the component. :type boolean: :param elevation: See description |VCard_vuetify_link|. :type ['number', 'string']: :param exact: See description |VCard_vuetify_link|. :type boolean: :param exact_active_class: See description |VCard_vuetify_link|. :type string: :param exact_path: See description |VCard_vuetify_link|. :type boolean: :param flat: Removes the card's elevation. :type boolean: :param height: Sets the height for the component. :type ['number', 'string']: :param hover: See description |VCard_vuetify_link|. :type boolean: :param href: Designates the component as anchor and applies the **href** attribute. :type ['string', 'object']: :param img: See description |VCard_vuetify_link|. :type string: :param light: Applies the light theme variant to the component. :type boolean: :param link: Designates that the component is a link. This is automatic when using the **href** or **to** prop. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param nuxt: See description |VCard_vuetify_link|. :type boolean: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param raised: See description |VCard_vuetify_link|. :type boolean: :param replace: See description |VCard_vuetify_link|. :type boolean: :param ripple: See description |VCard_vuetify_link|. :type ['boolean', 'object']: :param rounded: See description |VCard_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param target: Designates the target attribute. This should only be applied when using the **href** prop. :type string: :param tile: Removes the component's **border-radius**. :type boolean: :param to: See description |VCard_vuetify_link|. :type ['string', 'object']: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-card", children, **kwargs) self._attr_names += [ "active_class", "append", "color", "dark", "disabled", "elevation", "exact", "exact_active_class", "exact_path", "flat", "height", "hover", "href", "img", "light", "link", "loader_height", "loading", "max_height", "max_width", "min_height", "min_width", "nuxt", "outlined", "raised", "replace", "ripple", "rounded", "shaped", "tag", "target", "tile", "to", "width", ] self._event_names += [ # click, #Implemented in AbstractElement parent class ] class VCardActions(AbstractElement): """ Vuetify's VCardActions component. See more info and examples |VCardActions_vuetify_link|. .. |VCardActions_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-card-actions" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-card-actions", children, **kwargs) class VCardSubtitle(AbstractElement): """ Vuetify's VCardSubtitle component. See more info and examples |VCardSubtitle_vuetify_link|. .. |VCardSubtitle_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-card-subtitle" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-card-subtitle", children, **kwargs) class VCardText(AbstractElement): """ Vuetify's VCardText component. See more info and examples |VCardText_vuetify_link|. .. |VCardText_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-card-text" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-card-text", children, **kwargs) class VCardTitle(AbstractElement): """ Vuetify's VCardTitle component. See more info and examples |VCardTitle_vuetify_link|. .. |VCardTitle_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-card-title" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-card-title", children, **kwargs) class VCarousel(AbstractElement): """ Vuetify's VCarousel component. See more info and examples |VCarousel_vuetify_link|. .. |VCarousel_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-carousel" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param continuous: Determines whether carousel is continuous :type boolean: :param cycle: Determines if the carousel should cycle through images. :type boolean: :param dark: See description |VCarousel_vuetify_link|. :type boolean: :param delimiter_icon: Sets icon for carousel delimiter :type string: :param height: Sets the height for the component :type ['number', 'string']: :param hide_delimiter_background: Hides the bottom delimiter background. :type boolean: :param hide_delimiters: Hides the carousel's bottom delimiters. :type boolean: :param interval: The duration between image cycles. Requires the **cycle** prop. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param next_icon: The displayed icon for forcing pagination to the next item. :type ['boolean', 'string']: :param prev_icon: The displayed icon for forcing pagination to the previous item. :type ['boolean', 'string']: :param progress: Displays a carousel progress bar. Requires the **cycle** prop and **interval**. :type boolean: :param progress_color: Applies specified color to progress bar. :type string: :param reverse: Reverse the normal transition direction. :type boolean: :param show_arrows: Displays arrows for next/previous navigation. :type boolean: :param show_arrows_on_hover: Displays navigation arrows only when the carousel is hovered over. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param touch: Provide a custom **left** and **right** function when swiped left or right. :type object: :param touchless: Disable touch support. :type boolean: :param value: The designated model value for the component. :type any: :param vertical: Uses a vertical transition when changing windows. :type boolean: :param vertical_delimiters: Displays carousel delimiters vertically. :type string: Events :param change: Emitted when the component value is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-carousel", children, **kwargs) self._attr_names += [ "active_class", "continuous", "cycle", "dark", "delimiter_icon", "height", "hide_delimiter_background", "hide_delimiters", "interval", "light", "mandatory", "max", "multiple", "next_icon", "prev_icon", "progress", "progress_color", "reverse", "show_arrows", "show_arrows_on_hover", "tag", "touch", "touchless", "value", "vertical", "vertical_delimiters", ] self._event_names += [ "change", ] class VCarouselItem(AbstractElement): """ Vuetify's VCarouselItem component. See more info and examples |VCarouselItem_vuetify_link|. .. |VCarouselItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-carousel-item" target="_blank">here</a> :param active_class: See description |VCarouselItem_vuetify_link|. :type string: :param append: See description |VCarouselItem_vuetify_link|. :type boolean: :param disabled: Removes the ability to click or target the component. :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param exact: See description |VCarouselItem_vuetify_link|. :type boolean: :param exact_active_class: See description |VCarouselItem_vuetify_link|. :type string: :param exact_path: See description |VCarouselItem_vuetify_link|. :type boolean: :param href: Designates the component as anchor and applies the **href** attribute. :type ['string', 'object']: :param link: Designates that the component is a link. This is automatic when using the **href** or **to** prop. :type boolean: :param nuxt: See description |VCarouselItem_vuetify_link|. :type boolean: :param replace: See description |VCarouselItem_vuetify_link|. :type boolean: :param reverse_transition: Sets the reverse transition :type ['boolean', 'string']: :param ripple: See description |VCarouselItem_vuetify_link|. :type ['boolean', 'object']: :param tag: Specify a custom tag used on the root element. :type string: :param target: Designates the target attribute. This should only be applied when using the **href** prop. :type string: :param to: See description |VCarouselItem_vuetify_link|. :type ['string', 'object']: :param transition: See description |VCarouselItem_vuetify_link|. :type ['boolean', 'string']: :param value: The value used when the component is selected in a group. If not provided, the index will be used. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-carousel-item", children, **kwargs) self._attr_names += [ "active_class", "append", "disabled", "eager", "exact", "exact_active_class", "exact_path", "href", "link", "nuxt", "replace", "reverse_transition", "ripple", "tag", "target", "to", "transition", "value", ] class VCheckbox(AbstractElement): """ Vuetify's VCheckbox component. See more info and examples |VCheckbox_vuetify_link|. .. |VCheckbox_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-checkbox" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param background_color: Changes the background-color of the input :type string: :param color: See description |VCheckbox_vuetify_link|. :type string: :param dark: See description |VCheckbox_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param false_value: Sets value for falsy state :type any: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param indeterminate: Sets an indeterminate state for the checkbox :type boolean: :param indeterminate_icon: The icon used when in an indeterminate state :type string: :param input_value: The **v-model** bound value :type any: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Changes expected model to an array :type boolean: :param off_icon: The icon used when inactive :type string: :param on_icon: The icon used when active :type string: :param persistent_hint: Forces hint to always be visible :type boolean: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param ripple: See description |VCheckbox_vuetify_link|. :type ['boolean', 'object']: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param true_value: Sets value for truthy state :type any: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param value_comparator: Apply a custom value comparator function :type function: Events :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_prepend: Emitted when prepended icon is clicked :param update_error: The `error.sync` event :param update_indeterminate: The **indeterminate.sync** event. """ def __init__(self, children=None, **kwargs): super().__init__("v-checkbox", children, **kwargs) self._attr_names += [ "append_icon", "background_color", "color", "dark", "dense", "disabled", "error", "error_count", "error_messages", "false_value", "hide_details", "hint", "id", "indeterminate", "indeterminate_icon", "input_value", "label", "light", "messages", "multiple", "off_icon", "on_icon", "persistent_hint", "prepend_icon", "readonly", "ripple", "rules", "success", "success_messages", "true_value", "validate_on_blur", "value", "value_comparator", # JS functions unimplemented ] self._event_names += [ "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_prepend", "click:prepend"), # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ("update_indeterminate", "update:indeterminate"), ] class VSimpleCheckbox(AbstractElement): """ Vuetify's VSimpleCheckbox component. See more info and examples |VSimpleCheckbox_vuetify_link|. .. |VSimpleCheckbox_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-simple-checkbox" target="_blank">here</a> :param color: See description |VSimpleCheckbox_vuetify_link|. :type string: :param dark: See description |VSimpleCheckbox_vuetify_link|. :type boolean: :param disabled: Disables simple checkbox. :type boolean: :param indeterminate: Sets an indeterminate state for the simple checkbox. :type boolean: :param indeterminate_icon: The icon used when in an indeterminate state. :type string: :param light: Applies the light theme variant to the component. :type boolean: :param off_icon: The icon used when inactive. :type string: :param on_icon: The icon used when active. :type string: :param ripple: See description |VSimpleCheckbox_vuetify_link|. :type boolean: :param value: A boolean value that represents whether the simple checkbox is checked. :type boolean: Events :param input: The updated bound model """ def __init__(self, children=None, **kwargs): super().__init__("v-simple-checkbox", children, **kwargs) self._attr_names += [ "color", "dark", "disabled", "indeterminate", "indeterminate_icon", "light", "off_icon", "on_icon", "ripple", "value", ] self._event_names += [ "input", ] class VChip(AbstractElement): """ Vuetify's VChip component. See more info and examples |VChip_vuetify_link|. .. |VChip_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-chip" target="_blank">here</a> :param active: Determines whether the chip is visible or not. :type boolean: :param active_class: See description |VChip_vuetify_link|. :type string: :param append: See description |VChip_vuetify_link|. :type boolean: :param close: Adds remove button :type boolean: :param close_icon: Change the default icon used for **close** chips :type string: :param close_label: See description |VChip_vuetify_link|. :type string: :param color: See description |VChip_vuetify_link|. :type string: :param dark: See description |VChip_vuetify_link|. :type boolean: :param disabled: Disables the chip, making it un-selectable :type boolean: :param draggable: Makes the chip draggable :type boolean: :param exact: See description |VChip_vuetify_link|. :type boolean: :param exact_active_class: See description |VChip_vuetify_link|. :type string: :param exact_path: See description |VChip_vuetify_link|. :type boolean: :param filter: Displays a selection icon when selected :type boolean: :param filter_icon: Change the default icon used for **filter** chips :type string: :param href: Designates the component as anchor and applies the **href** attribute. :type ['string', 'object']: :param input_value: Controls the **active** state of the item. This is typically used to highlight the component. :type any: :param label: Removes circle edges :type boolean: :param large: Makes the component large. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param link: Explicitly define the chip as a link :type boolean: :param nuxt: See description |VChip_vuetify_link|. :type boolean: :param outlined: Removes background and applies border and text color :type boolean: :param pill: Remove `v-avatar` padding :type boolean: :param replace: See description |VChip_vuetify_link|. :type boolean: :param ripple: See description |VChip_vuetify_link|. :type ['boolean', 'object']: :param small: Makes the component small. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param target: Designates the target attribute. This should only be applied when using the **href** prop. :type string: :param text_color: Applies a specified color to the control text :type string: :param to: See description |VChip_vuetify_link|. :type ['string', 'object']: :param value: See description |VChip_vuetify_link|. :type any: :param x_large: Makes the component extra large. :type boolean: :param x_small: Makes the component extra small. :type boolean: Events :param click_close: Emitted when close icon is clicked :param input: The updated bound model :param update_active: Emitted when close icon is clicked, sets active to `false` """ def __init__(self, children=None, **kwargs): super().__init__("v-chip", children, **kwargs) self._attr_names += [ "active", "active_class", "append", "close", "close_icon", "close_label", "color", "dark", "disabled", "draggable", "exact", "exact_active_class", "exact_path", "filter", "filter_icon", "href", "input_value", "label", "large", "light", "link", "nuxt", "outlined", "pill", "replace", "ripple", "small", "tag", "target", "text_color", "to", "value", "x_large", "x_small", ] self._event_names += [ # click, #Implemented in AbstractElement parent class ("click_close", "click:close"), "input", ("update_active", "update:active"), ] class VChipGroup(AbstractElement): """ Vuetify's VChipGroup component. See more info and examples |VChipGroup_vuetify_link|. .. |VChipGroup_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-chip-group" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param center_active: Forces the selected chip to be centered :type boolean: :param color: See description |VChipGroup_vuetify_link|. :type string: :param column: Remove horizontal pagination and wrap items as needed :type boolean: :param dark: See description |VChipGroup_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param mobile_breakpoint: Sets the designated mobile breakpoint for the component. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param next_icon: Specify the icon to use for the next icon :type string: :param prev_icon: Specify the icon to use for the prev icon :type string: :param show_arrows: Force the display of the pagination arrows :type ['boolean', 'string']: :param tag: Specify a custom tag used on the root element. :type string: :param value: The designated model value for the component. :type any: Events :param change: Emitted when the component value is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-chip-group", children, **kwargs) self._attr_names += [ "active_class", "center_active", "color", "column", "dark", "light", "mandatory", "max", "mobile_breakpoint", "multiple", "next_icon", "prev_icon", "show_arrows", "tag", "value", ] self._event_names += [ "change", ] class VColorPicker(AbstractElement): """ Vuetify's VColorPicker component. See more info and examples |VColorPicker_vuetify_link|. .. |VColorPicker_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-color-picker" target="_blank">here</a> :param canvas_height: Height of canvas :type ['string', 'number']: :param dark: See description |VColorPicker_vuetify_link|. :type boolean: :param disabled: Disables picker :type boolean: :param dot_size: Changes the size of the selection dot on the canvas :type ['number', 'string']: :param elevation: See description |VColorPicker_vuetify_link|. :type ['number', 'string']: :param flat: Removes elevation :type boolean: :param hide_canvas: Hides canvas :type boolean: :param hide_inputs: Hides inputs :type boolean: :param hide_mode_switch: Hides mode switch :type boolean: :param hide_sliders: Hides sliders :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mode: Sets mode of inputs. Available modes are 'rgba', 'hsla', and 'hexa'. Can be synced with the `.sync` modifier. :type string: :param show_swatches: Displays color swatches :type boolean: :param swatches: Sets the available color swatches to select from - This prop only accepts rgba hex strings :type array: :param swatches_max_height: Sets the maximum height of the swatches section :type ['number', 'string']: :param value: Current color. This can be either a string representing a hex color, or an object representing a RGBA, HSLA, or HSVA value :type ['object', 'string']: :param width: Sets the width of the color picker :type ['number', 'string']: Events :param input: Selected color. Depending on what you passed to the `value` prop this is either a string or an object :param update_color: Selected color. This is the internal representation of the color, containing all values. :param update_mode: Selected mode """ def __init__(self, children=None, **kwargs): super().__init__("v-color-picker", children, **kwargs) self._attr_names += [ "canvas_height", "dark", "disabled", "dot_size", "elevation", "flat", "hide_canvas", "hide_inputs", "hide_mode_switch", "hide_sliders", "light", "mode", "show_swatches", "swatches", "swatches_max_height", "value", "width", ] self._event_names += [ "input", ("update_color", "update:color"), ("update_mode", "update:mode"), ] class VContent(AbstractElement): """ Vuetify's VContent component. See more info and examples |VContent_vuetify_link|. .. |VContent_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-content" target="_blank">here</a> :param tag: Specify a custom tag used on the root element. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-content", children, **kwargs) self._attr_names += [ "tag", ] class VCombobox(AbstractElement): """ Vuetify's VCombobox component. See more info and examples |VCombobox_vuetify_link|. .. |VCombobox_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-combobox" target="_blank">here</a> :param allow_overflow: Allow the menu to overflow off the screen :type boolean: :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param append_outer_icon: Appends an icon to the outside the component's input, uses same syntax as `v-icon` :type string: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param auto_select_first: When searching, will always highlight the first option :type boolean: :param autofocus: Enables autofocus :type boolean: :param background_color: Changes the background-color of the input :type string: :param cache_items: Keeps a local _unique_ copy of all items that have been passed through the **items** prop. :type boolean: :param chips: Changes display of selections to chips :type boolean: :param clear_icon: Applied when using **clearable** and the input is dirty :type string: :param clearable: Add input clear functionality, default icon is Material Design Icons **mdi-clear** :type boolean: :param color: See description |VCombobox_vuetify_link|. :type string: :param counter: Creates counter for input length; if no number is specified, it defaults to 25. Does not apply any validation. :type ['boolean', 'number', 'string']: :param counter_value: :type function: :param dark: See description |VCombobox_vuetify_link|. :type boolean: :param deletable_chips: Adds a remove icon to selected chips :type boolean: :param delimiters: Accepts an array of strings that will trigger a new tag when typing. Does not replace the normal Tab and Enter keys. :type array: :param dense: Reduces the input height :type boolean: :param disable_lookup: Disables keyboard lookup :type boolean: :param disabled: Disables the input :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param filled: Applies the alternate filled input style :type boolean: :param filter: See description |VCombobox_vuetify_link|. :type function: :param flat: Removes elevation (shadow) added to element when using the **solo** or **solo-inverted** props :type boolean: :param full_width: Designates input type as full-width :type boolean: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hide_no_data: Hides the menu when there are no options to show. Useful for preventing the menu from opening before results are fetched asynchronously. Also has the effect of opening the menu when the `items` array changes if not already open. :type boolean: :param hide_selected: Do not display in the select menu items that are already selected :type boolean: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param item_color: Sets color of selected items :type string: :param item_disabled: Set property of **items**'s disabled value :type ['string', 'array', 'function']: :param item_text: Set property of **items**'s text value :type ['string', 'array', 'function']: :param item_value: See description |VCombobox_vuetify_link|. :type ['string', 'array', 'function']: :param items: Can be an array of objects or array of strings. When using objects, will look for a text, value and disabled keys. This can be changed using the **item-text**, **item-value** and **item-disabled** props. Objects that have a **header** or **divider** property are considered special cases and generate a list header or divider; these items are not selectable. :type array: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param menu_props: Pass props through to the `v-menu` component. Accepts either a string for boolean props `menu-props="auto, overflowY"`, or an object `:menu-props="{ auto: true, overflowY: true }"` :type ['string', 'array', 'object']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Changes select to multiple. Accepts array for value :type boolean: :param no_data_text: Display text when there is no data :type string: :param no_filter: Do not apply filtering when searching. Useful when data is being filtered server side :type boolean: :param open_on_clear: When using the **clearable** prop, once cleared, the select menu will either open or stay open, depending on the current state :type boolean: :param outlined: Applies the outlined style to the input :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param persistent_placeholder: Forces placeholder to always be visible :type boolean: :param placeholder: Sets the input's placeholder text :type string: :param prefix: Displays prefix text :type string: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param prepend_inner_icon: Prepends an icon inside the component's input, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param return_object: Changes the selection behavior to return the object directly rather than the value specified with **item-value** :type boolean: :param reverse: Reverses the input orientation :type boolean: :param rounded: Adds a border radius to the input :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param search_input: Search value. Can be used with `.sync` modifier. :type string: :param shaped: Round if `outlined` and increase `border-radius` if `filled`. Must be used with either `outlined` or `filled` :type boolean: :param single_line: Label does not move on focus/dirty :type boolean: :param small_chips: Changes display of selections to chips with the **small** property :type boolean: :param solo: Changes the style of the input :type boolean: :param solo_inverted: Reduces element opacity until focused :type boolean: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param suffix: Displays suffix text :type string: :param type: Sets input type :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param value_comparator: See description |VCombobox_vuetify_link|. :type function: Events :param blur: Emitted when the input is blurred :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_append_outer: Emitted when appended outer icon is clicked :param click_clear: Emitted when clearable icon clicked :param click_prepend: Emitted when prepended icon is clicked :param click_prepend_inner: Emitted when prepended inner icon is clicked :param focus: Emitted when component is focused :param input: The updated bound model :param keydown: Emitted when **any** key is pressed :param update_error: The `error.sync` event :param update_list_index: Emitted when menu item is selected using keyboard arrows :param update_search_input: The `search-input.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-combobox", children, **kwargs) self._attr_names += [ "allow_overflow", "append_icon", "append_outer_icon", "attach", "auto_select_first", "autofocus", "background_color", "cache_items", "chips", "clear_icon", "clearable", "color", "counter", "counter_value", # JS functions unimplemented "dark", "deletable_chips", "delimiters", "dense", "disable_lookup", "disabled", "eager", "error", "error_count", "error_messages", "filled", "filter", # JS functions unimplemented "flat", "full_width", "height", "hide_details", "hide_no_data", "hide_selected", "hint", "id", "item_color", "item_disabled", # JS functions unimplemented "item_text", # JS functions unimplemented "item_value", # JS functions unimplemented "items", "label", "light", "loader_height", "loading", "menu_props", "messages", "multiple", "no_data_text", "no_filter", "open_on_clear", "outlined", "persistent_hint", "persistent_placeholder", "placeholder", "prefix", "prepend_icon", "prepend_inner_icon", "readonly", "return_object", "reverse", "rounded", "rules", "search_input", "shaped", "single_line", "small_chips", "solo", "solo_inverted", "success", "success_messages", "suffix", "type", "validate_on_blur", "value", "value_comparator", # JS functions unimplemented ] self._event_names += [ "blur", "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_append_outer", "click:append-outer"), ("click_clear", "click:clear"), ("click_prepend", "click:prepend"), ("click_prepend_inner", "click:prepend-inner"), "focus", "input", "keydown", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ("update_list_index", "update:list-index"), ("update_search_input", "update:search-input"), ] class VDataIterator(AbstractElement): """ Vuetify's VDataIterator component. See more info and examples |VDataIterator_vuetify_link|. .. |VDataIterator_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-data-iterator" target="_blank">here</a> :param checkbox_color: :type string: :param custom_filter: Function to filter items :type function: :param custom_group: Function used to group items :type function: :param custom_sort: Function used to sort items :type function: :param dark: See description |VDataIterator_vuetify_link|. :type boolean: :param disable_filtering: Disables filtering completely :type boolean: :param disable_pagination: Disables pagination completely :type boolean: :param disable_sort: Disables sorting completely :type boolean: :param expanded: Array of expanded items. Can be used with `.sync` modifier :type array: :param footer_props: See description |VDataIterator_vuetify_link|. :type object: :param group_by: Changes which item property should be used for grouping items. Currently only supports a single grouping in the format: `group` or `['group']`. When using an array, only the first element is considered. Can be used with `.sync` modifier :type ['string', 'array']: :param group_desc: Changes which direction grouping is done. Can be used with `.sync` modifier :type ['boolean', 'array']: :param hide_default_footer: Hides default footer :type boolean: :param item_key: The property on each item that is used as a unique key :type string: :param items: The array of items to display :type array: :param items_per_page: Changes how many items per page should be visible. Can be used with `.sync` modifier. Setting this prop to `-1` will display all items on the page :type number: :param light: Applies the light theme variant to the component. :type boolean: :param loading: If `true` and no items are provided, then a loading text will be shown :type ['boolean', 'string']: :param loading_text: Text shown when `loading` is true and no items are provided :type string: :param locale: See description |VDataIterator_vuetify_link|. :type string: :param mobile_breakpoint: Used to set when to toggle between regular table and mobile view :type ['number', 'string']: :param multi_sort: If `true` then one can sort on multiple properties :type boolean: :param must_sort: If `true` then one can not disable sorting, it will always switch between ascending and descending :type boolean: :param no_data_text: Text shown when no items are provided to the component :type string: :param no_results_text: Text shown when `search` prop is used and there are no results :type string: :param options: :type DataOptions: :param page: :type number: :param search: Text input used to filter items :type string: :param selectable_key: The property on each item that is used to determine if it is selectable or not :type string: :param server_items_length: Used only when data is provided by a server. Should be set to the total amount of items available on server so that pagination works correctly :type number: :param single_expand: Changes expansion mode to single expand :type boolean: :param single_select: Changes selection mode to single select :type boolean: :param sort_by: Changes which item property (or properties) should be used for sort order. Can be used with `.sync` modifier :type ['string', 'array']: :param sort_desc: Changes which direction sorting is done. Can be used with `.sync` modifier :type ['boolean', 'array']: :param value: Used for controlling selected rows :type array: Events :param current_items: :param input: Array of selected items :param item_expanded: Event emitted when an item is expanded or closed :param item_selected: Event emitted when an item is selected or deselected :param page_count: :param pagination: :param toggle_select_all: :param update_expanded: The `.sync` event for `expanded` prop :param update_group_by: :param update_group_desc: :param update_items_per_page: :param update_multi_sort: :param update_must_sort: :param update_options: :param update_page: :param update_sort_by: :param update_sort_desc: """ def __init__(self, children=None, **kwargs): super().__init__("v-data-iterator", children, **kwargs) self._attr_names += [ "checkbox_color", "custom_filter", # JS functions unimplemented "custom_group", # JS functions unimplemented "custom_sort", # JS functions unimplemented "dark", "disable_filtering", "disable_pagination", "disable_sort", "expanded", "footer_props", "group_by", "group_desc", "hide_default_footer", "item_key", "items", "items_per_page", "light", "loading", "loading_text", "locale", "mobile_breakpoint", "multi_sort", "must_sort", "no_data_text", "no_results_text", "options", "page", "search", "selectable_key", "server_items_length", "single_expand", "single_select", "sort_by", "sort_desc", "value", ] self._event_names += [ ("current_items", "current-items"), "input", ("item_expanded", "item-expanded"), ("item_selected", "item-selected"), ("page_count", "page-count"), "pagination", ("toggle_select_all", "toggle-select-all"), ("update_expanded", "update:expanded"), ("update_group_by", "update:group-by"), ("update_group_desc", "update:group-desc"), ("update_items_per_page", "update:items-per-page"), ("update_multi_sort", "update:multi-sort"), ("update_must_sort", "update:must-sort"), ("update_options", "update:options"), ("update_page", "update:page"), ("update_sort_by", "update:sort-by"), ("update_sort_desc", "update:sort-desc"), ] class VDataFooter(AbstractElement): """ Vuetify's VDataFooter component. See more info and examples |VDataFooter_vuetify_link|. .. |VDataFooter_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-data-footer" target="_blank">here</a> :param disable_items_per_page: Disables items-per-page dropdown :type boolean: :param disable_pagination: Disables pagination buttons :type boolean: :param first_icon: First icon :type string: :param items_per_page_all_text: Text for 'All' option in items-per-page dropdown :type string: :param items_per_page_options: Array of options to show in the items-per-page dropdown :type array: :param items_per_page_text: Text for items-per-page dropdown :type string: :param last_icon: Last icon :type string: :param next_icon: Next icon :type string: :param options: DataOptions :type object: :param page_text: :type string: :param pagination: DataPagination :type object: :param prev_icon: Previous icon :type string: :param show_current_page: Show current page number between prev/next icons :type boolean: :param show_first_last_page: Show first/last icons :type boolean: Events :param update_options: The `.sync` event for `options` prop """ def __init__(self, children=None, **kwargs): super().__init__("v-data-footer", children, **kwargs) self._attr_names += [ "disable_items_per_page", "disable_pagination", "first_icon", "items_per_page_all_text", "items_per_page_options", "items_per_page_text", "last_icon", "next_icon", "options", "page_text", "pagination", "prev_icon", "show_current_page", "show_first_last_page", ] self._event_names += [ ("update_options", "update:options"), ] class VDataTable(AbstractElement): """ Vuetify's VDataTable component. See more info and examples |VDataTable_vuetify_link|. .. |VDataTable_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-data-table" target="_blank">here</a> :param calculate_widths: Enables calculation of column widths. `widths` property will be available in select scoped slots :type boolean: :param caption: Set the caption (using `<caption>`) :type string: :param checkbox_color: Set the color of the checkboxes (showSelect must be used) :type string: :param custom_filter: Function to filter items :type function: :param custom_group: Function used to group items :type function: :param custom_sort: Function used to sort items :type function: :param dark: See description |VDataTable_vuetify_link|. :type boolean: :param dense: Decreases the height of rows :type boolean: :param disable_filtering: Disables filtering completely :type boolean: :param disable_pagination: Disables pagination completely :type boolean: :param disable_sort: Disables sorting completely :type boolean: :param expand_icon: Icon used for expand toggle button. :type string: :param expanded: Array of expanded items. Can be used with `.sync` modifier :type array: :param fixed_header: Fixed header to top of table. **NOTE:** Does not work in IE11 :type boolean: :param footer_props: See description |VDataTable_vuetify_link|. :type object: :param group_by: Changes which item property should be used for grouping items. Currently only supports a single grouping in the format: `group` or `['group']`. When using an array, only the first element is considered. Can be used with `.sync` modifier :type ['string', 'array']: :param group_desc: Changes which direction grouping is done. Can be used with `.sync` modifier :type ['boolean', 'array']: :param header_props: See description |VDataTable_vuetify_link|. :type object: :param headers: An array of objects that each describe a header column. See the example below for a definition of all properties :type DataTableHeader[]: :param headers_length: Can be used in combination with `hide-default-header` to specify the number of columns in the table to allow expansion rows and loading bar to function properly :type number: :param height: Set an explicit height of table :type ['number', 'string']: :param hide_default_footer: Hides default footer :type boolean: :param hide_default_header: Hide the default headers :type boolean: :param item_class: Property on supplied `items` that contains item's row class or function that takes an item as an argument and returns the class of corresponding row :type ['string', 'function']: :param item_key: The property on each item that is used as a unique key :type string: :param items: The array of items to display :type array: :param items_per_page: Changes how many items per page should be visible. Can be used with `.sync` modifier. Setting this prop to `-1` will display all items on the page :type number: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: If `true` and no items are provided, then a loading text will be shown :type ['boolean', 'string']: :param loading_text: Text shown when `loading` is true and no items are provided :type string: :param locale: See description |VDataTable_vuetify_link|. :type string: :param mobile_breakpoint: Used to set when to toggle between regular table and mobile view :type ['number', 'string']: :param multi_sort: If `true` then one can sort on multiple properties :type boolean: :param must_sort: If `true` then one can not disable sorting, it will always switch between ascending and descending :type boolean: :param no_data_text: Text shown when no items are provided to the component :type string: :param no_results_text: Text shown when `search` prop is used and there are no results :type string: :param options: :type DataOptions: :param page: :type number: :param search: Text input used to filter items :type string: :param selectable_key: The property on each item that is used to determine if it is selectable or not :type string: :param server_items_length: Used only when data is provided by a server. Should be set to the total amount of items available on server so that pagination works correctly :type number: :param show_expand: Shows the expand toggle in default rows :type boolean: :param show_group_by: Shows the group by toggle in the header and enables grouped rows :type boolean: :param show_select: Shows the select checkboxes in both the header and rows (if using default rows) :type boolean: :param single_expand: Changes expansion mode to single expand :type boolean: :param single_select: Changes selection mode to single select :type boolean: :param sort_by: Changes which item property (or properties) should be used for sort order. Can be used with `.sync` modifier :type ['string', 'array']: :param sort_desc: Changes which direction sorting is done. Can be used with `.sync` modifier :type ['boolean', 'array']: :param value: Used for controlling selected rows :type array: Events :param click_row: Emits when a table row is clicked. This event provides 2 arguments: the first is the item data that was clicked and the second is the other related data provided by the `item` slot. **NOTE:** will not emit when table rows are defined through a slot such as `item` or `body`. :param contextmenu_row: Emits when a table row is right-clicked. The item for the row is included. **NOTE:** will not emit when table rows are defined through a slot such as `item` or `body`. :param current_items: :param dblclick_row: Emits when a table row is double-clicked. The item for the row is included. **NOTE:** will not emit when table rows are defined through a slot such as `item` or `body`. :param input: Array of selected items :param item_expanded: Event emitted when an item is expanded or closed :param item_selected: Event emitted when an item is selected or deselected :param page_count: :param pagination: :param toggle_select_all: :param update_expanded: The `.sync` event for `expanded` prop :param update_group_by: :param update_group_desc: :param update_items_per_page: :param update_multi_sort: :param update_must_sort: :param update_options: :param update_page: :param update_sort_by: :param update_sort_desc: """ def __init__(self, children=None, **kwargs): super().__init__("v-data-table", children, **kwargs) self.ttsSensitive() self._attr_names += [ "calculate_widths", "caption", "checkbox_color", "custom_filter", # JS functions unimplemented "custom_group", # JS functions unimplemented "custom_sort", # JS functions unimplemented "dark", "dense", "disable_filtering", "disable_pagination", "disable_sort", "expand_icon", "expanded", "fixed_header", "footer_props", "group_by", "group_desc", "header_props", "headers", "headers_length", "height", "hide_default_footer", "hide_default_header", "item_class", # JS functions unimplemented "item_key", "items", "items_per_page", "light", "loader_height", "loading", "loading_text", "locale", "mobile_breakpoint", "multi_sort", "must_sort", "no_data_text", "no_results_text", "options", "page", "search", "selectable_key", "server_items_length", "show_expand", "show_group_by", "show_select", "single_expand", "single_select", "sort_by", "sort_desc", "value", ] self._event_names += [ ("click_row", "click:row"), ("contextmenu_row", "contextmenu:row"), ("current_items", "current-items"), ("dblclick_row", "dblclick:row"), "input", ("item_expanded", "item-expanded"), ("item_selected", "item-selected"), ("page_count", "page-count"), "pagination", ("toggle_select_all", "toggle-select-all"), ("update_expanded", "update:expanded"), ("update_group_by", "update:group-by"), ("update_group_desc", "update:group-desc"), ("update_items_per_page", "update:items-per-page"), ("update_multi_sort", "update:multi-sort"), ("update_must_sort", "update:must-sort"), ("update_options", "update:options"), ("update_page", "update:page"), ("update_sort_by", "update:sort-by"), ("update_sort_desc", "update:sort-desc"), ] class VEditDialog(AbstractElement): """ Vuetify's VEditDialog component. See more info and examples |VEditDialog_vuetify_link|. .. |VEditDialog_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-edit-dialog" target="_blank">here</a> :param cancel_text: Sets the default text for the cancel button when using the **large** prop :type any: :param dark: See description |VEditDialog_vuetify_link|. :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param large: Attaches a submit and cancel button to the dialog :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param persistent: Clicking outside or pressing **esc** key will not dismiss the dialog :type boolean: :param return_value: :type any: :param save_text: Sets the default text for the save button when using the **large** prop :type any: :param transition: See description |VEditDialog_vuetify_link|. :type string: Events :param cancel: Emits when editing is canceled :param close: Emits when edit-dialog close button is pressed :param open: Emits when editing is opened :param save: Emits when edit-dialog save button is pressed """ def __init__(self, children=None, **kwargs): super().__init__("v-edit-dialog", children, **kwargs) self._attr_names += [ "cancel_text", "dark", "eager", "large", "light", "persistent", "return_value", "save_text", "transition", ] self._event_names += [ "cancel", "close", "open", "save", ] class VDataTableHeader(AbstractElement): """ Vuetify's VDataTableHeader component. See more info and examples |VDataTableHeader_vuetify_link|. .. |VDataTableHeader_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-data-table-header" target="_blank">here</a> :param checkbox_color: :type string: :param disable_sort: Toggles rendering of sort button :type boolean: :param every_item: Indicates if all items in table are selected :type boolean: :param headers: Array of header items to display :type array: :param mobile: Renders mobile view of headers :type boolean: :param options: Options object. Identical to the one on `v-data-table` :type object: :param show_group_by: Shows group by button :type boolean: :param single_select: Toggles rendering of select-all checkbox :type boolean: :param some_items: Indicates if one or more items in table are selected :type boolean: :param sort_by_text: Sets the label text used by the default sort-by selector when `v-data-table` is rendering the mobile view :type string: :param sort_icon: Icon used for sort button :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-data-table-header", children, **kwargs) self._attr_names += [ "checkbox_color", "disable_sort", "every_item", "headers", "mobile", "options", "show_group_by", "single_select", "some_items", "sort_by_text", "sort_icon", ] class VSimpleTable(AbstractElement): """ Vuetify's VSimpleTable component. See more info and examples |VSimpleTable_vuetify_link|. .. |VSimpleTable_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-simple-table" target="_blank">here</a> :param dark: See description |VSimpleTable_vuetify_link|. :type boolean: :param dense: Decreases paddings to render a dense table :type boolean: :param fixed_header: Sets table header to fixed mode :type boolean: :param height: Sets the height for the component :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-simple-table", children, **kwargs) self._attr_names += [ "dark", "dense", "fixed_header", "height", "light", ] class VDatePicker(AbstractElement): """ Vuetify's VDatePicker component. See more info and examples |VDatePicker_vuetify_link|. .. |VDatePicker_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-date-picker" target="_blank">here</a> :param active_picker: Determines which picker in the date or month picker is being displayed. Allowed values: `'DATE'`, `'MONTH'`, `'YEAR'` :type string: :param allowed_dates: Restricts which dates can be selected :type function: :param color: See description |VDatePicker_vuetify_link|. :type string: :param dark: See description |VDatePicker_vuetify_link|. :type boolean: :param day_format: Allows you to customize the format of the day string that appears in the date table. Called with date (ISO 8601 **date** string) arguments. :type function: :param disabled: Disables interaction with the picker :type boolean: :param elevation: See description |VDatePicker_vuetify_link|. :type ['number', 'string']: :param event_color: Sets the color for event dot. It can be string (all events will have the same color) or `object` where attribute is the event date and value is boolean/color/array of colors for specified date or `function` taking date as a parameter and returning boolean/color/array of colors for that date :type ['array', 'function', 'object', 'string']: :param events: Array of dates or object defining events or colors or function returning boolean/color/array of colors :type ['array', 'function', 'object']: :param first_day_of_week: Sets the first day of the week, starting with 0 for Sunday. :type ['string', 'number']: :param flat: Removes elevation :type boolean: :param full_width: Forces 100% width :type boolean: :param header_color: Defines the header color. If not specified it will use the color defined by <code>color</code> prop or the default picker color :type string: :param header_date_format: Allows you to customize the format of the month string that appears in the header of the calendar. Called with date (ISO 8601 **date** string) arguments. :type function: :param landscape: Orients picker horizontal :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param locale: Sets the locale. Accepts a string with a BCP 47 language tag. :type string: :param locale_first_day_of_year: Sets the day that determines the first week of the year, starting with 0 for **Sunday**. For ISO 8601 this should be 4. :type ['string', 'number']: :param max: Maximum allowed date/month (ISO 8601 format) :type string: :param min: Minimum allowed date/month (ISO 8601 format) :type string: :param month_format: Formatting function used for displaying months in the months table. Called with date (ISO 8601 **date** string) arguments. :type function: :param multiple: Allow the selection of multiple dates :type boolean: :param next_icon: Sets the icon for next month/year button :type string: :param next_month_aria_label: :type string: :param next_year_aria_label: :type string: :param no_title: Hide the picker title :type boolean: :param picker_date: Displayed year/month :type string: :param prev_icon: Sets the icon for previous month/year button :type string: :param prev_month_aria_label: :type string: :param prev_year_aria_label: :type string: :param range: Allow the selection of date range :type boolean: :param reactive: Updates the picker model when changing months/years automatically :type boolean: :param readonly: Makes the picker readonly (doesn't allow to select new date) :type boolean: :param scrollable: Allows changing displayed month with mouse scroll :type boolean: :param selected_items_text: See description |VDatePicker_vuetify_link|. :type string: :param show_adjacent_months: Toggles visibility of days from previous and next months :type boolean: :param show_current: Toggles visibility of the current date/month outline or shows the provided date/month as a current :type ['boolean', 'string']: :param show_week: Toggles visibility of the week numbers in the body of the calendar :type boolean: :param title_date_format: Allows you to customize the format of the date string that appears in the title of the date picker. Called with date (ISO 8601 **date** string) arguments. :type function: :param type: Determines the type of the picker - `date` for date picker, `month` for month picker :type string: :param value: Date picker model (ISO 8601 format, YYYY-mm-dd or YYYY-mm) :type ['array', 'string']: :param weekday_format: Allows you to customize the format of the weekday string that appears in the body of the calendar. Called with date (ISO 8601 **date** string) arguments. :type function: :param width: Width of the picker :type ['number', 'string']: :param year_format: Allows you to customize the format of the year string that appears in the header of the calendar. Called with date (ISO 8601 **date** string) arguments. :type function: :param year_icon: Sets the icon in the year selection button :type string: Events :param change: Reactive date picker emits `input` even when any part of the date (year/month/day) changes, but `change` event is emitted only when the day (for date pickers) or month (for month pickers) changes. If `range` prop is set, date picker emits `change` when both [from, to] are selected. :param input: The updated bound model :param update_active_picker: The `.sync` event for `active-picker` prop :param update_picker_date: The `.sync` event for `picker-date` prop """ def __init__(self, children=None, **kwargs): super().__init__("v-date-picker", children, **kwargs) self._attr_names += [ "active_picker", "allowed_dates", # JS functions unimplemented "color", "dark", "day_format", # JS functions unimplemented "disabled", "elevation", "event_color", # JS functions unimplemented "events", # JS functions unimplemented "first_day_of_week", "flat", "full_width", "header_color", "header_date_format", # JS functions unimplemented "landscape", "light", "locale", "locale_first_day_of_year", "max", "min", "month_format", # JS functions unimplemented "multiple", "next_icon", "next_month_aria_label", "next_year_aria_label", "no_title", "picker_date", "prev_icon", "prev_month_aria_label", "prev_year_aria_label", "range", "reactive", "readonly", "scrollable", "selected_items_text", "show_adjacent_months", "show_current", "show_week", "title_date_format", # JS functions unimplemented "type", "value", "weekday_format", # JS functions unimplemented "width", "year_format", # JS functions unimplemented "year_icon", ] self._event_names += [ ("click_date", "click:date"), ("click_month", "click:month"), ("click_year", "click:year"), ("dblclick_date", "dblclick:date"), ("dblclick_month", "dblclick:month"), ("dblclick_year", "dblclick:year"), ("mousedown_date", "mousedown:date"), ("mousedown_month", "mousedown:month"), ("mousedown_year", "mousedown:year"), ("mouseenter_date", "mouseenter:date"), ("mouseenter_month", "mouseenter:month"), ("mouseenter_year", "mouseenter:year"), ("mouseleave_date", "mouseleave:date"), ("mouseleave_month", "mouseleave:month"), ("mouseleave_year", "mouseleave:year"), ("mousemove_date", "mousemove:date"), ("mousemove_month", "mousemove:month"), ("mousemove_year", "mousemove:year"), ("mouseover_date", "mouseover:date"), ("mouseover_month", "mouseover:month"), ("mouseover_year", "mouseover:year"), ("mouseout_date", "mouseout:date"), ("mouseout_month", "mouseout:month"), ("mouseout_year", "mouseout:year"), ("mouseup_date", "mouseup:date"), ("mouseup_month", "mouseup:month"), ("mouseup_year", "mouseup:year"), ("focus_date", "focus:date"), ("focus_month", "focus:month"), ("focus_year", "focus:year"), ("click_date", "click:date"), ("click_month", "click:month"), ("click_year", "click:year"), ("dblclick_date", "dblclick:date"), ("dblclick_month", "dblclick:month"), ("dblclick_year", "dblclick:year"), ("mousedown_date", "mousedown:date"), ("mousedown_month", "mousedown:month"), ("mousedown_year", "mousedown:year"), ("mouseenter_date", "mouseenter:date"), ("mouseenter_month", "mouseenter:month"), ("mouseenter_year", "mouseenter:year"), ("mouseleave_date", "mouseleave:date"), ("mouseleave_month", "mouseleave:month"), ("mouseleave_year", "mouseleave:year"), ("mousemove_date", "mousemove:date"), ("mousemove_month", "mousemove:month"), ("mousemove_year", "mousemove:year"), ("mouseover_date", "mouseover:date"), ("mouseover_month", "mouseover:month"), ("mouseover_year", "mouseover:year"), ("mouseout_date", "mouseout:date"), ("mouseout_month", "mouseout:month"), ("mouseout_year", "mouseout:year"), ("mouseup_date", "mouseup:date"), ("mouseup_month", "mouseup:month"), ("mouseup_year", "mouseup:year"), ("focus_date", "focus:date"), ("focus_month", "focus:month"), ("focus_year", "focus:year"), ("click_date", "click:date"), ("click_month", "click:month"), ("click_year", "click:year"), ("dblclick_date", "dblclick:date"), ("dblclick_month", "dblclick:month"), ("dblclick_year", "dblclick:year"), ("mousedown_date", "mousedown:date"), ("mousedown_month", "mousedown:month"), ("mousedown_year", "mousedown:year"), ("mouseenter_date", "mouseenter:date"), ("mouseenter_month", "mouseenter:month"), ("mouseenter_year", "mouseenter:year"), ("mouseleave_date", "mouseleave:date"), ("mouseleave_month", "mouseleave:month"), ("mouseleave_year", "mouseleave:year"), ("mousemove_date", "mousemove:date"), ("mousemove_month", "mousemove:month"), ("mousemove_year", "mousemove:year"), ("mouseover_date", "mouseover:date"), ("mouseover_month", "mouseover:month"), ("mouseover_year", "mouseover:year"), ("mouseout_date", "mouseout:date"), ("mouseout_month", "mouseout:month"), ("mouseout_year", "mouseout:year"), ("mouseup_date", "mouseup:date"), ("mouseup_month", "mouseup:month"), ("mouseup_year", "mouseup:year"), ("focus_date", "focus:date"), ("focus_month", "focus:month"), ("focus_year", "focus:year"), "change", "input", ("update_active_picker", "update:active-picker"), ("update_picker_date", "update:picker-date"), ] class VDialog(AbstractElement): """ Vuetify's VDialog component. See more info and examples |VDialog_vuetify_link|. .. |VDialog_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-dialog" target="_blank">here</a> :param activator: Designate a custom activator when the `activator` slot is not used. String can be any valid querySelector and Object can be any valid Node. :type any: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param close_delay: Milliseconds to wait before closing component. :type ['number', 'string']: :param content_class: Applies a custom class to the detached element. This is useful because the content is moved to the beginning of the `v-app` component (unless the **attach** prop is provided) and is not targetable by classes passed directly on the component. :type string: :param dark: See description |VDialog_vuetify_link|. :type boolean: :param disabled: Disables the ability to open the component. :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param fullscreen: Changes layout for fullscreen display. :type boolean: :param hide_overlay: Hides the display of the overlay. :type boolean: :param internal_activator: Detaches the menu content inside of the component as opposed to the document. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param max_width: Sets the maximum width for the component. :type ['string', 'number']: :param no_click_animation: Disables the bounce effect when clicking outside of a `v-dialog`'s content when using the **persistent** prop. :type boolean: :param open_delay: Milliseconds to wait before opening component. :type ['number', 'string']: :param open_on_focus: :type boolean: :param open_on_hover: Designates whether component should activate when its activator is hovered. :type boolean: :param origin: See description |VDialog_vuetify_link|. :type string: :param overlay_color: Sets the overlay color. :type string: :param overlay_opacity: Sets the overlay opacity. :type ['number', 'string']: :param persistent: Clicking outside of the element or pressing **esc** key will not deactivate it. :type boolean: :param retain_focus: Tab focus will return to the first child of the dialog by default. Disable this when using external tools that require focus such as TinyMCE or vue-clipboard. :type boolean: :param return_value: :type any: :param scrollable: See description |VDialog_vuetify_link|. :type boolean: :param transition: See description |VDialog_vuetify_link|. :type ['string', 'boolean']: :param value: Controls whether the component is visible or hidden. :type any: :param width: Sets the width for the component. :type ['string', 'number']: Events :param click_outside: Event that fires when clicking outside an active dialog. :param input: The updated bound model :param keydown: Event that fires when key is pressed. If dialog is active and not using the **persistent** prop, the **esc** key will deactivate it. """ def __init__(self, children=None, **kwargs): super().__init__("v-dialog", children, **kwargs) self._attr_names += [ "activator", "attach", "close_delay", "content_class", "dark", "disabled", "eager", "fullscreen", "hide_overlay", "internal_activator", "light", "max_width", "no_click_animation", "open_delay", "open_on_focus", "open_on_hover", "origin", "overlay_color", "overlay_opacity", "persistent", "retain_focus", "return_value", "scrollable", "transition", "value", "width", ] self._event_names += [ ("click_outside", "click:outside"), "input", "keydown", ] class VDivider(AbstractElement): """ Vuetify's VDivider component. See more info and examples |VDivider_vuetify_link|. .. |VDivider_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-divider" target="_blank">here</a> :param dark: See description |VDivider_vuetify_link|. :type boolean: :param inset: Adds indentation (72px) for **normal** dividers, reduces max height for **vertical**. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param vertical: Displays dividers vertically :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-divider", children, **kwargs) self._attr_names += [ "dark", "inset", "light", "vertical", ] class VExpansionPanels(AbstractElement): """ Vuetify's VExpansionPanels component. See more info and examples |VExpansionPanels_vuetify_link|. .. |VExpansionPanels_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-expansion-panels" target="_blank">here</a> :param accordion: Removes the margin around open panels :type boolean: :param active_class: The **active-class** applied to children when they are activated. :type string: :param dark: See description |VExpansionPanels_vuetify_link|. :type boolean: :param disabled: Disables the entire expansion-panel :type boolean: :param flat: Removes the expansion-panel's elevation and borders :type boolean: :param focusable: Makes the expansion-panel headers focusable :type boolean: :param hover: Applies a background-color shift on hover to expansion panel headers :type boolean: :param inset: Makes the expansion-panel open with a inset style :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param popout: Makes the expansion-panel open with an popout style :type boolean: :param readonly: Makes the entire expansion-panel read only. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the border-radius :type boolean: :param value: Controls the opened/closed state of content in the expansion-panel. Corresponds to a zero-based index of the currently opened content. If the `multiple` prop (previously `expand` in 1.5.x) is used then it is an array of numbers where each entry corresponds to the index of the opened content. The index order is not relevant. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-expansion-panels", children, **kwargs) self._attr_names += [ "accordion", "active_class", "dark", "disabled", "flat", "focusable", "hover", "inset", "light", "mandatory", "max", "multiple", "popout", "readonly", "tag", "tile", "value", ] class VExpansionPanel(AbstractElement): """ Vuetify's VExpansionPanel component. See more info and examples |VExpansionPanel_vuetify_link|. .. |VExpansionPanel_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-expansion-panel" target="_blank">here</a> :param active_class: See description |VExpansionPanel_vuetify_link|. :type string: :param disabled: Disables the expansion-panel content :type boolean: :param readonly: Makes the expansion-panel content read only. :type boolean: Events :param change: Toggles the value of the selected panel """ def __init__(self, children=None, **kwargs): super().__init__("v-expansion-panel", children, **kwargs) self._attr_names += [ "active_class", "disabled", "readonly", ] self._event_names += [ "change", # click, #Implemented in AbstractElement parent class ] class VExpansionPanelHeader(AbstractElement): """ Vuetify's VExpansionPanelHeader component. See more info and examples |VExpansionPanelHeader_vuetify_link|. .. |VExpansionPanelHeader_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-expansion-panel-header" target="_blank">here</a> :param color: See description |VExpansionPanelHeader_vuetify_link|. :type string: :param disable_icon_rotate: Removes the icon rotation animation when expanding a panel :type boolean: :param expand_icon: Set the expand action icon :type string: :param hide_actions: Hide the expand icon in the content header :type boolean: :param ripple: See description |VExpansionPanelHeader_vuetify_link|. :type ['boolean', 'object']: """ def __init__(self, children=None, **kwargs): super().__init__("v-expansion-panel-header", children, **kwargs) self._attr_names += [ "color", "disable_icon_rotate", "expand_icon", "hide_actions", "ripple", ] self._event_names += [ # click, #Implemented in AbstractElement parent class ] class VExpansionPanelContent(AbstractElement): """ Vuetify's VExpansionPanelContent component. See more info and examples |VExpansionPanelContent_vuetify_link|. .. |VExpansionPanelContent_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-expansion-panel-content" target="_blank">here</a> :param color: See description |VExpansionPanelContent_vuetify_link|. :type string: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-expansion-panel-content", children, **kwargs) self._attr_names += [ "color", "eager", ] class VFileInput(AbstractElement): """ Vuetify's VFileInput component. See more info and examples |VFileInput_vuetify_link|. .. |VFileInput_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-file-input" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param append_outer_icon: Appends an icon to the outside the component's input, uses same syntax as `v-icon` :type string: :param autofocus: Enables autofocus :type boolean: :param background_color: Changes the background-color of the input :type string: :param chips: Changes display of selections to chips :type boolean: :param clear_icon: Applied when using **clearable** and the input is dirty :type string: :param clearable: Add input clear functionality, default icon is Material Design Icons **mdi-clear** :type boolean: :param color: See description |VFileInput_vuetify_link|. :type string: :param counter: Creates counter for input length; if no number is specified, it defaults to 25. Does not apply any validation. :type ['boolean', 'number', 'string']: :param counter_size_string: See description |VFileInput_vuetify_link|. :type string: :param counter_string: See description |VFileInput_vuetify_link|. :type string: :param counter_value: :type function: :param dark: See description |VFileInput_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param filled: Applies the alternate filled input style :type boolean: :param flat: Removes elevation (shadow) added to element when using the **solo** or **solo-inverted** props :type boolean: :param full_width: Designates input type as full-width :type boolean: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hide_input: Display the icon only without the input (file names) :type boolean: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Adds the **multiple** attribute to the input, allowing multiple file selections. :type boolean: :param outlined: Applies the outlined style to the input :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param persistent_placeholder: Forces placeholder to always be visible :type boolean: :param placeholder: Sets the input's placeholder text :type string: :param prefix: Displays prefix text :type string: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param prepend_inner_icon: Prepends an icon inside the component's input, uses the same syntax as `v-icon` :type string: :param reverse: Reverses the input orientation :type boolean: :param rounded: Adds a border radius to the input :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param shaped: Round if `outlined` and increase `border-radius` if `filled`. Must be used with either `outlined` or `filled` :type boolean: :param show_size: Sets the displayed size of selected file(s). When using **true** will default to _1000_ displaying (**kB, MB, GB**) while _1024_ will display (**KiB, MiB, GiB**). :type ['boolean', 'number']: :param single_line: Label does not move on focus/dirty :type boolean: :param small_chips: Changes display of selections to chips with the **small** property :type boolean: :param solo: Changes the style of the input :type boolean: :param solo_inverted: Reduces element opacity until focused :type boolean: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param suffix: Displays suffix text :type string: :param truncate_length: The length of a filename before it is truncated with ellipsis :type ['number', 'string']: :param type: Sets input type :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: See description |VFileInput_vuetify_link|. :type any: Events :param blur: Emitted when the input is blurred :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_append_outer: Emitted when appended outer icon is clicked :param click_clear: Emitted when clearable icon clicked :param click_prepend: Emitted when prepended icon is clicked :param click_prepend_inner: Emitted when prepended inner icon is clicked :param focus: Emitted when component is focused :param input: The updated bound model :param keydown: Emitted when **any** key is pressed :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-file-input", children, **kwargs) self._attr_names += [ "append_icon", "append_outer_icon", "autofocus", "background_color", "chips", "clear_icon", "clearable", "color", "counter", "counter_size_string", "counter_string", "counter_value", # JS functions unimplemented "dark", "dense", "disabled", "error", "error_count", "error_messages", "filled", "flat", "full_width", "height", "hide_details", "hide_input", "hint", "id", "label", "light", "loader_height", "loading", "messages", "multiple", "outlined", "persistent_hint", "persistent_placeholder", "placeholder", "prefix", "prepend_icon", "prepend_inner_icon", "reverse", "rounded", "rules", "shaped", "show_size", "single_line", "small_chips", "solo", "solo_inverted", "success", "success_messages", "suffix", "truncate_length", "type", "validate_on_blur", "value", ] self._event_names += [ "blur", "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_append_outer", "click:append-outer"), ("click_clear", "click:clear"), ("click_prepend", "click:prepend"), ("click_prepend_inner", "click:prepend-inner"), "focus", "input", "keydown", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ] class VFooter(AbstractElement): """ Vuetify's VFooter component. See more info and examples |VFooter_vuetify_link|. .. |VFooter_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-footer" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param app: See description |VFooter_vuetify_link|. :type boolean: :param color: See description |VFooter_vuetify_link|. :type string: :param dark: See description |VFooter_vuetify_link|. :type boolean: :param elevation: See description |VFooter_vuetify_link|. :type ['number', 'string']: :param fixed: Applies **position: fixed** to the component. :type boolean: :param height: Sets the height for the component. :type ['number', 'string']: :param inset: Positions the toolbar offset from an application `v-navigation-drawer` :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param padless: Remove all padding from the footer :type boolean: :param rounded: See description |VFooter_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the component's **border-radius**. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-footer", children, **kwargs) self._attr_names += [ "absolute", "app", "color", "dark", "elevation", "fixed", "height", "inset", "light", "max_height", "max_width", "min_height", "min_width", "outlined", "padless", "rounded", "shaped", "tag", "tile", "width", ] class VForm(AbstractElement): """ Vuetify's VForm component. See more info and examples |VForm_vuetify_link|. .. |VForm_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-form" target="_blank">here</a> :param disabled: Puts all children inputs into a disabled state. :type boolean: :param lazy_validation: If enabled, **value** will always be _true_ unless there are visible validation errors. You can still call `validate()` to manually trigger validation :type boolean: :param readonly: Puts all children inputs into a readonly state. :type boolean: :param value: A boolean value representing the validity of the form. :type boolean: Events :param input: The updated bound model :param submit: Emitted when form is submitted """ def __init__(self, children=None, **kwargs): super().__init__("v-form", children, **kwargs) self._attr_names += [ "disabled", "lazy_validation", "readonly", "value", ] self._event_names += [ "input", "submit", ] class VContainer(AbstractElement): """ Vuetify's VContainer component. See more info and examples |VContainer_vuetify_link|. .. |VContainer_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-container" target="_blank">here</a> :param fluid: Removes viewport maximum-width size breakpoints :type boolean: :param id: Sets the DOM id on the component :type string: :param tag: Specify a custom tag used on the root element. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-container", children, **kwargs) self._attr_names += [ "fluid", "id", "tag", ] class VCol(AbstractElement): """ Vuetify's VCol component. See more info and examples |VCol_vuetify_link|. .. |VCol_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-col" target="_blank">here</a> :param align_self: See description |VCol_vuetify_link|. :type string: :param cols: Sets the default number of columns the component extends. Available options are **1 -> 12** and **auto**. :type ['boolean', 'string', 'number']: :param lg: Changes the number of columns on large and greater breakpoints. :type ['boolean', 'string', 'number']: :param md: Changes the number of columns on medium and greater breakpoints. :type ['boolean', 'string', 'number']: :param offset: Sets the default offset for the column. :type ['string', 'number']: :param offset_lg: Changes the offset of the component on large and greater breakpoints. :type ['string', 'number']: :param offset_md: Changes the offset of the component on medium and greater breakpoints. :type ['string', 'number']: :param offset_sm: Changes the offset of the component on small and greater breakpoints. :type ['string', 'number']: :param offset_xl: Changes the offset of the component on extra large and greater breakpoints. :type ['string', 'number']: :param order: See description |VCol_vuetify_link|. :type ['string', 'number']: :param order_lg: Changes the order of the component on large and greater breakpoints. :type ['string', 'number']: :param order_md: Changes the order of the component on medium and greater breakpoints. :type ['string', 'number']: :param order_sm: Changes the order of the component on small and greater breakpoints. :type ['string', 'number']: :param order_xl: Changes the order of the component on extra large and greater breakpoints. :type ['string', 'number']: :param sm: Changes the number of columns on small and greater breakpoints. :type ['boolean', 'string', 'number']: :param tag: Specify a custom tag used on the root element. :type string: :param xl: Changes the number of columns on extra large and greater breakpoints. :type ['boolean', 'string', 'number']: """ def __init__(self, children=None, **kwargs): super().__init__("v-col", children, **kwargs) self._attr_names += [ "align_self", "cols", "lg", "md", "offset", "offset_lg", "offset_md", "offset_sm", "offset_xl", "order", "order_lg", "order_md", "order_sm", "order_xl", "sm", "tag", "xl", ] class VRow(AbstractElement): """ Vuetify's VRow component. See more info and examples |VRow_vuetify_link|. .. |VRow_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-row" target="_blank">here</a> :param align: See description |VRow_vuetify_link|. :type string: :param align_content: See description |VRow_vuetify_link|. :type string: :param align_content_lg: Changes the **align-content** property on large and greater breakpoints. :type string: :param align_content_md: Changes the **align-content** property on medium and greater breakpoints. :type string: :param align_content_sm: Changes the **align-content** property on small and greater breakpoints. :type string: :param align_content_xl: Changes the **align-content** property on extra large and greater breakpoints. :type string: :param align_lg: Changes the **align-items** property on large and greater breakpoints. :type string: :param align_md: Changes the **align-items** property on medium and greater breakpoints. :type string: :param align_sm: Changes the **align-items** property on small and greater breakpoints. :type string: :param align_xl: Changes the **align-items** property on extra large and greater breakpoints. :type string: :param dense: Reduces the gutter between `v-col`s. :type boolean: :param justify: See description |VRow_vuetify_link|. :type string: :param justify_lg: Changes the **justify-content** property on large and greater breakpoints. :type string: :param justify_md: Changes the **justify-content** property on medium and greater breakpoints. :type string: :param justify_sm: Changes the **justify-content** property on small and greater breakpoints. :type string: :param justify_xl: Changes the **justify-content** property on extra large and greater breakpoints. :type string: :param no_gutters: Removes the gutter between `v-col`s. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-row", children, **kwargs) self._attr_names += [ "align", "align_content", "align_content_lg", "align_content_md", "align_content_sm", "align_content_xl", "align_lg", "align_md", "align_sm", "align_xl", "dense", "justify", "justify_lg", "justify_md", "justify_sm", "justify_xl", "no_gutters", "tag", ] class VSpacer(AbstractElement): """ Vuetify's VSpacer component. See more info and examples |VSpacer_vuetify_link|. .. |VSpacer_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-spacer" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-spacer", children, **kwargs) class VLayout(AbstractElement): """ Vuetify's VLayout component. See more info and examples |VLayout_vuetify_link|. .. |VLayout_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-layout" target="_blank">here</a> :param align_baseline: :type Boolean: :param align_center: :type Boolean: :param align_content_center: :type Boolean: :param align_content_end: :type Boolean: :param align_content_space_around: :type Boolean: :param align_content_space_between: :type Boolean: :param align_content_start: :type Boolean: :param align_end: :type Boolean: :param align_start: :type Boolean: :param column: :type boolean: :param d_{type}: :type Boolean: :param fill_height: :type Boolean: :param id: Sets the DOM id on the component :type string: :param justify_center: :type Boolean: :param justify_end: :type Boolean: :param justify_space_around: :type Boolean: :param justify_space_between: :type Boolean: :param justify_start: :type Boolean: :param reverse: :type boolean: :param row: :type boolean: :param tag: Specify a custom tag used on the root element. :type String: :param wrap: :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-layout", children, **kwargs) self._attr_names += [ "align_baseline", "align_center", "align_content_center", "align_content_end", "align_content_space_around", "align_content_space_between", "align_content_start", "align_end", "align_start", "column", "d_{type}", "fill_height", "id", "justify_center", "justify_end", "justify_space_around", "justify_space_between", "justify_start", "reverse", "row", "tag", "wrap", ] class VFlex(AbstractElement): """ Vuetify's VFlex component. See more info and examples |VFlex_vuetify_link|. .. |VFlex_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-flex" target="_blank">here</a> :param (size)(1_12): :type boolean: :param align_self_baseline: :type boolean: :param align_self_center: :type boolean: :param align_self_end: :type boolean: :param align_self_start: :type boolean: :param grow: :type boolean: :param id: Sets the DOM id on the component :type string: :param offset_(size)(0_12): :type boolean: :param order_(size)(1_12): :type boolean: :param shrink: :type boolean: :param tag: Specify a custom tag used on the root element. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-flex", children, **kwargs) self._attr_names += [ "sm1", "sm2", "sm3", "sm4", "sm5", "sm6", "sm7", "sm8", "sm9", "sm10", "sm11", "sm12", "md1", "md2", "md3", "md4", "md5", "md6", "md7", "md8", "md9", "md10", "md11", "md12", "lg1", "lg2", "lg3", "lg4", "lg5", "lg6", "lg7", "lg8", "lg9", "lg10", "lg11", "lg12", "xl1", "xl2", "xl3", "xl4", "xl5", "xl6", "xl7", "xl8", "xl9", "xl10", "xl11", "xl12", "align_self_baseline", "align_self_center", "align_self_end", "align_self_start", "grow", "id", "offset_sm0", "offset_sm1", "offset_sm2", "offset_sm3", "offset_sm4", "offset_sm5", "offset_sm6", "offset_sm7", "offset_sm8", "offset_sm9", "offset_sm10", "offset_sm11", "offset_sm12", "offset_md0", "offset_md1", "offset_md2", "offset_md3", "offset_md4", "offset_md5", "offset_md6", "offset_md7", "offset_md8", "offset_md9", "offset_md10", "offset_md11", "offset_md12", "offset_lg0", "offset_lg1", "offset_lg2", "offset_lg3", "offset_lg4", "offset_lg5", "offset_lg6", "offset_lg7", "offset_lg8", "offset_lg9", "offset_lg10", "offset_lg11", "offset_lg12", "offset_xl0", "offset_xl1", "offset_xl2", "offset_xl3", "offset_xl4", "offset_xl5", "offset_xl6", "offset_xl7", "offset_xl8", "offset_xl9", "offset_xl10", "offset_xl11", "offset_xl12", "order_sm1", "order_sm2", "order_sm3", "order_sm4", "order_sm5", "order_sm6", "order_sm7", "order_sm8", "order_sm9", "order_sm10", "order_sm11", "order_sm12", "order_md1", "order_md2", "order_md3", "order_md4", "order_md5", "order_md6", "order_md7", "order_md8", "order_md9", "order_md10", "order_md11", "order_md12", "order_lg1", "order_lg2", "order_lg3", "order_lg4", "order_lg5", "order_lg6", "order_lg7", "order_lg8", "order_lg9", "order_lg10", "order_lg11", "order_lg12", "order_xl1", "order_xl2", "order_xl3", "order_xl4", "order_xl5", "order_xl6", "order_xl7", "order_xl8", "order_xl9", "order_xl10", "order_xl11", "order_xl12", "shrink", "tag", ] class VHover(AbstractElement): """ Vuetify's VHover component. See more info and examples |VHover_vuetify_link|. .. |VHover_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-hover" target="_blank">here</a> :param close_delay: Milliseconds to wait before closing component. :type ['number', 'string']: :param disabled: Turns off hover functionality :type boolean: :param open_delay: Milliseconds to wait before opening component. :type ['number', 'string']: :param value: Controls whether the component is visible or hidden. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-hover", children, **kwargs) self._attr_names += [ "close_delay", "disabled", "open_delay", "value", ] class VIcon(AbstractElement): """ Vuetify's VIcon component. See more info and examples |VIcon_vuetify_link|. .. |VIcon_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-icon" target="_blank">here</a> :param color: See description |VIcon_vuetify_link|. :type string: :param dark: See description |VIcon_vuetify_link|. :type boolean: :param dense: Makes icon smaller (20px) :type boolean: :param disabled: Disable the input :type boolean: :param large: Makes the component large. :type boolean: :param left: Applies appropriate margins to the icon inside of a button when placed to the **left** of another element or text :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param right: Applies appropriate margins to the icon inside of a button when placed to the **right** of another element or text :type boolean: :param size: Specifies a custom font size for the icon :type ['number', 'string']: :param small: Makes the component small. :type boolean: :param tag: Specifies a custom tag to be used :type string: :param x_large: Makes the component extra large. :type boolean: :param x_small: Makes the component extra small. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-icon", children, **kwargs) self._attr_names += [ "color", "dark", "dense", "disabled", "large", "left", "light", "right", "size", "small", "tag", "x_large", "x_small", ] class VImg(AbstractElement): """ Vuetify's VImg component. See more info and examples |VImg_vuetify_link|. .. |VImg_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-img" target="_blank">here</a> :param alt: Alternate text for screen readers. Leave empty for decorative images :type string: :param aspect_ratio: Calculated as `width/height`, so for a 1920x1080px image this will be `1.7778`. Will be calculated automatically if omitted :type ['string', 'number']: :param contain: Prevents the image from being cropped if it doesn't fit :type boolean: :param content_class: Apply a custom class to the responsive content div. :type string: :param dark: See description |VImg_vuetify_link|. :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param gradient: See description |VImg_vuetify_link|. :type string: :param height: Sets the height for the component. :type ['number', 'string']: :param lazy_src: See description |VImg_vuetify_link|. :type string: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param options: See description |VImg_vuetify_link|. :type object: :param position: See description |VImg_vuetify_link|. :type string: :param sizes: See description |VImg_vuetify_link|. :type string: :param src: The image URL. This prop is mandatory :type ['string', 'object']: :param srcset: See description |VImg_vuetify_link|. :type string: :param transition: The transition to use when switching from `lazy-src` to `src` :type ['boolean', 'string']: :param width: Sets the width for the component. :type ['number', 'string']: Events :param error: Emitted when there is an error :param load: Emitted when image is loaded :param loadstart: Emitted when the image starts to load """ def __init__(self, children=None, **kwargs): super().__init__("v-img", children, **kwargs) self._attr_names += [ "alt", "aspect_ratio", "contain", "content_class", "dark", "eager", "gradient", "height", "lazy_src", "light", "max_height", "max_width", "min_height", "min_width", "options", "position", "sizes", "src", "srcset", "transition", "width", ] self._event_names += [ "error", "load", "loadstart", ] class VInput(AbstractElement): """ Vuetify's VInput component. See more info and examples |VInput_vuetify_link|. .. |VInput_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-input" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param background_color: Changes the background-color of the input :type string: :param color: See description |VInput_vuetify_link|. :type string: :param dark: See description |VInput_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type boolean: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param persistent_hint: Forces hint to always be visible :type boolean: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: Events :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_prepend: Emitted when prepended icon is clicked :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-input", children, **kwargs) self._attr_names += [ "append_icon", "background_color", "color", "dark", "dense", "disabled", "error", "error_count", "error_messages", "height", "hide_details", "hint", "id", "label", "light", "loading", "messages", "persistent_hint", "prepend_icon", "readonly", "rules", "success", "success_messages", "validate_on_blur", "value", ] self._event_names += [ "change", ("click_append", "click:append"), ("click_prepend", "click:prepend"), # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ] class VItem(AbstractElement): """ Vuetify's VItem component. See more info and examples |VItem_vuetify_link|. .. |VItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-item" target="_blank">here</a> :param active_class: See description |VItem_vuetify_link|. :type string: :param disabled: Removes the ability to click or target the component. :type boolean: :param value: The value used when the component is selected in a group. If not provided, the index will be used. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-item", children, **kwargs) self._attr_names += [ "active_class", "disabled", "value", ] class VItemGroup(AbstractElement): """ Vuetify's VItemGroup component. See more info and examples |VItemGroup_vuetify_link|. .. |VItemGroup_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-item-group" target="_blank">here</a> :param active_class: See description |VItemGroup_vuetify_link|. :type string: :param dark: See description |VItemGroup_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param value: The designated model value for the component. :type any: Events :param change: Emitted when the component value is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-item-group", children, **kwargs) self._attr_names += [ "active_class", "dark", "light", "mandatory", "max", "multiple", "tag", "value", ] self._event_names += [ "change", ] class VLazy(AbstractElement): """ Vuetify's VLazy component. See more info and examples |VLazy_vuetify_link|. .. |VLazy_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-lazy" target="_blank">here</a> :param height: Sets the height for the component. :type ['number', 'string']: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param options: See description |VLazy_vuetify_link|. :type object: :param tag: Specify a custom tag used on the root element. :type string: :param transition: See description |VLazy_vuetify_link|. :type string: :param value: Controls whether the component is visible or hidden. :type any: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-lazy", children, **kwargs) self._attr_names += [ "height", "max_height", "max_width", "min_height", "min_width", "options", "tag", "transition", "value", "width", ] class VListItemActionText(AbstractElement): """ Vuetify's VListItemActionText component. See more info and examples |VListItemActionText_vuetify_link|. .. |VListItemActionText_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-action-text" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-action-text", children, **kwargs) class VListItemContent(AbstractElement): """ Vuetify's VListItemContent component. See more info and examples |VListItemContent_vuetify_link|. .. |VListItemContent_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-content" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-content", children, **kwargs) class VListItemTitle(AbstractElement): """ Vuetify's VListItemTitle component. See more info and examples |VListItemTitle_vuetify_link|. .. |VListItemTitle_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-title" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-title", children, **kwargs) class VListItemSubtitle(AbstractElement): """ Vuetify's VListItemSubtitle component. See more info and examples |VListItemSubtitle_vuetify_link|. .. |VListItemSubtitle_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-subtitle" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-subtitle", children, **kwargs) class VList(AbstractElement): """ Vuetify's VList component. See more info and examples |VList_vuetify_link|. .. |VList_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list" target="_blank">here</a> :param color: See description |VList_vuetify_link|. :type string: :param dark: See description |VList_vuetify_link|. :type boolean: :param dense: Lowers max height of list tiles :type boolean: :param disabled: Disables all children `v-list-item` components :type boolean: :param elevation: See description |VList_vuetify_link|. :type ['number', 'string']: :param expand: Will only collapse when explicitly closed :type boolean: :param flat: Remove the highlighted background on active `v-list-item`s :type boolean: :param height: Sets the height for the component. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param nav: See description |VList_vuetify_link|. :type boolean: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param rounded: Rounds the `v-list-item` edges :type boolean: :param shaped: Provides an alternative active style for `v-list-item`. :type boolean: :param subheader: Removes top padding. Used when previous sibling is a header :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param three_line: See description |VList_vuetify_link|. :type boolean: :param tile: Removes the component's **border-radius**. :type boolean: :param two_line: See description |VList_vuetify_link|. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-list", children, **kwargs) self._attr_names += [ "color", "dark", "dense", "disabled", "elevation", "expand", "flat", "height", "light", "max_height", "max_width", "min_height", "min_width", "nav", "outlined", "rounded", "shaped", "subheader", "tag", "three_line", "tile", "two_line", "width", ] class VListGroup(AbstractElement): """ Vuetify's VListGroup component. See more info and examples |VListGroup_vuetify_link|. .. |VListGroup_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-group" target="_blank">here</a> :param active_class: See description |VListGroup_vuetify_link|. :type string: :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param color: See description |VListGroup_vuetify_link|. :type string: :param disabled: Disables all children `v-list-item` components :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param group: Assign a route namespace. Accepts a string or regexp for determining active state :type ['string', 'regexp']: :param no_action: Removes left padding assigned for action icons from group items :type boolean: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param ripple: See description |VListGroup_vuetify_link|. :type ['boolean', 'object']: :param sub_group: Designate the component as nested list group :type boolean: :param value: Expands / Collapse the list-group :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-list-group", children, **kwargs) self._attr_names += [ "active_class", "append_icon", "color", "disabled", "eager", "group", "no_action", "prepend_icon", "ripple", "sub_group", "value", ] self._event_names += [ # click, #Implemented in AbstractElement parent class ] class VListItem(AbstractElement): """ Vuetify's VListItem component. See more info and examples |VListItem_vuetify_link|. .. |VListItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item" target="_blank">here</a> :param active_class: See description |VListItem_vuetify_link|. :type string: :param append: See description |VListItem_vuetify_link|. :type boolean: :param color: Applies specified color to the control when in an **active** state or **input-value** is **true** - it can be the name of material color (for example `success` or `purple`) or css color (`#033` or `rgba(255, 0, 0, 0.5)`) :type string: :param dark: See description |VListItem_vuetify_link|. :type boolean: :param dense: Lowers max height of list tiles :type boolean: :param disabled: Disables the component :type boolean: :param exact: See description |VListItem_vuetify_link|. :type boolean: :param exact_active_class: See description |VListItem_vuetify_link|. :type string: :param exact_path: See description |VListItem_vuetify_link|. :type boolean: :param href: Designates the component as anchor and applies the **href** attribute. :type ['string', 'object']: :param inactive: If set, the list tile will not be rendered as a link even if it has to/href prop or @click handler :type boolean: :param input_value: Controls the **active** state of the item. This is typically used to highlight the component :type any: :param light: Applies the light theme variant to the component. :type boolean: :param link: Designates that the component is a link. This is automatic when using the **href** or **to** prop. :type boolean: :param nuxt: See description |VListItem_vuetify_link|. :type boolean: :param replace: See description |VListItem_vuetify_link|. :type boolean: :param ripple: See description |VListItem_vuetify_link|. :type ['boolean', 'object']: :param selectable: See description |VListItem_vuetify_link|. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param target: Designates the target attribute. This should only be applied when using the **href** prop. :type string: :param three_line: See description |VListItem_vuetify_link|. :type boolean: :param to: See description |VListItem_vuetify_link|. :type ['string', 'object']: :param two_line: See description |VListItem_vuetify_link|. :type boolean: :param value: See description |VListItem_vuetify_link|. :type any: Events :param keydown: """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item", children, **kwargs) self._attr_names += [ "active_class", "append", "color", "dark", "dense", "disabled", "exact", "exact_active_class", "exact_path", "href", "inactive", "input_value", "light", "link", "nuxt", "replace", "ripple", "selectable", "tag", "target", "three_line", "to", "two_line", "value", ] self._event_names += [ # click, #Implemented in AbstractElement parent class "keydown", ] class VListItemAction(AbstractElement): """ Vuetify's VListItemAction component. See more info and examples |VListItemAction_vuetify_link|. .. |VListItemAction_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-action" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-action", children, **kwargs) class VListItemAvatar(AbstractElement): """ Vuetify's VListItemAvatar component. See more info and examples |VListItemAvatar_vuetify_link|. .. |VListItemAvatar_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-avatar" target="_blank">here</a> :param color: See description |VListItemAvatar_vuetify_link|. :type string: :param height: Sets the height for the component. :type ['number', 'string']: :param horizontal: Uses an alternative horizontal style. :type boolean: :param left: See description |VListItemAvatar_vuetify_link|. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param right: See description |VListItemAvatar_vuetify_link|. :type boolean: :param rounded: See description |VListItemAvatar_vuetify_link|. :type ['boolean', 'string']: :param size: Sets the height and width of the component. :type ['number', 'string']: :param tile: Removes the component's **border-radius**. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-avatar", children, **kwargs) self._attr_names += [ "color", "height", "horizontal", "left", "max_height", "max_width", "min_height", "min_width", "right", "rounded", "size", "tile", "width", ] class VListItemIcon(AbstractElement): """ Vuetify's VListItemIcon component. See more info and examples |VListItemIcon_vuetify_link|. .. |VListItemIcon_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-icon" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-icon", children, **kwargs) class VListItemGroup(AbstractElement): """ Vuetify's VListItemGroup component. See more info and examples |VListItemGroup_vuetify_link|. .. |VListItemGroup_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-list-item-group" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param color: See description |VListItemGroup_vuetify_link|. :type string: :param dark: See description |VListItemGroup_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param value: Sets the active list-item inside the list-group :type any: Events :param change: Emitted when the component value is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-list-item-group", children, **kwargs) self._attr_names += [ "active_class", "color", "dark", "light", "mandatory", "max", "multiple", "tag", "value", ] self._event_names += [ "change", ] class VMain(AbstractElement): """ Vuetify's VMain component. See more info and examples |VMain_vuetify_link|. .. |VMain_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-main" target="_blank">here</a> :param tag: Specify a custom tag used on the root element. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-main", children, **kwargs) self._attr_names += [ "tag", ] class VMenu(AbstractElement): """ Vuetify's VMenu component. See more info and examples |VMenu_vuetify_link|. .. |VMenu_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-menu" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param activator: Designate a custom activator when the `activator` slot is not used. String can be any valid querySelector and Object can be any valid Node. :type any: :param allow_overflow: Removes overflow re-positioning for the content :type boolean: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param auto: Centers list on selected element :type boolean: :param bottom: Aligns the component towards the bottom. :type boolean: :param close_delay: Milliseconds to wait before closing component. Only works with the **open-on-hover** prop :type ['number', 'string']: :param close_on_click: Designates if menu should close on outside-activator click :type boolean: :param close_on_content_click: Designates if menu should close when its content is clicked :type boolean: :param content_class: Applies a custom class to the detached element. This is useful because the content is moved to the beginning of the `v-app` component (unless the **attach** prop is provided) and is not targetable by classes passed directly on the component. :type string: :param dark: See description |VMenu_vuetify_link|. :type boolean: :param disable_keys: Removes all keyboard interaction :type boolean: :param disabled: Disables the menu :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param internal_activator: Detaches the menu content inside of the component as opposed to the document. :type boolean: :param left: Aligns the component towards the left. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the max height of the menu content :type ['number', 'string']: :param max_width: Sets the maximum width for the content :type ['number', 'string']: :param min_width: Sets the minimum width for the content :type ['number', 'string']: :param nudge_bottom: Nudge the content to the bottom :type ['number', 'string']: :param nudge_left: Nudge the content to the left :type ['number', 'string']: :param nudge_right: Nudge the content to the right :type ['number', 'string']: :param nudge_top: Nudge the content to the top :type ['number', 'string']: :param nudge_width: Nudge the content width :type ['number', 'string']: :param offset_overflow: Causes the component to flip to the opposite side when repositioned due to overflow :type boolean: :param offset_x: Offset the menu on the x-axis. Works in conjunction with direction left/right :type boolean: :param offset_y: Offset the menu on the y-axis. Works in conjunction with direction top/bottom :type boolean: :param open_delay: Milliseconds to wait before opening component. Only works with the **open-on-hover** prop :type ['number', 'string']: :param open_on_click: Designates whether menu should open on activator click :type boolean: :param open_on_focus: :type boolean: :param open_on_hover: Designates whether menu should open on activator hover :type boolean: :param origin: See description |VMenu_vuetify_link|. :type string: :param position_x: Used to position the content when not using an activator slot :type number: :param position_y: Used to position the content when not using an activator slot :type number: :param return_value: The value that is updated when the menu is closed - must be primitive. Dot notation is supported :type any: :param right: Aligns the component towards the right. :type boolean: :param rounded: See description |VMenu_vuetify_link|. :type ['boolean', 'string']: :param tile: Removes the component's **border-radius**. :type boolean: :param top: Aligns the content towards the top. :type boolean: :param transition: See description |VMenu_vuetify_link|. :type ['boolean', 'string']: :param value: Controls whether the component is visible or hidden. :type any: :param z_index: The z-index used for the component :type ['number', 'string']: Events :param input: The updated bound model """ def __init__(self, children=None, **kwargs): super().__init__("v-menu", children, **kwargs) self._attr_names += [ "absolute", "activator", "allow_overflow", "attach", "auto", "bottom", "close_delay", "close_on_click", "close_on_content_click", "content_class", "dark", "disable_keys", "disabled", "eager", "fixed", "internal_activator", "left", "light", "max_height", "max_width", "min_width", "nudge_bottom", "nudge_left", "nudge_right", "nudge_top", "nudge_width", "offset_overflow", "offset_x", "offset_y", "open_delay", "open_on_click", "open_on_focus", "open_on_hover", "origin", "position_x", "position_y", "return_value", "right", "rounded", "tile", "top", "transition", "value", "z_index", ] self._event_names += [ "input", ] class VNavigationDrawer(AbstractElement): """ Vuetify's VNavigationDrawer component. See more info and examples |VNavigationDrawer_vuetify_link|. .. |VNavigationDrawer_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-navigation-drawer" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param app: See description |VNavigationDrawer_vuetify_link|. :type boolean: :param bottom: Expands from the bottom of the screen on mobile devices :type boolean: :param clipped: A clipped drawer rests under the application toolbar. **Note:** requires the **clipped-left** or **clipped-right** prop on `v-app-bar` to work as intended :type boolean: :param color: See description |VNavigationDrawer_vuetify_link|. :type string: :param dark: See description |VNavigationDrawer_vuetify_link|. :type boolean: :param disable_resize_watcher: Will automatically open/close drawer when resized depending if mobile or desktop. :type boolean: :param disable_route_watcher: Disables opening of navigation drawer when route changes :type boolean: :param expand_on_hover: Collapses the drawer to a **mini-variant** until hovering with the mouse :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param floating: A floating drawer has no visible container (no border-right) :type boolean: :param height: Sets the height of the navigation drawer :type ['number', 'string']: :param hide_overlay: Hides the display of the overlay. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mini_variant: Condenses navigation drawer width, also accepts the **.sync** modifier. With this, the drawer will re-open when clicking it :type boolean: :param mini_variant_width: Designates the width assigned when the `mini` prop is turned on :type ['number', 'string']: :param mobile_breakpoint: Sets the designated mobile breakpoint for the component. This will apply alternate styles for mobile devices such as the `temporary` prop, or activate the `bottom` prop when the breakpoint value is met. Setting the value to `0` will disable this functionality. :type ['number', 'string']: :param overlay_color: Sets the overlay color. :type string: :param overlay_opacity: Sets the overlay opacity. :type ['number', 'string']: :param permanent: The drawer remains visible regardless of screen size :type boolean: :param right: Places the navigation drawer on the right :type boolean: :param src: See description |VNavigationDrawer_vuetify_link|. :type ['string', 'object']: :param stateless: Remove all automated state functionality (resize, mobile, route) and manually control the drawer state :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param temporary: A temporary drawer sits above its application and uses a scrim (overlay) to darken the background :type boolean: :param touchless: Disable mobile touch functionality :type boolean: :param value: Controls whether the component is visible or hidden. :type any: :param width: Sets the width for the component. :type ['number', 'string']: Events :param input: The updated bound model :param transitionend: Emits event object when transition is complete. :param update_mini_variant: The `mini-variant.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-navigation-drawer", children, **kwargs) self._attr_names += [ "absolute", "app", "bottom", "clipped", "color", "dark", "disable_resize_watcher", "disable_route_watcher", "expand_on_hover", "fixed", "floating", "height", "hide_overlay", "light", "mini_variant", "mini_variant_width", "mobile_breakpoint", "overlay_color", "overlay_opacity", "permanent", "right", "src", "stateless", "tag", "temporary", "touchless", "value", "width", ] self._event_names += [ "input", "transitionend", ("update_mini_variant", "update:mini-variant"), ] class VOverflowBtn(AbstractElement): """ Vuetify's VOverflowBtn component. See more info and examples |VOverflowBtn_vuetify_link|. .. |VOverflowBtn_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-overflow-btn" target="_blank">here</a> :param allow_overflow: Allow the menu to overflow off the screen :type boolean: :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param append_outer_icon: Appends an icon to the outside the component's input, uses same syntax as `v-icon` :type string: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param auto_select_first: When searching, will always highlight the first option :type boolean: :param autofocus: Enables autofocus :type boolean: :param background_color: Changes the background-color of the input :type string: :param cache_items: Keeps a local _unique_ copy of all items that have been passed through the **items** prop. :type boolean: :param chips: Changes display of selections to chips :type boolean: :param clear_icon: Applied when using **clearable** and the input is dirty :type string: :param clearable: Add input clear functionality, default icon is Material Design Icons **mdi-clear** :type boolean: :param color: See description |VOverflowBtn_vuetify_link|. :type string: :param counter: Creates counter for input length; if no number is specified, it defaults to 25. Does not apply any validation. :type ['boolean', 'number', 'string']: :param counter_value: :type function: :param dark: See description |VOverflowBtn_vuetify_link|. :type boolean: :param deletable_chips: Adds a remove icon to selected chips :type boolean: :param dense: Reduces the input height :type boolean: :param disable_lookup: Disables keyboard lookup :type boolean: :param disabled: Disables the input :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param editable: Creates an editable button :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param filled: Applies the alternate filled input style :type boolean: :param filter: See description |VOverflowBtn_vuetify_link|. :type function: :param flat: Removes elevation (shadow) added to element when using the **solo** or **solo-inverted** props :type boolean: :param full_width: Designates input type as full-width :type boolean: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hide_no_data: Hides the menu when there are no options to show. Useful for preventing the menu from opening before results are fetched asynchronously. Also has the effect of opening the menu when the `items` array changes if not already open. :type boolean: :param hide_selected: Do not display in the select menu items that are already selected :type boolean: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param item_color: Sets color of selected items :type string: :param item_disabled: Set property of **items**'s disabled value :type ['string', 'array', 'function']: :param item_text: Set property of **items**'s text value :type ['string', 'array', 'function']: :param item_value: See description |VOverflowBtn_vuetify_link|. :type ['string', 'array', 'function']: :param items: Can be an array of objects or array of strings. When using objects, will look for a text, value and disabled keys. This can be changed using the **item-text**, **item-value** and **item-disabled** props. Objects that have a **header** or **divider** property are considered special cases and generate a list header or divider; these items are not selectable. :type array: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param menu_props: Pass props through to the `v-menu` component. Accepts either a string for boolean props `menu-props="auto, overflowY"`, or an object `:menu-props="{ auto: true, overflowY: true }"` :type ['string', 'array', 'object']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Changes select to multiple. Accepts array for value :type boolean: :param no_data_text: Display text when there is no data :type string: :param no_filter: Do not apply filtering when searching. Useful when data is being filtered server side :type boolean: :param open_on_clear: When using the **clearable** prop, once cleared, the select menu will either open or stay open, depending on the current state :type boolean: :param outlined: Applies the outlined style to the input :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param persistent_placeholder: Forces placeholder to always be visible :type boolean: :param placeholder: Sets the input's placeholder text :type string: :param prefix: Displays prefix text :type string: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param prepend_inner_icon: Prepends an icon inside the component's input, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param return_object: Changes the selection behavior to return the object directly rather than the value specified with **item-value** :type boolean: :param reverse: Reverses the input orientation :type boolean: :param rounded: Adds a border radius to the input :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param search_input: Search value. Can be used with `.sync` modifier. :type string: :param segmented: Creates a segmented button :type boolean: :param shaped: Round if `outlined` and increase `border-radius` if `filled`. Must be used with either `outlined` or `filled` :type boolean: :param single_line: Label does not move on focus/dirty :type boolean: :param small_chips: Changes display of selections to chips with the **small** property :type boolean: :param solo: Changes the style of the input :type boolean: :param solo_inverted: Reduces element opacity until focused :type boolean: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param suffix: Displays suffix text :type string: :param type: Sets input type :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param value_comparator: See description |VOverflowBtn_vuetify_link|. :type function: Events :param blur: Emitted when the input is blurred :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_append_outer: Emitted when appended outer icon is clicked :param click_clear: Emitted when clearable icon clicked :param click_prepend: Emitted when prepended icon is clicked :param click_prepend_inner: Emitted when prepended inner icon is clicked :param focus: Emitted when component is focused :param input: The updated bound model :param keydown: Emitted when **any** key is pressed :param update_error: The `error.sync` event :param update_list_index: Emitted when menu item is selected using keyboard arrows :param update_search_input: The `search-input.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-overflow-btn", children, **kwargs) self._attr_names += [ "allow_overflow", "append_icon", "append_outer_icon", "attach", "auto_select_first", "autofocus", "background_color", "cache_items", "chips", "clear_icon", "clearable", "color", "counter", "counter_value", # JS functions unimplemented "dark", "deletable_chips", "dense", "disable_lookup", "disabled", "eager", "editable", "error", "error_count", "error_messages", "filled", "filter", # JS functions unimplemented "flat", "full_width", "height", "hide_details", "hide_no_data", "hide_selected", "hint", "id", "item_color", "item_disabled", # JS functions unimplemented "item_text", # JS functions unimplemented "item_value", # JS functions unimplemented "items", "label", "light", "loader_height", "loading", "menu_props", "messages", "multiple", "no_data_text", "no_filter", "open_on_clear", "outlined", "persistent_hint", "persistent_placeholder", "placeholder", "prefix", "prepend_icon", "prepend_inner_icon", "readonly", "return_object", "reverse", "rounded", "rules", "search_input", "segmented", "shaped", "single_line", "small_chips", "solo", "solo_inverted", "success", "success_messages", "suffix", "type", "validate_on_blur", "value", "value_comparator", # JS functions unimplemented ] self._event_names += [ "blur", "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_append_outer", "click:append-outer"), ("click_clear", "click:clear"), ("click_prepend", "click:prepend"), ("click_prepend_inner", "click:prepend-inner"), "focus", "input", "keydown", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ("update_list_index", "update:list-index"), ("update_search_input", "update:search-input"), ] class VOverlay(AbstractElement): """ Vuetify's VOverlay component. See more info and examples |VOverlay_vuetify_link|. .. |VOverlay_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-overlay" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param color: See description |VOverlay_vuetify_link|. :type string: :param dark: See description |VOverlay_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param opacity: Sets the overlay opacity :type ['number', 'string']: :param value: Controls whether the component is visible or hidden. :type any: :param z_index: The z-index used for the component :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-overlay", children, **kwargs) self._attr_names += [ "absolute", "color", "dark", "light", "opacity", "value", "z_index", ] class VPagination(AbstractElement): """ Vuetify's VPagination component. See more info and examples |VPagination_vuetify_link|. .. |VPagination_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-pagination" target="_blank">here</a> :param circle: Shape pagination elements as circles :type boolean: :param color: See description |VPagination_vuetify_link|. :type string: :param current_page_aria_label: :type string: :param dark: See description |VPagination_vuetify_link|. :type boolean: :param disabled: Disables component :type boolean: :param length: The length of the pagination component :type number: :param light: Applies the light theme variant to the component. :type boolean: :param next_aria_label: :type string: :param next_icon: Specify the icon to use for the next icon :type string: :param page_aria_label: :type string: :param prev_icon: Specify the icon to use for the prev icon :type string: :param previous_aria_label: :type string: :param total_visible: Specify the max total visible pagination numbers :type ['number', 'string']: :param value: Current selected page :type number: :param wrapper_aria_label: :type string: Events :param input: The updated bound model :param next: Emitted when going to next item :param previous: Emitted when going to previous item """ def __init__(self, children=None, **kwargs): super().__init__("v-pagination", children, **kwargs) self._attr_names += [ "circle", "color", "current_page_aria_label", "dark", "disabled", "length", "light", "next_aria_label", "next_icon", "page_aria_label", "prev_icon", "previous_aria_label", "total_visible", "value", "wrapper_aria_label", ] self._event_names += [ "input", "next", "previous", ] class VSheet(AbstractElement): """ Vuetify's VSheet component. See more info and examples |VSheet_vuetify_link|. .. |VSheet_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-sheet" target="_blank">here</a> :param color: See description |VSheet_vuetify_link|. :type string: :param dark: See description |VSheet_vuetify_link|. :type boolean: :param elevation: See description |VSheet_vuetify_link|. :type ['number', 'string']: :param height: Sets the height for the component. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param rounded: See description |VSheet_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the component's **border-radius**. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-sheet", children, **kwargs) self._attr_names += [ "color", "dark", "elevation", "height", "light", "max_height", "max_width", "min_height", "min_width", "outlined", "rounded", "shaped", "tag", "tile", "width", ] class VParallax(AbstractElement): """ Vuetify's VParallax component. See more info and examples |VParallax_vuetify_link|. .. |VParallax_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-parallax" target="_blank">here</a> :param alt: Attaches an alt property to the parallax image :type string: :param height: Sets the height for the component :type ['string', 'number']: :param src: The image to parallax :type string: :param srcset: See description |VParallax_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-parallax", children, **kwargs) self._attr_names += [ "alt", "height", "src", "srcset", ] class VProgressCircular(AbstractElement): """ Vuetify's VProgressCircular component. See more info and examples |VProgressCircular_vuetify_link|. .. |VProgressCircular_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-progress-circular" target="_blank">here</a> :param button: Deprecated - Pending removal :type boolean: :param color: See description |VProgressCircular_vuetify_link|. :type string: :param indeterminate: Constantly animates, use when loading progress is unknown. :type boolean: :param rotate: Rotates the circle start point in deg :type ['number', 'string']: :param size: Sets the diameter of the circle in pixels :type ['number', 'string']: :param value: The percentage value for current progress :type ['number', 'string']: :param width: Sets the stroke of the circle in pixels :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-progress-circular", children, **kwargs) self._attr_names += [ "button", "color", "indeterminate", "rotate", "size", "value", "width", ] class VProgressLinear(AbstractElement): """ Vuetify's VProgressLinear component. See more info and examples |VProgressLinear_vuetify_link|. .. |VProgressLinear_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-progress-linear" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param active: Reduce the height to 0, hiding component :type boolean: :param background_color: Background color, set to component's color if null :type string: :param background_opacity: Background opacity, if null it defaults to 0.3 if background color is not specified or 1 otherwise :type ['number', 'string']: :param bottom: Aligns the component towards the bottom. :type boolean: :param buffer_value: The percentage value for the buffer :type ['number', 'string']: :param color: See description |VProgressLinear_vuetify_link|. :type string: :param dark: See description |VProgressLinear_vuetify_link|. :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param height: Sets the height for the component :type ['number', 'string']: :param indeterminate: Constantly animates, use when loading progress is unknown. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param query: Animates like **indeterminate** prop but inverse :type boolean: :param reverse: Displays reversed progress (right to left in LTR mode and left to right in RTL) :type boolean: :param rounded: Adds a border radius to the progress component :type boolean: :param stream: An alternative style for portraying loading that works in tandem with **buffer-value** :type boolean: :param striped: Adds a stripe background to the filled portion of the progress component :type boolean: :param top: Aligns the content towards the top. :type boolean: :param value: The designated model value for the component. :type ['number', 'string']: Events :param change: Emitted when the component value is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-progress-linear", children, **kwargs) self._attr_names += [ "absolute", "active", "background_color", "background_opacity", "bottom", "buffer_value", "color", "dark", "fixed", "height", "indeterminate", "light", "query", "reverse", "rounded", "stream", "striped", "top", "value", ] self._event_names += [ "change", ] class VRadioGroup(AbstractElement): """ Vuetify's VRadioGroup component. See more info and examples |VRadioGroup_vuetify_link|. .. |VRadioGroup_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-radio-group" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param background_color: Changes the background-color of the input :type string: :param column: Displays radio buttons in column :type boolean: :param dark: See description |VRadioGroup_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param name: Sets the component's name attribute :type string: :param persistent_hint: Forces hint to always be visible :type boolean: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param row: Displays radio buttons in row :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param tag: Specify a custom tag used on the root element. :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param value_comparator: Apply a custom value comparator function :type function: Events :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_prepend: Emitted when prepended icon is clicked :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-radio-group", children, **kwargs) self._attr_names += [ "active_class", "append_icon", "background_color", "column", "dark", "dense", "disabled", "error", "error_count", "error_messages", "hide_details", "hint", "id", "label", "light", "mandatory", "max", "messages", "multiple", "name", "persistent_hint", "prepend_icon", "readonly", "row", "rules", "success", "success_messages", "tag", "validate_on_blur", "value", "value_comparator", # JS functions unimplemented ] self._event_names += [ "change", ("click_append", "click:append"), ("click_prepend", "click:prepend"), # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ] class VRadio(AbstractElement): """ Vuetify's VRadio component. See more info and examples |VRadio_vuetify_link|. .. |VRadio_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-radio" target="_blank">here</a> :param active_class: See description |VRadio_vuetify_link|. :type string: :param color: See description |VRadio_vuetify_link|. :type string: :param dark: See description |VRadio_vuetify_link|. :type boolean: :param disabled: Removes the ability to click or target the component. :type boolean: :param id: Sets the DOM id on the component :type string: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param name: Sets the component's name attribute :type string: :param off_icon: The icon used when inactive :type string: :param on_icon: The icon used when active :type string: :param readonly: Puts input in readonly state :type boolean: :param ripple: See description |VRadio_vuetify_link|. :type ['boolean', 'object']: :param value: The value used when the component is selected in a group. If not provided, the index will be used. :type any: Events :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_prepend: Emitted when prepended icon is clicked :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-radio", children, **kwargs) self._attr_names += [ "active_class", "color", "dark", "disabled", "id", "label", "light", "name", "off_icon", "on_icon", "readonly", "ripple", "value", ] self._event_names += [ "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_prepend", "click:prepend"), # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ] class VRangeSlider(AbstractElement): """ Vuetify's VRangeSlider component. See more info and examples |VRangeSlider_vuetify_link|. .. |VRangeSlider_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-range-slider" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param background_color: Changes the background-color of the input :type string: :param color: See description |VRangeSlider_vuetify_link|. :type string: :param dark: See description |VRangeSlider_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param inverse_label: Reverse the label position. Works with **rtl**. :type boolean: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param max: Sets the maximum allowed value :type ['number', 'string']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param min: Sets the minimum allowed value :type ['number', 'string']: :param persistent_hint: Forces hint to always be visible :type boolean: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param step: If greater than 0, sets step interval for ticks :type ['number', 'string']: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param thumb_color: Sets the thumb and thumb label color :type string: :param thumb_label: Show thumb label. If `true` it shows label when using slider. If set to `'always'` it always shows label. :type ['boolean', 'string']: :param thumb_size: Controls the size of the thumb label. :type ['number', 'string']: :param tick_labels: When provided with Array<string>, will attempt to map the labels to each step in index order :type array: :param tick_size: Controls the size of **ticks** :type ['number', 'string']: :param ticks: Show track ticks. If `true` it shows ticks when using slider. If set to `'always'` it always shows ticks. :type ['boolean', 'string']: :param track_color: Sets the track's color :type string: :param track_fill_color: Sets the track's fill color :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param vertical: Changes slider direction to vertical :type boolean: Events :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_prepend: Emitted when prepended icon is clicked :param end: Slider value emitted at the end of slider movement :param input: The updated bound model :param start: Slider value emitted at start of slider movement :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-range-slider", children, **kwargs) self._attr_names += [ "append_icon", "background_color", "color", "dark", "dense", "disabled", "error", "error_count", "error_messages", "height", "hide_details", "hint", "id", "inverse_label", "label", "light", "loader_height", "loading", "max", "messages", "min", "persistent_hint", "prepend_icon", "readonly", "rules", "step", "success", "success_messages", "thumb_color", "thumb_label", "thumb_size", "tick_labels", "tick_size", "ticks", "track_color", "track_fill_color", "validate_on_blur", "value", "vertical", ] self._event_names += [ "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_prepend", "click:prepend"), "end", "input", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class "start", ("update_error", "update:error"), ] class VRating(AbstractElement): """ Vuetify's VRating component. See more info and examples |VRating_vuetify_link|. .. |VRating_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-rating" target="_blank">here</a> :param background_color: The color used empty icons :type string: :param clearable: Allows for the component to be cleared. Triggers when the icon containing the current value is clicked. :type boolean: :param close_delay: Milliseconds to wait before closing component. :type ['number', 'string']: :param color: See description |VRating_vuetify_link|. :type string: :param dark: See description |VRating_vuetify_link|. :type boolean: :param dense: Icons have a smaller size :type boolean: :param empty_icon: The icon displayed when empty :type string: :param full_icon: The icon displayed when full :type string: :param half_icon: The icon displayed when half (requires **half-increments** prop) :type string: :param half_increments: Allows the selection of half increments :type boolean: :param hover: Provides visual feedback when hovering over icons :type boolean: :param icon_label: The **aria-label** used for icons :type string: :param large: Makes the component large. :type boolean: :param length: The amount of ratings to show :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param open_delay: Milliseconds to wait before opening component. :type ['number', 'string']: :param readonly: Removes all hover effects and pointer events :type boolean: :param ripple: See description |VRating_vuetify_link|. :type ['boolean', 'object']: :param size: Sets the height and width of the component. :type ['number', 'string']: :param small: Makes the component small. :type boolean: :param value: The rating value :type number: :param x_large: Makes the component extra large. :type boolean: :param x_small: Makes the component extra small. :type boolean: Events :param input: Emits the rating number when this value changes """ def __init__(self, children=None, **kwargs): super().__init__("v-rating", children, **kwargs) self._attr_names += [ "background_color", "clearable", "close_delay", "color", "dark", "dense", "empty_icon", "full_icon", "half_icon", "half_increments", "hover", "icon_label", "large", "length", "light", "open_delay", "readonly", "ripple", "size", "small", "value", "x_large", "x_small", ] self._event_names += [ "input", ] class VResponsive(AbstractElement): """ Vuetify's VResponsive component. See more info and examples |VResponsive_vuetify_link|. .. |VResponsive_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-responsive" target="_blank">here</a> :param aspect_ratio: Sets a base aspect ratio, calculated as width/height. This will only set a **minimum** height, the component can still grow if it has a lot of content. :type ['string', 'number']: :param content_class: Apply a custom class to the responsive content div. :type string: :param height: Sets the height for the component. :type ['number', 'string']: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-responsive", children, **kwargs) self._attr_names += [ "aspect_ratio", "content_class", "height", "max_height", "max_width", "min_height", "min_width", "width", ] class VSelect(AbstractElement): """ Vuetify's VSelect component. See more info and examples |VSelect_vuetify_link|. .. |VSelect_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-select" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param append_outer_icon: Appends an icon to the outside the component's input, uses same syntax as `v-icon` :type string: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param autofocus: Enables autofocus :type boolean: :param background_color: Changes the background-color of the input :type string: :param cache_items: Keeps a local _unique_ copy of all items that have been passed through the **items** prop. :type boolean: :param chips: Changes display of selections to chips :type boolean: :param clear_icon: Applied when using **clearable** and the input is dirty :type string: :param clearable: Add input clear functionality, default icon is Material Design Icons **mdi-clear** :type boolean: :param color: See description |VSelect_vuetify_link|. :type string: :param counter: Creates counter for input length; if no number is specified, it defaults to 25. Does not apply any validation. :type ['boolean', 'number', 'string']: :param counter_value: :type function: :param dark: See description |VSelect_vuetify_link|. :type boolean: :param deletable_chips: Adds a remove icon to selected chips :type boolean: :param dense: Reduces the input height :type boolean: :param disable_lookup: Disables keyboard lookup :type boolean: :param disabled: Disables the input :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param filled: Applies the alternate filled input style :type boolean: :param flat: Removes elevation (shadow) added to element when using the **solo** or **solo-inverted** props :type boolean: :param full_width: Designates input type as full-width :type boolean: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hide_selected: Do not display in the select menu items that are already selected :type boolean: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param item_color: Sets color of selected items :type string: :param item_disabled: Set property of **items**'s disabled value :type ['string', 'array', 'function']: :param item_text: Set property of **items**'s text value :type ['string', 'array', 'function']: :param item_value: See description |VSelect_vuetify_link|. :type ['string', 'array', 'function']: :param items: Can be an array of objects or array of strings. When using objects, will look for a text, value and disabled keys. This can be changed using the **item-text**, **item-value** and **item-disabled** props. Objects that have a **header** or **divider** property are considered special cases and generate a list header or divider; these items are not selectable. :type array: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param menu_props: Pass props through to the `v-menu` component. Accepts either a string for boolean props `menu-props="auto, overflowY"`, or an object `:menu-props="{ auto: true, overflowY: true }"` :type ['string', 'array', 'object']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Changes select to multiple. Accepts array for value :type boolean: :param no_data_text: Display text when there is no data :type string: :param open_on_clear: When using the **clearable** prop, once cleared, the select menu will either open or stay open, depending on the current state :type boolean: :param outlined: Applies the outlined style to the input :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param persistent_placeholder: Forces placeholder to always be visible :type boolean: :param placeholder: Sets the input's placeholder text :type string: :param prefix: Displays prefix text :type string: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param prepend_inner_icon: Prepends an icon inside the component's input, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param return_object: Changes the selection behavior to return the object directly rather than the value specified with **item-value** :type boolean: :param reverse: Reverses the input orientation :type boolean: :param rounded: Adds a border radius to the input :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param shaped: Round if `outlined` and increase `border-radius` if `filled`. Must be used with either `outlined` or `filled` :type boolean: :param single_line: Label does not move on focus/dirty :type boolean: :param small_chips: Changes display of selections to chips with the **small** property :type boolean: :param solo: Changes the style of the input :type boolean: :param solo_inverted: Reduces element opacity until focused :type boolean: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param suffix: Displays suffix text :type string: :param type: Sets input type :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param value_comparator: See description |VSelect_vuetify_link|. :type function: Events :param blur: Emitted when the input is blurred :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_append_outer: Emitted when appended outer icon is clicked :param click_clear: Emitted when clearable icon clicked :param click_prepend: Emitted when prepended icon is clicked :param click_prepend_inner: Emitted when prepended inner icon is clicked :param focus: Emitted when component is focused :param input: The updated bound model :param keydown: Emitted when **any** key is pressed :param update_error: The `error.sync` event :param update_list_index: Emitted when menu item is selected using keyboard arrows :param update_search_input: The `search-input.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-select", children, **kwargs) self.ttsSensitive() self._attr_names += [ "append_icon", "append_outer_icon", "attach", "autofocus", "background_color", "cache_items", "chips", "clear_icon", "clearable", "color", "counter", "counter_value", # JS functions unimplemented "dark", "deletable_chips", "dense", "disable_lookup", "disabled", "eager", "error", "error_count", "error_messages", "filled", "flat", "full_width", "height", "hide_details", "hide_selected", "hint", "id", "item_color", "item_disabled", # JS functions unimplemented "item_text", # JS functions unimplemented "item_value", # JS functions unimplemented "items", "label", "light", "loader_height", "loading", "menu_props", "messages", "multiple", "no_data_text", "open_on_clear", "outlined", "persistent_hint", "persistent_placeholder", "placeholder", "prefix", "prepend_icon", "prepend_inner_icon", "readonly", "return_object", "reverse", "rounded", "rules", "shaped", "single_line", "small_chips", "solo", "solo_inverted", "success", "success_messages", "suffix", "type", "validate_on_blur", "value", "value_comparator", # JS functions unimplemented ] self._event_names += [ "blur", "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_append_outer", "click:append-outer"), ("click_clear", "click:clear"), ("click_prepend", "click:prepend"), ("click_prepend_inner", "click:prepend-inner"), "focus", "input", "keydown", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ("update_list_index", "update:list-index"), ("update_search_input", "update:search-input"), ] class VSkeletonLoader(AbstractElement): """ Vuetify's VSkeletonLoader component. See more info and examples |VSkeletonLoader_vuetify_link|. .. |VSkeletonLoader_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-skeleton-loader" target="_blank">here</a> :param boilerplate: Remove the loading animation from the skeleton :type boolean: :param dark: See description |VSkeletonLoader_vuetify_link|. :type boolean: :param elevation: See description |VSkeletonLoader_vuetify_link|. :type ['number', 'string']: :param height: Sets the height for the component. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param loading: Applies a loading animation with a on-hover loading cursor. A value of **false** will only work when there is content in the `default` slot. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param tile: Removes the component's border-radius :type boolean: :param transition: See description |VSkeletonLoader_vuetify_link|. :type string: :param type: A string delimited list of skeleton components to create such as `type="text@3"` or `type="card, list-item"`. Will recursively generate a corresponding skeleton from the provided string. Also supports short-hand for multiple elements such as **article@3** and **paragraph@2** which will generate 3 _article_ skeletons and 2 _paragraph_ skeletons. Please see below for a list of available pre-defined options. :type string: :param types: A custom types object that will be combined with the pre-defined options. For a list of available pre-defined options, see the **type** prop. :type object: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-skeleton-loader", children, **kwargs) self._attr_names += [ "boilerplate", "dark", "elevation", "height", "light", "loading", "max_height", "max_width", "min_height", "min_width", "tile", "transition", "type", "types", "width", ] class VSlider(AbstractElement): """ Vuetify's VSlider component. See more info and examples |VSlider_vuetify_link|. .. |VSlider_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-slider" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param background_color: Changes the background-color of the input :type string: :param color: See description |VSlider_vuetify_link|. :type string: :param dark: See description |VSlider_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param inverse_label: Reverse the label position. Works with **rtl**. :type boolean: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param max: Sets the maximum allowed value :type ['number', 'string']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param min: Sets the minimum allowed value :type ['number', 'string']: :param persistent_hint: Forces hint to always be visible :type boolean: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param step: If greater than 0, sets step interval for ticks :type ['number', 'string']: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param thumb_color: Sets the thumb and thumb label color :type string: :param thumb_label: Show thumb label. If `true` it shows label when using slider. If set to `'always'` it always shows label. :type ['boolean', 'string']: :param thumb_size: Controls the size of the thumb label. :type ['number', 'string']: :param tick_labels: When provided with Array<string>, will attempt to map the labels to each step in index order :type array: :param tick_size: Controls the size of **ticks** :type ['number', 'string']: :param ticks: Show track ticks. If `true` it shows ticks when using slider. If set to `'always'` it always shows ticks. :type ['boolean', 'string']: :param track_color: Sets the track's color :type string: :param track_fill_color: Sets the track's fill color :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param vertical: Changes slider direction to vertical :type boolean: Events :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_prepend: Emitted when prepended icon is clicked :param end: Slider value emitted at the end of slider movement :param input: The updated bound model :param start: Slider value emitted at start of slider movement :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-slider", children, **kwargs) self._attr_names += [ "append_icon", "background_color", "color", "dark", "dense", "disabled", "error", "error_count", "error_messages", "height", "hide_details", "hint", "id", "inverse_label", "label", "light", "loader_height", "loading", "max", "messages", "min", "persistent_hint", "prepend_icon", "readonly", "rules", "step", "success", "success_messages", "thumb_color", "thumb_label", "thumb_size", "tick_labels", "tick_size", "ticks", "track_color", "track_fill_color", "validate_on_blur", "value", "vertical", ] self._event_names += [ "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_prepend", "click:prepend"), "end", "input", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class "start", ("update_error", "update:error"), ] class VSlideGroup(AbstractElement): """ Vuetify's VSlideGroup component. See more info and examples |VSlideGroup_vuetify_link|. .. |VSlideGroup_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-slide-group" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param center_active: Forces the selected component to be centered :type boolean: :param dark: See description |VSlideGroup_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param mobile_breakpoint: Sets the designated mobile breakpoint for the component. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param next_icon: The appended slot when arrows are shown :type string: :param prev_icon: The prepended slot when arrows are shown :type string: :param show_arrows: See description |VSlideGroup_vuetify_link|. :type ['boolean', 'string']: :param tag: Specify a custom tag used on the root element. :type string: :param value: The designated model value for the component. :type any: Events :param change: Emitted when the component value is changed by user interaction :param click_next: Emitted when the next is clicked :param click_prev: Emitted when the prev is clicked """ def __init__(self, children=None, **kwargs): super().__init__("v-slide-group", children, **kwargs) self._attr_names += [ "active_class", "center_active", "dark", "light", "mandatory", "max", "mobile_breakpoint", "multiple", "next_icon", "prev_icon", "show_arrows", "tag", "value", ] self._event_names += [ "change", ("click_next", "click:next"), ("click_prev", "click:prev"), ] class VSlideItem(AbstractElement): """ Vuetify's VSlideItem component. See more info and examples |VSlideItem_vuetify_link|. .. |VSlideItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-slide-item" target="_blank">here</a> :param active_class: See description |VSlideItem_vuetify_link|. :type string: :param disabled: Removes the ability to click or target the component. :type boolean: :param value: The value used when the component is selected in a group. If not provided, the index will be used. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-slide-item", children, **kwargs) self._attr_names += [ "active_class", "disabled", "value", ] class VSnackbar(AbstractElement): """ Vuetify's VSnackbar component. See more info and examples |VSnackbar_vuetify_link|. .. |VSnackbar_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-snackbar" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param app: Respects boundaries of—and will not overlap with—other `app` components like `v-app-bar`, `v-navigation-drawer`, and `v-footer`. :type boolean: :param bottom: Aligns the component towards the bottom. :type boolean: :param centered: Positions the snackbar in the center of the screen, (x and y axis). :type boolean: :param color: See description |VSnackbar_vuetify_link|. :type string: :param content_class: Apply a custom class to the snackbar content :type string: :param dark: See description |VSnackbar_vuetify_link|. :type boolean: :param elevation: See description |VSnackbar_vuetify_link|. :type ['number', 'string']: :param height: Sets the height for the component. :type ['number', 'string']: :param left: Aligns the component towards the left. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param multi_line: Gives the snackbar a larger minimum height. :type boolean: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param right: Aligns the component towards the right. :type boolean: :param rounded: See description |VSnackbar_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param text: Applies the defined **color** to text and a low opacity background of the same. :type boolean: :param tile: Removes the component's **border-radius**. :type boolean: :param timeout: Time (in milliseconds) to wait until snackbar is automatically hidden. Use `-1` to keep open indefinitely (`0` in version < 2.3 ). It is recommended for this number to be between `4000` and `10000`. Changes to this property will reset the timeout. :type ['number', 'string']: :param top: Aligns the content towards the top. :type boolean: :param transition: See description |VSnackbar_vuetify_link|. :type ['boolean', 'string']: :param value: Controls whether the component is visible or hidden. :type any: :param vertical: Stacks snackbar content on top of the actions (button). :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: Events :param input: The updated bound model """ def __init__(self, children=None, **kwargs): super().__init__("v-snackbar", children, **kwargs) self._attr_names += [ "absolute", "app", "bottom", "centered", "color", "content_class", "dark", "elevation", "height", "left", "light", "max_height", "max_width", "min_height", "min_width", "multi_line", "outlined", "right", "rounded", "shaped", "tag", "text", "tile", "timeout", "top", "transition", "value", "vertical", "width", ] self._event_names += [ "input", ] class VSparkline(AbstractElement): """ Vuetify's VSparkline component. See more info and examples |VSparkline_vuetify_link|. .. |VSparkline_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-sparkline" target="_blank">here</a> :param auto_draw: Trace the length of the line when first rendered :type boolean: :param auto_draw_duration: Amount of time (in ms) to run the trace animation :type number: :param auto_draw_easing: The easing function to use for the trace animation :type string: :param auto_line_width: Automatically expand bars to use space efficiently :type boolean: :param color: See description |VSparkline_vuetify_link|. :type string: :param fill: Using the **fill** property allows you to better customize the look and feel of your sparkline. :type boolean: :param gradient: An array of colors to use as a linear-gradient :type array: :param gradient_direction: The direction the gradient should run :type string: :param height: Height of the SVG trendline or bars :type ['string', 'number']: :param label_size: The label font size :type ['number', 'string']: :param labels: An array of string labels that correspond to the same index as its data counterpart :type array: :param line_width: The thickness of the line, in px :type ['string', 'number']: :param padding: Low `smooth` or high `line-width` values may result in cropping, increase padding to compensate :type ['string', 'number']: :param show_labels: Show labels below each data point :type boolean: :param smooth: Number of px to use as a corner radius. `true` defaults to 8, `false` is 0 :type ['boolean', 'number', 'string']: :param type: Choose between a trendline or bars :type string: :param value: An array of numbers. :type array: :param width: Width of the SVG trendline or bars :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-sparkline", children, **kwargs) self._attr_names += [ "auto_draw", "auto_draw_duration", "auto_draw_easing", "auto_line_width", "color", "fill", "gradient", "gradient_direction", "height", "label_size", "labels", "line_width", "padding", "show_labels", "smooth", "type", "value", "width", ] class VSpeedDial(AbstractElement): """ Vuetify's VSpeedDial component. See more info and examples |VSpeedDial_vuetify_link|. .. |VSpeedDial_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-speed-dial" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param bottom: Aligns the component towards the bottom. :type boolean: :param direction: Direction in which speed-dial content will show. Possible values are `top`, `bottom`, `left`, `right`. :type string: :param fixed: Applies **position: fixed** to the component. :type boolean: :param left: Aligns the component towards the left. :type boolean: :param mode: See description |VSpeedDial_vuetify_link|. :type string: :param open_on_hover: Opens speed-dial on hover :type boolean: :param origin: See description |VSpeedDial_vuetify_link|. :type string: :param right: Aligns the component towards the right. :type boolean: :param top: Aligns the content towards the top. :type boolean: :param transition: See description |VSpeedDial_vuetify_link|. :type string: :param value: Controls whether the component is visible or hidden. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-speed-dial", children, **kwargs) self._attr_names += [ "absolute", "bottom", "direction", "fixed", "left", "mode", "open_on_hover", "origin", "right", "top", "transition", "value", ] class VStepper(AbstractElement): """ Vuetify's VStepper component. See more info and examples |VStepper_vuetify_link|. .. |VStepper_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-stepper" target="_blank">here</a> :param alt_labels: Places the labels beneath the step :type boolean: :param color: See description |VStepper_vuetify_link|. :type string: :param dark: See description |VStepper_vuetify_link|. :type boolean: :param elevation: See description |VStepper_vuetify_link|. :type ['number', 'string']: :param flat: Removes the stepper's elevation. :type boolean: :param height: Sets the height for the component. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param non_linear: Allow user to jump to any step :type boolean: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param rounded: See description |VStepper_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the component's **border-radius**. :type boolean: :param value: The designated model value for the component. :type any: :param vertical: Display steps vertically :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: Events :param change: Emitted when step is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-stepper", children, **kwargs) self._attr_names += [ "alt_labels", "color", "dark", "elevation", "flat", "height", "light", "max_height", "max_width", "min_height", "min_width", "non_linear", "outlined", "rounded", "shaped", "tag", "tile", "value", "vertical", "width", ] self._event_names += [ "change", ] class VStepperContent(AbstractElement): """ Vuetify's VStepperContent component. See more info and examples |VStepperContent_vuetify_link|. .. |VStepperContent_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-stepper-content" target="_blank">here</a> :param step: Sets step to associate the content to :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-stepper-content", children, **kwargs) self._attr_names += [ "step", ] class VStepperStep(AbstractElement): """ Vuetify's VStepperStep component. See more info and examples |VStepperStep_vuetify_link|. .. |VStepperStep_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-stepper-step" target="_blank">here</a> :param color: See description |VStepperStep_vuetify_link|. :type string: :param complete: Marks step as complete :type boolean: :param complete_icon: Icon to display when step is marked as completed :type string: :param edit_icon: Icon to display when step is editable :type string: :param editable: Marks step as editable :type boolean: :param error_icon: Icon to display when step has an error :type string: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param step: Content to display inside step circle :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-stepper-step", children, **kwargs) self._attr_names += [ "color", "complete", "complete_icon", "edit_icon", "editable", "error_icon", "rules", "step", ] self._event_names += [ # click, #Implemented in AbstractElement parent class ] class VStepperHeader(AbstractElement): """ Vuetify's VStepperHeader component. See more info and examples |VStepperHeader_vuetify_link|. .. |VStepperHeader_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-stepper-header" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-stepper-header", children, **kwargs) class VStepperItems(AbstractElement): """ Vuetify's VStepperItems component. See more info and examples |VStepperItems_vuetify_link|. .. |VStepperItems_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-stepper-items" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-stepper-items", children, **kwargs) class VSubheader(AbstractElement): """ Vuetify's VSubheader component. See more info and examples |VSubheader_vuetify_link|. .. |VSubheader_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-subheader" target="_blank">here</a> :param dark: See description |VSubheader_vuetify_link|. :type boolean: :param inset: Adds indentation (72px) :type boolean: :param light: Applies the light theme variant to the component. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-subheader", children, **kwargs) self._attr_names += [ "dark", "inset", "light", ] class VSwitch(AbstractElement): """ Vuetify's VSwitch component. See more info and examples |VSwitch_vuetify_link|. .. |VSwitch_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-switch" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param background_color: Changes the background-color of the input :type string: :param color: See description |VSwitch_vuetify_link|. :type string: :param dark: See description |VSwitch_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param false_value: Sets value for falsy state :type any: :param flat: Display component without elevation. Default elevation for thumb is 4dp, `flat` resets it :type boolean: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param input_value: The **v-model** bound value :type any: :param inset: Enlarge the `v-switch` track to encompass the thumb :type boolean: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loading: Displays circular progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - primary, secondary, success, info, warning, error) or a Boolean which uses the component color (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param multiple: Changes expected model to an array :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param ripple: See description |VSwitch_vuetify_link|. :type ['boolean', 'object']: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param true_value: Sets value for truthy state :type any: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: :param value_comparator: Apply a custom value comparator function :type function: Events :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_prepend: Emitted when prepended icon is clicked :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-switch", children, **kwargs) self._attr_names += [ "append_icon", "background_color", "color", "dark", "dense", "disabled", "error", "error_count", "error_messages", "false_value", "flat", "hide_details", "hint", "id", "input_value", "inset", "label", "light", "loading", "messages", "multiple", "persistent_hint", "prepend_icon", "readonly", "ripple", "rules", "success", "success_messages", "true_value", "validate_on_blur", "value", "value_comparator", # JS functions unimplemented ] self._event_names += [ "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_prepend", "click:prepend"), # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ] class VSystemBar(AbstractElement): """ Vuetify's VSystemBar component. See more info and examples |VSystemBar_vuetify_link|. .. |VSystemBar_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-system-bar" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param app: See description |VSystemBar_vuetify_link|. :type boolean: :param color: See description |VSystemBar_vuetify_link|. :type string: :param dark: See description |VSystemBar_vuetify_link|. :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param height: Sets the height for the component. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param lights_out: Reduces the system bar opacity. :type boolean: :param window: Increases the system bar height to 32px (24px default). :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-system-bar", children, **kwargs) self._attr_names += [ "absolute", "app", "color", "dark", "fixed", "height", "light", "lights_out", "window", ] class VTabs(AbstractElement): """ Vuetify's VTabs component. See more info and examples |VTabs_vuetify_link|. .. |VTabs_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tabs" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param align_with_title: Make `v-tabs` lined up with the toolbar title :type boolean: :param background_color: Changes the background color of the component. :type string: :param center_active: Forces the selected tab to be centered :type boolean: :param centered: Centers the tabs :type boolean: :param color: See description |VTabs_vuetify_link|. :type string: :param dark: See description |VTabs_vuetify_link|. :type boolean: :param fixed_tabs: `v-tabs-item` min-width 160px, max-width 360px :type boolean: :param grow: Force `v-tab`'s to take up all available space :type boolean: :param height: Sets the height of the tabs bar :type ['number', 'string']: :param hide_slider: Hide's the generated `v-tabs-slider` :type boolean: :param icons_and_text: Will stack icon and text vertically :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mobile_breakpoint: Sets the designated mobile breakpoint for the component. :type ['string', 'number']: :param next_icon: Right pagination icon :type string: :param optional: Does not require an active item. Useful when using `v-tab` as a `router-link` :type boolean: :param prev_icon: Left pagination icon :type string: :param right: Aligns tabs to the right :type boolean: :param show_arrows: Show pagination arrows if the tab items overflow their container. For mobile devices, arrows will only display when using this prop. :type ['boolean', 'string']: :param slider_color: Changes the background color of an auto-generated `v-tabs-slider` :type string: :param slider_size: Changes the size of the slider, **height** for horizontal, **width** for vertical. :type ['number', 'string']: :param value: The designated model value for the component. :type any: :param vertical: Stacks tabs on top of each other vertically. :type boolean: Events :param change: Emitted when tab is changed by user interaction. Returns a string if **href** attribute is set and number if it is not. """ def __init__(self, children=None, **kwargs): super().__init__("v-tabs", children, **kwargs) self._attr_names += [ "active_class", "align_with_title", "background_color", "center_active", "centered", "color", "dark", "fixed_tabs", "grow", "height", "hide_slider", "icons_and_text", "light", "mobile_breakpoint", "next_icon", "optional", "prev_icon", "right", "show_arrows", "slider_color", "slider_size", "value", "vertical", ] self._event_names += [ "change", ] class VTab(AbstractElement): """ Vuetify's VTab component. See more info and examples |VTab_vuetify_link|. .. |VTab_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tab" target="_blank">here</a> :param active_class: See description |VTab_vuetify_link|. :type string: :param append: See description |VTab_vuetify_link|. :type boolean: :param dark: See description |VTab_vuetify_link|. :type boolean: :param disabled: Removes the ability to click or target the component. :type boolean: :param exact: See description |VTab_vuetify_link|. :type boolean: :param exact_active_class: See description |VTab_vuetify_link|. :type string: :param exact_path: See description |VTab_vuetify_link|. :type boolean: :param href: Designates the component as anchor and applies the **href** attribute. :type ['string', 'object']: :param light: Applies the light theme variant to the component. :type boolean: :param link: Designates that the component is a link. This is automatic when using the **href** or **to** prop. :type boolean: :param nuxt: See description |VTab_vuetify_link|. :type boolean: :param replace: See description |VTab_vuetify_link|. :type boolean: :param ripple: See description |VTab_vuetify_link|. :type ['boolean', 'object']: :param tag: Specify a custom tag used on the root element. :type string: :param target: Designates the target attribute. This should only be applied when using the **href** prop. :type string: :param to: See description |VTab_vuetify_link|. :type ['string', 'object']: Events :param change: Emitted when tab becomes active :param keydown: Emitted when **enter** key is pressed """ def __init__(self, children=None, **kwargs): super().__init__("v-tab", children, **kwargs) self._attr_names += [ "active_class", "append", "dark", "disabled", "exact", "exact_active_class", "exact_path", "href", "light", "link", "nuxt", "replace", "ripple", "tag", "target", "to", ] self._event_names += [ "change", # click, #Implemented in AbstractElement parent class "keydown", ] class VTabItem(AbstractElement): """ Vuetify's VTabItem component. See more info and examples |VTabItem_vuetify_link|. .. |VTabItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tab-item" target="_blank">here</a> :param active_class: See description |VTabItem_vuetify_link|. :type string: :param disabled: Removes the ability to click or target the component. :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param id: Sets the DOM id on the component :type string: :param reverse_transition: Sets the reverse transition :type ['boolean', 'string']: :param transition: See description |VTabItem_vuetify_link|. :type ['boolean', 'string']: :param value: Sets the value of the tab. If not provided, the index will be used. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-tab-item", children, **kwargs) self._attr_names += [ "active_class", "disabled", "eager", "id", "reverse_transition", "transition", "value", ] class VTabsItems(AbstractElement): """ Vuetify's VTabsItems component. See more info and examples |VTabsItems_vuetify_link|. .. |VTabsItems_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tabs-items" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param continuous: If `true`, window will "wrap around" from the last item to the first, and from the first item to the last :type boolean: :param dark: See description |VTabsItems_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param mandatory: Forces a value to always be selected (if available). :type boolean: :param max: Sets a maximum number of selections that can be made. :type ['number', 'string']: :param multiple: Allow multiple selections. The **value** prop must be an _array_. :type boolean: :param next_icon: Icon used for the "next" button if `show-arrows` is `true` :type ['boolean', 'string']: :param prev_icon: Icon used for the "prev" button if `show-arrows` is `true` :type ['boolean', 'string']: :param reverse: Reverse the normal transition direction. :type boolean: :param show_arrows: Display the "next" and "prev" buttons :type boolean: :param show_arrows_on_hover: Display the "next" and "prev" buttons on hover. `show-arrows` MUST ALSO be set. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param touch: Provide a custom **left** and **right** function when swiped left or right. :type object: :param touchless: Disable touch support. :type boolean: :param value: The designated model value for the component. :type any: :param vertical: Uses a vertical transition when changing windows. :type boolean: Events :param change: Emitted when user swipes between tabs. """ def __init__(self, children=None, **kwargs): super().__init__("v-tabs-items", children, **kwargs) self._attr_names += [ "active_class", "continuous", "dark", "light", "mandatory", "max", "multiple", "next_icon", "prev_icon", "reverse", "show_arrows", "show_arrows_on_hover", "tag", "touch", "touchless", "value", "vertical", ] self._event_names += [ "change", ] class VTabsSlider(AbstractElement): """ Vuetify's VTabsSlider component. See more info and examples |VTabsSlider_vuetify_link|. .. |VTabsSlider_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tabs-slider" target="_blank">here</a> :param color: See description |VTabsSlider_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-tabs-slider", children, **kwargs) self._attr_names += [ "color", ] class VTextarea(AbstractElement): """ Vuetify's VTextarea component. See more info and examples |VTextarea_vuetify_link|. .. |VTextarea_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-textarea" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param append_outer_icon: Appends an icon to the outside the component's input, uses same syntax as `v-icon` :type string: :param auto_grow: Automatically grow the textarea depending on amount of text :type boolean: :param autofocus: Enables autofocus :type boolean: :param background_color: Changes the background-color of the input :type string: :param clear_icon: Applied when using **clearable** and the input is dirty :type string: :param clearable: Add input clear functionality, default icon is Material Design Icons **mdi-clear** :type boolean: :param color: See description |VTextarea_vuetify_link|. :type string: :param counter: Creates counter for input length; if no number is specified, it defaults to 25. Does not apply any validation. :type ['boolean', 'number', 'string']: :param counter_value: :type function: :param dark: See description |VTextarea_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param filled: Applies the alternate filled input style :type boolean: :param flat: Removes elevation (shadow) added to element when using the **solo** or **solo-inverted** props :type boolean: :param full_width: Designates input type as full-width :type boolean: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param no_resize: Remove resize handle :type boolean: :param outlined: Applies the outlined style to the input :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param persistent_placeholder: Forces placeholder to always be visible :type boolean: :param placeholder: Sets the input's placeholder text :type string: :param prefix: Displays prefix text :type string: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param prepend_inner_icon: Prepends an icon inside the component's input, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param reverse: Reverses the input orientation :type boolean: :param rounded: Adds a border radius to the input :type boolean: :param row_height: Height value for each row. Requires the use of the **auto-grow** prop. :type ['number', 'string']: :param rows: Default row count :type ['number', 'string']: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param shaped: Round if `outlined` and increase `border-radius` if `filled`. Must be used with either `outlined` or `filled` :type boolean: :param single_line: Label does not move on focus/dirty :type boolean: :param solo: Changes the style of the input :type boolean: :param solo_inverted: Reduces element opacity until focused :type boolean: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param suffix: Displays suffix text :type string: :param type: Sets input type :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: Events :param blur: Emitted when the input is blurred :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_append_outer: Emitted when appended outer icon is clicked :param click_clear: Emitted when clearable icon clicked :param click_prepend: Emitted when prepended icon is clicked :param click_prepend_inner: Emitted when prepended inner icon is clicked :param focus: Emitted when component is focused :param input: The updated bound model :param keydown: Emitted when **any** key is pressed :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-textarea", children, **kwargs) self._attr_names += [ "append_icon", "append_outer_icon", "auto_grow", "autofocus", "background_color", "clear_icon", "clearable", "color", "counter", "counter_value", # JS functions unimplemented "dark", "dense", "disabled", "error", "error_count", "error_messages", "filled", "flat", "full_width", "height", "hide_details", "hint", "id", "label", "light", "loader_height", "loading", "messages", "no_resize", "outlined", "persistent_hint", "persistent_placeholder", "placeholder", "prefix", "prepend_icon", "prepend_inner_icon", "readonly", "reverse", "rounded", "row_height", "rows", "rules", "shaped", "single_line", "solo", "solo_inverted", "success", "success_messages", "suffix", "type", "validate_on_blur", "value", ] self._event_names += [ "blur", "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_append_outer", "click:append-outer"), ("click_clear", "click:clear"), ("click_prepend", "click:prepend"), ("click_prepend_inner", "click:prepend-inner"), "focus", "input", "keydown", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ] class VTextField(AbstractElement): """ Vuetify's VTextField component. See more info and examples |VTextField_vuetify_link|. .. |VTextField_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-text-field" target="_blank">here</a> :param append_icon: Appends an icon to the component, uses the same syntax as `v-icon` :type string: :param append_outer_icon: Appends an icon to the outside the component's input, uses same syntax as `v-icon` :type string: :param autofocus: Enables autofocus :type boolean: :param background_color: Changes the background-color of the input :type string: :param clear_icon: Applied when using **clearable** and the input is dirty :type string: :param clearable: Add input clear functionality, default icon is Material Design Icons **mdi-clear** :type boolean: :param color: See description |VTextField_vuetify_link|. :type string: :param counter: Creates counter for input length; if no number is specified, it defaults to 25. Does not apply any validation. :type ['boolean', 'number', 'string']: :param counter_value: :type function: :param dark: See description |VTextField_vuetify_link|. :type boolean: :param dense: Reduces the input height :type boolean: :param disabled: Disable the input :type boolean: :param error: Puts the input in a manual error state :type boolean: :param error_count: The total number of errors that should display at once :type ['number', 'string']: :param error_messages: Puts the input in an error state and passes through custom error messages. Will be combined with any validations that occur from the **rules** prop. This field will not trigger validation :type ['string', 'array']: :param filled: Applies the alternate filled input style :type boolean: :param flat: Removes elevation (shadow) added to element when using the **solo** or **solo-inverted** props :type boolean: :param full_width: Designates input type as full-width :type boolean: :param height: Sets the height of the input :type ['number', 'string']: :param hide_details: Hides hint and validation errors. When set to `auto` messages will be rendered only if there's a message (hint, error message, counter value etc) to display :type ['boolean', 'string']: :param hint: Hint text :type string: :param id: Sets the DOM id on the component :type string: :param label: Sets input label :type string: :param light: Applies the light theme variant to the component. :type boolean: :param loader_height: Specifies the height of the loader :type ['number', 'string']: :param loading: Displays linear progress bar. Can either be a String which specifies which color is applied to the progress bar (any material color or theme color - **primary**, **secondary**, **success**, **info**, **warning**, **error**) or a Boolean which uses the component **color** (set by color prop - if it's supported by the component) or the primary color :type ['boolean', 'string']: :param messages: Displays a list of messages or message if using a string :type ['string', 'array']: :param outlined: Applies the outlined style to the input :type boolean: :param persistent_hint: Forces hint to always be visible :type boolean: :param persistent_placeholder: Forces placeholder to always be visible :type boolean: :param placeholder: Sets the input’s placeholder text :type string: :param prefix: Displays prefix text :type string: :param prepend_icon: Prepends an icon to the component, uses the same syntax as `v-icon` :type string: :param prepend_inner_icon: Prepends an icon inside the component's input, uses the same syntax as `v-icon` :type string: :param readonly: Puts input in readonly state :type boolean: :param reverse: Reverses the input orientation :type boolean: :param rounded: Adds a border radius to the input :type boolean: :param rules: Accepts a mixed array of types `function`, `boolean` and `string`. Functions pass an input value as an argument and must return either `true` / `false` or a `string` containing an error message. The input field will enter an error state if a function returns (or any value in the array contains) `false` or is a `string` :type array: :param shaped: Round if `outlined` and increase `border-radius` if `filled`. Must be used with either `outlined` or `filled` :type boolean: :param single_line: Label does not move on focus/dirty :type boolean: :param solo: Changes the style of the input :type boolean: :param solo_inverted: Reduces element opacity until focused :type boolean: :param success: Puts the input in a manual success state :type boolean: :param success_messages: Puts the input in a success state and passes through custom success messages. :type ['string', 'array']: :param suffix: Displays suffix text :type string: :param type: Sets input type :type string: :param validate_on_blur: Delays validation until blur event :type boolean: :param value: The input's value :type any: Events :param blur: Emitted when the input is blurred :param change: Emitted when the input is changed by user interaction :param click_append: Emitted when appended icon is clicked :param click_append_outer: Emitted when appended outer icon is clicked :param click_clear: Emitted when clearable icon clicked :param click_prepend: Emitted when prepended icon is clicked :param click_prepend_inner: Emitted when prepended inner icon is clicked :param focus: Emitted when component is focused :param input: The updated bound model :param keydown: Emitted when **any** key is pressed :param update_error: The `error.sync` event """ def __init__(self, children=None, **kwargs): super().__init__("v-text-field", children, **kwargs) self._attr_names += [ "append_icon", "append_outer_icon", "autofocus", "background_color", "clear_icon", "clearable", "color", "counter", "counter_value", # JS functions unimplemented "dark", "dense", "disabled", "error", "error_count", "error_messages", "filled", "flat", "full_width", "height", "hide_details", "hint", "id", "label", "light", "loader_height", "loading", "messages", "outlined", "persistent_hint", "persistent_placeholder", "placeholder", "prefix", "prepend_icon", "prepend_inner_icon", "readonly", "reverse", "rounded", "rules", "shaped", "single_line", "solo", "solo_inverted", "success", "success_messages", "suffix", "type", "validate_on_blur", "value", ] self._event_names += [ "blur", "change", # click, #Implemented in AbstractElement parent class ("click_append", "click:append"), ("click_append_outer", "click:append-outer"), ("click_clear", "click:clear"), ("click_prepend", "click:prepend"), ("click_prepend_inner", "click:prepend-inner"), "focus", "input", "keydown", # mousedown, #Implemented in AbstractElement parent class # mouseup, #Implemented in AbstractElement parent class ("update_error", "update:error"), ] class VThemeProvider(AbstractElement): """ Vuetify's VThemeProvider component. See more info and examples |VThemeProvider_vuetify_link|. .. |VThemeProvider_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-theme-provider" target="_blank">here</a> :param dark: See description |VThemeProvider_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param root: Use the current value of `$vuetify.theme.dark` as opposed to the provided one. :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-theme-provider", children, **kwargs) self._attr_names += [ "dark", "light", "root", ] class VTimeline(AbstractElement): """ Vuetify's VTimeline component. See more info and examples |VTimeline_vuetify_link|. .. |VTimeline_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-timeline" target="_blank">here</a> :param align_top: Align caret and dot of timeline items to the top :type boolean: :param dark: See description |VTimeline_vuetify_link|. :type boolean: :param dense: Hide opposite slot content, and position all items to one side of timeline :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param reverse: Reverse direction of timeline items :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-timeline", children, **kwargs) self._attr_names += [ "align_top", "dark", "dense", "light", "reverse", ] class VTimelineItem(AbstractElement): """ Vuetify's VTimelineItem component. See more info and examples |VTimelineItem_vuetify_link|. .. |VTimelineItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-timeline-item" target="_blank">here</a> :param color: See description |VTimelineItem_vuetify_link|. :type string: :param dark: See description |VTimelineItem_vuetify_link|. :type boolean: :param fill_dot: Remove padding from dot container :type boolean: :param hide_dot: Hide display of timeline dot :type boolean: :param icon: Specify icon for dot container :type string: :param icon_color: See description |VTimelineItem_vuetify_link|. :type string: :param large: Large size dot :type boolean: :param left: Explicitly set the item to a left orientation :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param right: Explicitly set the item to a right orientation :type boolean: :param small: Small size dot :type boolean: """ def __init__(self, children=None, **kwargs): super().__init__("v-timeline-item", children, **kwargs) self._attr_names += [ "color", "dark", "fill_dot", "hide_dot", "icon", "icon_color", "large", "left", "light", "right", "small", ] class VTimePicker(AbstractElement): """ Vuetify's VTimePicker component. See more info and examples |VTimePicker_vuetify_link|. .. |VTimePicker_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-time-picker" target="_blank">here</a> :param allowed_hours: Restricts which hours can be selected :type ['function', 'array']: :param allowed_minutes: Restricts which minutes can be selected :type ['function', 'array']: :param allowed_seconds: Restricts which seconds can be selected :type ['function', 'array']: :param ampm_in_title: Place AM/PM switch in title, not near the clock. :type boolean: :param color: See description |VTimePicker_vuetify_link|. :type string: :param dark: See description |VTimePicker_vuetify_link|. :type boolean: :param disabled: disables picker :type boolean: :param elevation: See description |VTimePicker_vuetify_link|. :type ['number', 'string']: :param flat: Removes elevation :type boolean: :param format: Defines the format of a time displayed in picker. Available options are `ampm` and `24hr`. :type string: :param full_width: Forces 100% width :type boolean: :param header_color: Defines the header color. If not specified it will use the color defined by <code>color</code> prop or the default picker color :type string: :param landscape: Orients picker horizontal :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param max: Maximum allowed time :type string: :param min: Minimum allowed time :type string: :param no_title: Hide the picker title :type boolean: :param readonly: Puts picker in readonly state :type boolean: :param scrollable: Allows changing hour/minute with mouse scroll :type boolean: :param use_seconds: Toggles the use of seconds in picker :type boolean: :param value: Time picker model (ISO 8601 format, 24hr hh:mm) :type any: :param width: Width of the picker :type ['number', 'string']: Events :param change: Emitted when the time selection is done (when user changes the minute for HH:MM picker and the second for HH:MM:SS picker :param click_hour: Emitted when user selects the hour :param click_minute: Emitted when user selects the minute :param click_second: Emitted when user selects the second :param input: The updated bound model :param update_period: Emitted when user clicks the AM/PM button """ def __init__(self, children=None, **kwargs): super().__init__("v-time-picker", children, **kwargs) self._attr_names += [ "allowed_hours", # JS functions unimplemented "allowed_minutes", # JS functions unimplemented "allowed_seconds", # JS functions unimplemented "ampm_in_title", "color", "dark", "disabled", "elevation", "flat", "format", "full_width", "header_color", "landscape", "light", "max", "min", "no_title", "readonly", "scrollable", "use_seconds", "value", "width", ] self._event_names += [ "change", ("click_hour", "click:hour"), ("click_minute", "click:minute"), ("click_second", "click:second"), "input", ("update_period", "update:period"), ] class VToolbar(AbstractElement): """ Vuetify's VToolbar component. See more info and examples |VToolbar_vuetify_link|. .. |VToolbar_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-toolbar" target="_blank">here</a> :param absolute: Applies position: absolute to the component. :type boolean: :param bottom: Aligns the component towards the bottom. :type boolean: :param collapse: Puts the toolbar into a collapsed state reducing its maximum width. :type boolean: :param color: See description |VToolbar_vuetify_link|. :type string: :param dark: See description |VToolbar_vuetify_link|. :type boolean: :param dense: Reduces the height of the toolbar content to 48px (96px when using the **prominent** prop). :type boolean: :param elevation: See description |VToolbar_vuetify_link|. :type ['number', 'string']: :param extended: Use this prop to increase the height of the toolbar _without_ using the `extension` slot for adding content. May be used in conjunction with the **extension-height** prop, and any of the other props that affect the height of the toolbar, e.g. **prominent**, **dense**, etc., **WITH THE EXCEPTION** of **height**. :type boolean: :param extension_height: Specify an explicit height for the `extension` slot. :type ['number', 'string']: :param flat: Removes the toolbar's box-shadow. :type boolean: :param floating: Applies **display: inline-flex** to the component. :type boolean: :param height: Designates a specific height for the toolbar. Overrides the heights imposed by other props, e.g. **prominent**, **dense**, **extended**, etc. :type ['number', 'string']: :param light: Applies the light theme variant to the component. :type boolean: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param outlined: Removes elevation (box-shadow) and adds a *thin* border. :type boolean: :param prominent: Increases the height of the toolbar content to 128px. :type boolean: :param rounded: See description |VToolbar_vuetify_link|. :type ['boolean', 'string']: :param shaped: Applies a large border radius on the top left and bottom right of the card. :type boolean: :param short: Reduce the height of the toolbar content to 56px (112px when using the **prominent** prop). :type boolean: :param src: See description |VToolbar_vuetify_link|. :type ['string', 'object']: :param tag: Specify a custom tag used on the root element. :type string: :param tile: Removes the component's **border-radius**. :type boolean: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-toolbar", children, **kwargs) self._attr_names += [ "absolute", "bottom", "collapse", "color", "dark", "dense", "elevation", "extended", "extension_height", "flat", "floating", "height", "light", "max_height", "max_width", "min_height", "min_width", "outlined", "prominent", "rounded", "shaped", "short", "src", "tag", "tile", "width", ] class VToolbarItems(AbstractElement): """ Vuetify's VToolbarItems component. See more info and examples |VToolbarItems_vuetify_link|. .. |VToolbarItems_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-toolbar-items" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-toolbar-items", children, **kwargs) class VToolbarTitle(AbstractElement): """ Vuetify's VToolbarTitle component. See more info and examples |VToolbarTitle_vuetify_link|. .. |VToolbarTitle_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-toolbar-title" target="_blank">here</a> """ def __init__(self, children=None, **kwargs): super().__init__("v-toolbar-title", children, **kwargs) class VTooltip(AbstractElement): """ Vuetify's VTooltip component. See more info and examples |VTooltip_vuetify_link|. .. |VTooltip_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tooltip" target="_blank">here</a> :param absolute: Applies **position: absolute** to the component. :type boolean: :param activator: Designate a custom activator when the `activator` slot is not used. String can be any valid querySelector and Object can be any valid Node. :type any: :param allow_overflow: Removes overflow re-positioning for the content :type boolean: :param attach: Specifies which DOM element that this component should detach to. String can be any valid querySelector and Object can be any valid Node. This will attach to the root `v-app` component by default. :type any: :param bottom: Aligns the component towards the bottom. :type boolean: :param close_delay: Delay (in ms) after which menu closes (when open-on-hover prop is set to true) :type ['number', 'string']: :param color: See description |VTooltip_vuetify_link|. :type string: :param content_class: Applies a custom class to the detached element. This is useful because the content is moved to the beginning of the `v-app` component (unless the **attach** prop is provided) and is not targetable by classes passed directly on the component. :type string: :param disabled: Disables the tooltip :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param fixed: Applies **position: fixed** to the component. :type boolean: :param internal_activator: Designates whether to use an internal activator :type boolean: :param left: Aligns the component towards the left. :type boolean: :param max_width: Sets the maximum width for the content :type ['number', 'string']: :param min_width: Sets the minimum width for the content :type ['number', 'string']: :param nudge_bottom: Nudge the content to the bottom :type ['number', 'string']: :param nudge_left: Nudge the content to the left :type ['number', 'string']: :param nudge_right: Nudge the content to the right :type ['number', 'string']: :param nudge_top: Nudge the content to the top :type ['number', 'string']: :param nudge_width: Nudge the content width :type ['number', 'string']: :param offset_overflow: Causes the component to flip to the opposite side when repositioned due to overflow :type boolean: :param open_delay: Delay (in ms) after which tooltip opens (when `open-on-hover` prop is set to **true**) :type ['number', 'string']: :param open_on_click: Designates whether the tooltip should open on activator click :type boolean: :param open_on_focus: :type boolean: :param open_on_hover: Designates whether the tooltip should open on activator hover :type boolean: :param position_x: Used to position the content when not using an activator slot :type number: :param position_y: Used to position the content when not using an activator slot :type number: :param right: Aligns the component towards the right. :type boolean: :param tag: Specifies a custom tag for the activator wrapper :type string: :param top: Aligns the content towards the top. :type boolean: :param transition: See description |VTooltip_vuetify_link|. :type string: :param value: Controls whether the component is visible or hidden. :type any: :param z_index: The z-index used for the component :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-tooltip", children, **kwargs) self._attr_names += [ "absolute", "activator", "allow_overflow", "attach", "bottom", "close_delay", "color", "content_class", "disabled", "eager", "fixed", "internal_activator", "left", "max_width", "min_width", "nudge_bottom", "nudge_left", "nudge_right", "nudge_top", "nudge_width", "offset_overflow", "open_delay", "open_on_click", "open_on_focus", "open_on_hover", "position_x", "position_y", "right", "tag", "top", "transition", "value", "z_index", ] class VTreeview(AbstractElement): """ Vuetify's VTreeview component. See more info and examples |VTreeview_vuetify_link|. .. |VTreeview_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-treeview" target="_blank">here</a> :param activatable: Allows user to mark a node as active by clicking on it :type boolean: :param active: Syncable prop that allows one to control which nodes are active. The array consists of the `item-key` of each active item. :type array: :param active_class: The class applied to the node when active :type string: :param color: Sets the color of the active node :type string: :param dark: See description |VTreeview_vuetify_link|. :type boolean: :param dense: Decreases the height of the items :type boolean: :param expand_icon: Icon used to indicate that a node can be expanded :type string: :param filter: Custom item filtering function. By default it will use case-insensitive search in item's label. :type function: :param hoverable: Applies a hover class when mousing over nodes :type boolean: :param indeterminate_icon: Icon used when node is in an indeterminate state. Only visible when `selectable` is `true`. :type string: :param item_children: Property on supplied `items` that contains its children :type string: :param item_disabled: Property on supplied `items` that contains the disabled state of the item :type string: :param item_key: Property on supplied `items` used to keep track of node state. The value of this property has to be unique among all items. :type string: :param item_text: Property on supplied `items` that contains its label text :type string: :param items: An array of items used to build the treeview :type array: :param light: Applies the light theme variant to the component. :type boolean: :param load_children: A function used when dynamically loading children. If this prop is set, then the supplied function will be run if expanding an item that has a `item-children` property that is an empty array. Supports returning a Promise. :type function: :param loading_icon: Icon used when node is in a loading state :type string: :param multiple_active: When `true`, allows user to have multiple active nodes at the same time :type boolean: :param off_icon: Icon used when node is not selected. Only visible when `selectable` is `true`. :type string: :param on_icon: Icon used when leaf node is selected or when a branch node is fully selected. Only visible when `selectable` is `true`. :type string: :param open: Syncable prop that allows one to control which nodes are open. The array consists of the `item-key` of each open item. :type array: :param open_all: When `true` will cause all branch nodes to be opened when component is mounted :type boolean: :param open_on_click: When `true` will cause nodes to be opened by clicking anywhere on it, instead of only opening by clicking on expand icon. When using this prop with `activatable` you will be unable to mark nodes with children as active. :type boolean: :param return_object: When `true` will make `v-model`, `active.sync` and `open.sync` return the complete object instead of just the key :type boolean: :param rounded: Provides an alternative active style for `v-treeview` node. Only visible when `activatable` is `true` and should not be used in conjunction with the `shaped` prop. :type boolean: :param search: The search model for filtering results :type string: :param selectable: Will render a checkbox next to each node allowing them to be selected :type boolean: :param selected_color: The color of the selection checkbox :type string: :param selection_type: Controls how the treeview selects nodes. There are two modes available: 'leaf' and 'independent' :type string: :param shaped: Provides an alternative active style for `v-treeview` node. Only visible when `activatable` is `true` and should not be used in conjunction with the `rounded` prop. :type boolean: :param transition: Applies a transition when nodes are opened and closed :type boolean: :param value: Allows one to control which nodes are selected. The array consists of the `item-key` of each selected item. Is used with `@input` event to allow for `v-model` binding. :type array: Events :param input: Emits the array of selected items when this value changes :param update_active: Emits the array of active items when this value changes :param update_open: Emits the array of open items when this value changes """ def __init__(self, children=None, **kwargs): super().__init__("v-treeview", children, **kwargs) self._attr_names += [ "activatable", "active", "active_class", "color", "dark", "dense", "expand_icon", "filter", # JS functions unimplemented "hoverable", "indeterminate_icon", "item_children", "item_disabled", "item_key", "item_text", "items", "light", "load_children", # JS functions unimplemented "loading_icon", "multiple_active", "off_icon", "on_icon", "open", "open_all", "open_on_click", "return_object", "rounded", "search", "selectable", "selected_color", "selection_type", "shaped", "transition", "value", ] self._event_names += [ "input", ("update_active", "update:active"), ("update_open", "update:open"), ] class VVirtualScroll(AbstractElement): """ Vuetify's VVirtualScroll component. See more info and examples |VVirtualScroll_vuetify_link|. .. |VVirtualScroll_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-virtual-scroll" target="_blank">here</a> :param bench: The number of items **outside** the user view that are rendered (even if they are **not** viewable); to help prevent empty white space when scrolling *fast*. :type ['number', 'string']: :param height: Height of the component as a css value :type ['number', 'string']: :param item_height: Height in pixels of the items to display :type ['number', 'string']: :param items: The array of items to display :type array: :param max_height: Sets the maximum height for the component. :type ['number', 'string']: :param max_width: Sets the maximum width for the component. :type ['number', 'string']: :param min_height: Sets the minimum height for the component. :type ['number', 'string']: :param min_width: Sets the minimum width for the component. :type ['number', 'string']: :param width: Sets the width for the component. :type ['number', 'string']: """ def __init__(self, children=None, **kwargs): super().__init__("v-virtual-scroll", children, **kwargs) self._attr_names += [ "bench", "height", "item_height", "items", "max_height", "max_width", "min_height", "min_width", "width", ] class VWindow(AbstractElement): """ Vuetify's VWindow component. See more info and examples |VWindow_vuetify_link|. .. |VWindow_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-window" target="_blank">here</a> :param active_class: The **active-class** applied to children when they are activated. :type string: :param continuous: If `true`, window will "wrap around" from the last item to the first, and from the first item to the last :type boolean: :param dark: See description |VWindow_vuetify_link|. :type boolean: :param light: Applies the light theme variant to the component. :type boolean: :param next_icon: Icon used for the "next" button if `show-arrows` is `true` :type ['boolean', 'string']: :param prev_icon: Icon used for the "prev" button if `show-arrows` is `true` :type ['boolean', 'string']: :param reverse: Reverse the normal transition direction. :type boolean: :param show_arrows: Display the "next" and "prev" buttons :type boolean: :param show_arrows_on_hover: Display the "next" and "prev" buttons on hover. `show-arrows` MUST ALSO be set. :type boolean: :param tag: Specify a custom tag used on the root element. :type string: :param touch: Provide a custom **left** and **right** function when swiped left or right. :type object: :param touchless: Disable touch support. :type boolean: :param value: The designated model value for the component. :type any: :param vertical: Uses a vertical transition when changing windows. :type boolean: Events :param change: Emitted when the component value is changed by user interaction """ def __init__(self, children=None, **kwargs): super().__init__("v-window", children, **kwargs) self._attr_names += [ "active_class", "continuous", "dark", "light", "next_icon", "prev_icon", "reverse", "show_arrows", "show_arrows_on_hover", "tag", "touch", "touchless", "value", "vertical", ] self._event_names += [ "change", ] class VWindowItem(AbstractElement): """ Vuetify's VWindowItem component. See more info and examples |VWindowItem_vuetify_link|. .. |VWindowItem_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-window-item" target="_blank">here</a> :param active_class: See description |VWindowItem_vuetify_link|. :type string: :param disabled: Prevents the item from becoming active when using the "next" and "prev" buttons or the `toggle` method :type boolean: :param eager: Will force the components content to render on mounted. This is useful if you have content that will not be rendered in the DOM that you want crawled for SEO. :type boolean: :param reverse_transition: Sets the reverse transition :type ['boolean', 'string']: :param transition: See description |VWindowItem_vuetify_link|. :type ['boolean', 'string']: :param value: The value used when the component is selected in a group. If not provided, the index will be used. :type any: """ def __init__(self, children=None, **kwargs): super().__init__("v-window-item", children, **kwargs) self._attr_names += [ "active_class", "disabled", "eager", "reverse_transition", "transition", "value", ] class VCarouselTransition(AbstractElement): """ Vuetify's VCarouselTransition component. See more info and examples |VCarouselTransition_vuetify_link|. .. |VCarouselTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-carousel-transition" target="_blank">here</a> :param group: See description |VCarouselTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VCarouselTransition_vuetify_link|. :type boolean: :param mode: See description |VCarouselTransition_vuetify_link|. :type string: :param origin: See description |VCarouselTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-carousel-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VCarouselReverseTransition(AbstractElement): """ Vuetify's VCarouselReverseTransition component. See more info and examples |VCarouselReverseTransition_vuetify_link|. .. |VCarouselReverseTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-carousel-reverse-transition" target="_blank">here</a> :param group: See description |VCarouselReverseTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VCarouselReverseTransition_vuetify_link|. :type boolean: :param mode: See description |VCarouselReverseTransition_vuetify_link|. :type string: :param origin: See description |VCarouselReverseTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-carousel-reverse-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VTabTransition(AbstractElement): """ Vuetify's VTabTransition component. See more info and examples |VTabTransition_vuetify_link|. .. |VTabTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tab-transition" target="_blank">here</a> :param group: See description |VTabTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VTabTransition_vuetify_link|. :type boolean: :param mode: See description |VTabTransition_vuetify_link|. :type string: :param origin: See description |VTabTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-tab-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VTabReverseTransition(AbstractElement): """ Vuetify's VTabReverseTransition component. See more info and examples |VTabReverseTransition_vuetify_link|. .. |VTabReverseTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-tab-reverse-transition" target="_blank">here</a> :param group: See description |VTabReverseTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VTabReverseTransition_vuetify_link|. :type boolean: :param mode: See description |VTabReverseTransition_vuetify_link|. :type string: :param origin: See description |VTabReverseTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-tab-reverse-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VMenuTransition(AbstractElement): """ Vuetify's VMenuTransition component. See more info and examples |VMenuTransition_vuetify_link|. .. |VMenuTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-menu-transition" target="_blank">here</a> :param group: See description |VMenuTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VMenuTransition_vuetify_link|. :type boolean: :param mode: See description |VMenuTransition_vuetify_link|. :type string: :param origin: See description |VMenuTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-menu-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VFabTransition(AbstractElement): """ Vuetify's VFabTransition component. See more info and examples |VFabTransition_vuetify_link|. .. |VFabTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-fab-transition" target="_blank">here</a> :param group: See description |VFabTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VFabTransition_vuetify_link|. :type boolean: :param mode: See description |VFabTransition_vuetify_link|. :type string: :param origin: See description |VFabTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-fab-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VDialogTransition(AbstractElement): """ Vuetify's VDialogTransition component. See more info and examples |VDialogTransition_vuetify_link|. .. |VDialogTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-dialog-transition" target="_blank">here</a> :param group: See description |VDialogTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VDialogTransition_vuetify_link|. :type boolean: :param mode: See description |VDialogTransition_vuetify_link|. :type string: :param origin: See description |VDialogTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-dialog-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VDialogBottomTransition(AbstractElement): """ Vuetify's VDialogBottomTransition component. See more info and examples |VDialogBottomTransition_vuetify_link|. .. |VDialogBottomTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-dialog-bottom-transition" target="_blank">here</a> :param group: See description |VDialogBottomTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VDialogBottomTransition_vuetify_link|. :type boolean: :param mode: See description |VDialogBottomTransition_vuetify_link|. :type string: :param origin: See description |VDialogBottomTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-dialog-bottom-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VDialogTopTransition(AbstractElement): """ Vuetify's VDialogTopTransition component. See more info and examples |VDialogTopTransition_vuetify_link|. .. |VDialogTopTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-dialog-top-transition" target="_blank">here</a> :param group: See description |VDialogTopTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VDialogTopTransition_vuetify_link|. :type boolean: :param mode: See description |VDialogTopTransition_vuetify_link|. :type string: :param origin: See description |VDialogTopTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-dialog-top-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VFadeTransition(AbstractElement): """ Vuetify's VFadeTransition component. See more info and examples |VFadeTransition_vuetify_link|. .. |VFadeTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-fade-transition" target="_blank">here</a> :param group: See description |VFadeTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VFadeTransition_vuetify_link|. :type boolean: :param mode: See description |VFadeTransition_vuetify_link|. :type string: :param origin: See description |VFadeTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-fade-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VScaleTransition(AbstractElement): """ Vuetify's VScaleTransition component. See more info and examples |VScaleTransition_vuetify_link|. .. |VScaleTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-scale-transition" target="_blank">here</a> :param group: See description |VScaleTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VScaleTransition_vuetify_link|. :type boolean: :param mode: See description |VScaleTransition_vuetify_link|. :type string: :param origin: See description |VScaleTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-scale-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VScrollXTransition(AbstractElement): """ Vuetify's VScrollXTransition component. See more info and examples |VScrollXTransition_vuetify_link|. .. |VScrollXTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-scroll-x-transition" target="_blank">here</a> :param group: See description |VScrollXTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VScrollXTransition_vuetify_link|. :type boolean: :param mode: See description |VScrollXTransition_vuetify_link|. :type string: :param origin: See description |VScrollXTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-scroll-x-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VScrollXReverseTransition(AbstractElement): """ Vuetify's VScrollXReverseTransition component. See more info and examples |VScrollXReverseTransition_vuetify_link|. .. |VScrollXReverseTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-scroll-x-reverse-transition" target="_blank">here</a> :param group: See description |VScrollXReverseTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VScrollXReverseTransition_vuetify_link|. :type boolean: :param mode: See description |VScrollXReverseTransition_vuetify_link|. :type string: :param origin: See description |VScrollXReverseTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-scroll-x-reverse-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VScrollYTransition(AbstractElement): """ Vuetify's VScrollYTransition component. See more info and examples |VScrollYTransition_vuetify_link|. .. |VScrollYTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-scroll-y-transition" target="_blank">here</a> :param group: See description |VScrollYTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VScrollYTransition_vuetify_link|. :type boolean: :param mode: See description |VScrollYTransition_vuetify_link|. :type string: :param origin: See description |VScrollYTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-scroll-y-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VScrollYReverseTransition(AbstractElement): """ Vuetify's VScrollYReverseTransition component. See more info and examples |VScrollYReverseTransition_vuetify_link|. .. |VScrollYReverseTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-scroll-y-reverse-transition" target="_blank">here</a> :param group: See description |VScrollYReverseTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VScrollYReverseTransition_vuetify_link|. :type boolean: :param mode: See description |VScrollYReverseTransition_vuetify_link|. :type string: :param origin: See description |VScrollYReverseTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-scroll-y-reverse-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VSlideXTransition(AbstractElement): """ Vuetify's VSlideXTransition component. See more info and examples |VSlideXTransition_vuetify_link|. .. |VSlideXTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-slide-x-transition" target="_blank">here</a> :param group: See description |VSlideXTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VSlideXTransition_vuetify_link|. :type boolean: :param mode: See description |VSlideXTransition_vuetify_link|. :type string: :param origin: See description |VSlideXTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-slide-x-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VSlideXReverseTransition(AbstractElement): """ Vuetify's VSlideXReverseTransition component. See more info and examples |VSlideXReverseTransition_vuetify_link|. .. |VSlideXReverseTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-slide-x-reverse-transition" target="_blank">here</a> :param group: See description |VSlideXReverseTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VSlideXReverseTransition_vuetify_link|. :type boolean: :param mode: See description |VSlideXReverseTransition_vuetify_link|. :type string: :param origin: See description |VSlideXReverseTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-slide-x-reverse-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VSlideYTransition(AbstractElement): """ Vuetify's VSlideYTransition component. See more info and examples |VSlideYTransition_vuetify_link|. .. |VSlideYTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-slide-y-transition" target="_blank">here</a> :param group: See description |VSlideYTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VSlideYTransition_vuetify_link|. :type boolean: :param mode: See description |VSlideYTransition_vuetify_link|. :type string: :param origin: See description |VSlideYTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-slide-y-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VSlideYReverseTransition(AbstractElement): """ Vuetify's VSlideYReverseTransition component. See more info and examples |VSlideYReverseTransition_vuetify_link|. .. |VSlideYReverseTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-slide-y-reverse-transition" target="_blank">here</a> :param group: See description |VSlideYReverseTransition_vuetify_link|. :type boolean: :param hide_on_leave: Hides the leaving element (no exit animation) :type boolean: :param leave_absolute: See description |VSlideYReverseTransition_vuetify_link|. :type boolean: :param mode: See description |VSlideYReverseTransition_vuetify_link|. :type string: :param origin: See description |VSlideYReverseTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-slide-y-reverse-transition", children, **kwargs) self._attr_names += [ "group", "hide_on_leave", "leave_absolute", "mode", "origin", ] class VExpandTransition(AbstractElement): """ Vuetify's VExpandTransition component. See more info and examples |VExpandTransition_vuetify_link|. .. |VExpandTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-expand-transition" target="_blank">here</a> :param mode: See description |VExpandTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-expand-transition", children, **kwargs) self._attr_names += [ "mode", ] class VExpandXTransition(AbstractElement): """ Vuetify's VExpandXTransition component. See more info and examples |VExpandXTransition_vuetify_link|. .. |VExpandXTransition_vuetify_link| raw:: html <a href="https://vuetifyjs.com/api/v-expand-x-transition" target="_blank">here</a> :param mode: See description |VExpandXTransition_vuetify_link|. :type string: """ def __init__(self, children=None, **kwargs): super().__init__("v-expand-x-transition", children, **kwargs) self._attr_names += [ "mode", ]
[ "trame.get_app_instance", "trame.html.Template.slot_names.update", "numpy.isinf", "numpy.isnan" ]
[((241, 259), 'trame.get_app_instance', 'get_app_instance', ([], {}), '()\n', (257, 259), False, 'from trame import get_app_instance\n'), ((3125, 3163), 'trame.html.Template.slot_names.update', 'Template.slot_names.update', (['slot_names'], {}), '(slot_names)\n', (3151, 3163), False, 'from trame.html import AbstractElement, Template\n'), ((907, 922), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (915, 922), True, 'import numpy as np\n'), ((926, 941), 'numpy.isinf', 'np.isinf', (['value'], {}), '(value)\n', (934, 941), True, 'import numpy as np\n')]
#!/usr/bin/python # # Copyright (C) 2016 Google, Inc # Written by <NAME> <<EMAIL>> # # SPDX-License-Identifier: GPL-2.0+ # import struct import sys import fdt_util import libfdt # This deals with a device tree, presenting it as an assortment of Node and # Prop objects, representing nodes and properties, respectively. This file # contains the base classes and defines the high-level API. You can use # FdtScan() as a convenience function to create and scan an Fdt. # This implementation uses a libfdt Python library to access the device tree, # so it is fairly efficient. # A list of types we support (TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL, TYPE_INT64) = range(5) def CheckErr(errnum, msg): if errnum: raise ValueError('Error %d: %s: %s' % (errnum, libfdt.fdt_strerror(errnum), msg)) class Prop: """A device tree property Properties: name: Property name (as per the device tree) value: Property value as a string of bytes, or a list of strings of bytes type: Value type """ def __init__(self, node, offset, name, bytes): self._node = node self._offset = offset self.name = name self.value = None self.bytes = str(bytes) if not bytes: self.type = TYPE_BOOL self.value = True return self.type, self.value = self.BytesToValue(bytes) def GetPhandle(self): """Get a (single) phandle value from a property Gets the phandle valuie from a property and returns it as an integer """ return fdt_util.fdt32_to_cpu(self.value[:4]) def Widen(self, newprop): """Figure out which property type is more general Given a current property and a new property, this function returns the one that is less specific as to type. The less specific property will be ble to represent the data in the more specific property. This is used for things like: node1 { compatible = "fred"; value = <1>; }; node1 { compatible = "fred"; value = <1 2>; }; He we want to use an int array for 'value'. The first property suggests that a single int is enough, but the second one shows that it is not. Calling this function with these two propertes would update the current property to be like the second, since it is less specific. """ if newprop.type < self.type: self.type = newprop.type if type(newprop.value) == list and type(self.value) != list: self.value = [self.value] if type(self.value) == list and len(newprop.value) > len(self.value): val = self.GetEmpty(self.type) while len(self.value) < len(newprop.value): self.value.append(val) def BytesToValue(self, bytes): """Converts a string of bytes into a type and value Args: A string containing bytes Return: A tuple: Type of data Data, either a single element or a list of elements. Each element is one of: TYPE_STRING: string value from the property TYPE_INT: a byte-swapped integer stored as a 4-byte string TYPE_BYTE: a byte stored as a single-byte string """ bytes = str(bytes) size = len(bytes) strings = bytes.split('\0') is_string = True count = len(strings) - 1 if count > 0 and not strings[-1]: for string in strings[:-1]: if not string: is_string = False break for ch in string: if ch < ' ' or ch > '~': is_string = False break else: is_string = False if is_string: if count == 1: return TYPE_STRING, strings[0] else: return TYPE_STRING, strings[:-1] if size % 4: if size == 1: return TYPE_BYTE, bytes[0] else: return TYPE_BYTE, list(bytes) val = [] for i in range(0, size, 4): val.append(bytes[i:i + 4]) if size == 4: return TYPE_INT, val[0] else: return TYPE_INT, val def GetEmpty(self, type): """Get an empty / zero value of the given type Returns: A single value of the given type """ if type == TYPE_BYTE: return chr(0) elif type == TYPE_INT: return struct.pack('<I', 0); elif type == TYPE_STRING: return '' else: return True def GetOffset(self): """Get the offset of a property Returns: The offset of the property (struct fdt_property) within the file """ return self._node._fdt.GetStructOffset(self._offset) class Node: """A device tree node Properties: offset: Integer offset in the device tree name: Device tree node tname path: Full path to node, along with the node name itself _fdt: Device tree object subnodes: A list of subnodes for this node, each a Node object props: A dict of properties for this node, each a Prop object. Keyed by property name """ def __init__(self, fdt, parent, offset, name, path): self._fdt = fdt self.parent = parent self._offset = offset self.name = name self.path = path self.subnodes = [] self.props = {} def _FindNode(self, name): """Find a node given its name Args: name: Node name to look for Returns: Node object if found, else None """ for subnode in self.subnodes: if subnode.name == name: return subnode return None def Offset(self): """Returns the offset of a node, after checking the cache This should be used instead of self._offset directly, to ensure that the cache does not contain invalid offsets. """ self._fdt.CheckCache() return self._offset def Scan(self): """Scan a node's properties and subnodes This fills in the props and subnodes properties, recursively searching into subnodes so that the entire tree is built. """ self.props = self._fdt.GetProps(self) phandle = self.props.get('phandle') if phandle: val = fdt_util.fdt32_to_cpu(phandle.value) self._fdt.phandle_to_node[val] = self offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self.Offset()) while offset >= 0: sep = '' if self.path[-1] == '/' else '/' name = self._fdt._fdt_obj.get_name(offset) path = self.path + sep + name node = Node(self._fdt, self, offset, name, path) self.subnodes.append(node) node.Scan() offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset) def Refresh(self, my_offset): """Fix up the _offset for each node, recursively Note: This does not take account of property offsets - these will not be updated. """ if self._offset != my_offset: #print '%s: %d -> %d\n' % (self.path, self._offset, my_offset) self._offset = my_offset offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset) for subnode in self.subnodes: subnode.Refresh(offset) offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset) def DeleteProp(self, prop_name): """Delete a property of a node The property is deleted and the offset cache is invalidated. Args: prop_name: Name of the property to delete Raises: ValueError if the property does not exist """ CheckErr(libfdt.fdt_delprop(self._fdt.GetFdt(), self.Offset(), prop_name), "Node '%s': delete property: '%s'" % (self.path, prop_name)) del self.props[prop_name] self._fdt.Invalidate() class Fdt: """Provides simple access to a flat device tree blob using libfdts. Properties: fname: Filename of fdt _root: Root of device tree (a Node object) """ def __init__(self, fname): self._fname = fname self._cached_offsets = False self.phandle_to_node = {} if self._fname: self._fname = fdt_util.EnsureCompiled(self._fname) with open(self._fname) as fd: self._fdt = bytearray(fd.read()) self._fdt_obj = libfdt.Fdt(self._fdt) def Scan(self, root='/'): """Scan a device tree, building up a tree of Node objects This fills in the self._root property Args: root: Ignored TODO(<EMAIL>): Implement the 'root' parameter """ self._root = self.Node(self, None, 0, '/', '/') self._root.Scan() def GetRoot(self): """Get the root Node of the device tree Returns: The root Node object """ return self._root def GetNode(self, path): """Look up a node from its path Args: path: Path to look up, e.g. '/microcode/update@0' Returns: Node object, or None if not found """ node = self._root for part in path.split('/')[1:]: node = node._FindNode(part) if not node: return None return node def Flush(self): """Flush device tree changes back to the file If the device tree has changed in memory, write it back to the file. """ with open(self._fname, 'wb') as fd: fd.write(self._fdt) def Pack(self): """Pack the device tree down to its minimum size When nodes and properties shrink or are deleted, wasted space can build up in the device tree binary. """ CheckErr(libfdt.fdt_pack(self._fdt), 'pack') fdt_len = libfdt.fdt_totalsize(self._fdt) del self._fdt[fdt_len:] def GetFdt(self): """Get the contents of the FDT Returns: The FDT contents as a string of bytes """ return self._fdt def CheckErr(errnum, msg): if errnum: raise ValueError('Error %d: %s: %s' % (errnum, libfdt.fdt_strerror(errnum), msg)) def GetProps(self, node): """Get all properties from a node. Args: node: Full path to node name to look in. Returns: A dictionary containing all the properties, indexed by node name. The entries are Prop objects. Raises: ValueError: if the node does not exist. """ props_dict = {} poffset = libfdt.fdt_first_property_offset(self._fdt, node._offset) while poffset >= 0: p = self._fdt_obj.get_property_by_offset(poffset) prop = Prop(node, poffset, p.name, p.value) props_dict[prop.name] = prop poffset = libfdt.fdt_next_property_offset(self._fdt, poffset) return props_dict def Invalidate(self): """Mark our offset cache as invalid""" self._cached_offsets = False def CheckCache(self): """Refresh the offset cache if needed""" if self._cached_offsets: return self.Refresh() self._cached_offsets = True def Refresh(self): """Refresh the offset cache""" self._root.Refresh(0) def GetStructOffset(self, offset): """Get the file offset of a given struct offset Args: offset: Offset within the 'struct' region of the device tree Returns: Position of @offset within the device tree binary """ return libfdt.fdt_off_dt_struct(self._fdt) + offset @classmethod def Node(self, fdt, parent, offset, name, path): """Create a new node This is used by Fdt.Scan() to create a new node using the correct class. Args: fdt: Fdt object parent: Parent node, or None if this is the root node offset: Offset of node name: Node name path: Full path to node """ node = Node(fdt, parent, offset, name, path) return node def FdtScan(fname): """Returns a new Fdt object from the implementation we are using""" dtb = Fdt(fname) dtb.Scan() return dtb
[ "libfdt.fdt_off_dt_struct", "fdt_util.fdt32_to_cpu", "libfdt.fdt_next_property_offset", "libfdt.Fdt", "libfdt.fdt_pack", "struct.pack", "libfdt.fdt_first_property_offset", "libfdt.fdt_strerror", "libfdt.fdt_totalsize", "fdt_util.EnsureCompiled" ]
[((1606, 1643), 'fdt_util.fdt32_to_cpu', 'fdt_util.fdt32_to_cpu', (['self.value[:4]'], {}), '(self.value[:4])\n', (1627, 1643), False, 'import fdt_util\n'), ((10363, 10394), 'libfdt.fdt_totalsize', 'libfdt.fdt_totalsize', (['self._fdt'], {}), '(self._fdt)\n', (10383, 10394), False, 'import libfdt\n'), ((11159, 11216), 'libfdt.fdt_first_property_offset', 'libfdt.fdt_first_property_offset', (['self._fdt', 'node._offset'], {}), '(self._fdt, node._offset)\n', (11191, 11216), False, 'import libfdt\n'), ((6753, 6789), 'fdt_util.fdt32_to_cpu', 'fdt_util.fdt32_to_cpu', (['phandle.value'], {}), '(phandle.value)\n', (6774, 6789), False, 'import fdt_util\n'), ((8761, 8797), 'fdt_util.EnsureCompiled', 'fdt_util.EnsureCompiled', (['self._fname'], {}), '(self._fname)\n', (8784, 8797), False, 'import fdt_util\n'), ((10309, 10335), 'libfdt.fdt_pack', 'libfdt.fdt_pack', (['self._fdt'], {}), '(self._fdt)\n', (10324, 10335), False, 'import libfdt\n'), ((11427, 11478), 'libfdt.fdt_next_property_offset', 'libfdt.fdt_next_property_offset', (['self._fdt', 'poffset'], {}), '(self._fdt, poffset)\n', (11458, 11478), False, 'import libfdt\n'), ((12186, 12221), 'libfdt.fdt_off_dt_struct', 'libfdt.fdt_off_dt_struct', (['self._fdt'], {}), '(self._fdt)\n', (12210, 12221), False, 'import libfdt\n'), ((4776, 4796), 'struct.pack', 'struct.pack', (['"""<I"""', '(0)'], {}), "('<I', 0)\n", (4787, 4796), False, 'import struct\n'), ((8922, 8943), 'libfdt.Fdt', 'libfdt.Fdt', (['self._fdt'], {}), '(self._fdt)\n', (8932, 8943), False, 'import libfdt\n'), ((791, 818), 'libfdt.fdt_strerror', 'libfdt.fdt_strerror', (['errnum'], {}), '(errnum)\n', (810, 818), False, 'import libfdt\n'), ((10720, 10747), 'libfdt.fdt_strerror', 'libfdt.fdt_strerror', (['errnum'], {}), '(errnum)\n', (10739, 10747), False, 'import libfdt\n')]
# probability.py import scipy import numpy as np ################################################################################ # Functions: # Phi # T # SkewNorm # SampleSkewNorm ################################################################################ def Phi(x, m, s, a): return 0.5 * (1. + scipy.special.erf((x - m) / s / pow(2, 0.5))) def T(h, a): f = lambda x: np.exp(-0.5 * pow(h, 2) * (1 + pow(x, 2))) / (1 + pow(x,2)) temp = scipy.integrate.quad(f, 0, a)[0] return 1. / (2. * np.pi) * temp def SkewNorm(x, m, s, a): return Phi(x, m, s, a) - 2 * T((x - m)/s, a) def SampleSkewNorm(m, s, a): """ A quick and dirty implementation of a skew-normal random variable. Returns values from a skew-normal distribution with location m, scale s, and shape parameter a (see ). When a = 0, this is just a Gaussian with mean m and standard deviation, s. """ # first, choose a random value in [0,1]: p = np.random.rand() # next, find the value of x corresponding that cumulative probability for # the skew-normal func = lambda x: p - SkewNorm(x, m, s, a) x = scipy.optimize.newton(func, 0) return x
[ "numpy.random.rand", "scipy.optimize.newton", "scipy.integrate.quad" ]
[((962, 978), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (976, 978), True, 'import numpy as np\n'), ((1134, 1164), 'scipy.optimize.newton', 'scipy.optimize.newton', (['func', '(0)'], {}), '(func, 0)\n', (1155, 1164), False, 'import scipy\n'), ((459, 488), 'scipy.integrate.quad', 'scipy.integrate.quad', (['f', '(0)', 'a'], {}), '(f, 0, a)\n', (479, 488), False, 'import scipy\n')]
from datetime import datetime, timedelta from threading import Lock from cutecare.backends import BluetoothInterface import logging _HANDLE_READ_SENSOR_DATA = 0x25 _LOGGER = logging.getLogger(__name__) class CuteCarePollerCC41A(object): def __init__(self, mac, backend, adapter='hci0'): self._mac = mac self._bt_interface = BluetoothInterface(backend, adapter) def name(self): return 'CuteCare CC41A DIY Sensor' def parameter_value(self): with self._bt_interface.connect(self._mac) as connection: raw_data = connection.read_handle_listen(_HANDLE_READ_SENSOR_DATA) _LOGGER.debug('Received result for handle %s: %s', \ _HANDLE_READ_SENSOR_DATA, self._format_bytes(raw_data)) return raw_data[0] * 256 + raw_data[1]; @staticmethod def _format_bytes(raw_data): """Prettyprint a byte array.""" return ' '.join([format(c, "02x") for c in raw_data]).upper()
[ "cutecare.backends.BluetoothInterface", "logging.getLogger" ]
[((175, 202), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (192, 202), False, 'import logging\n'), ((347, 383), 'cutecare.backends.BluetoothInterface', 'BluetoothInterface', (['backend', 'adapter'], {}), '(backend, adapter)\n', (365, 383), False, 'from cutecare.backends import BluetoothInterface\n')]
""" desispec.fiberbitmasking ============== Functions to properly take FIBERSTATUS into account in the variances for data reduction """ from __future__ import absolute_import, division import numpy as np from astropy.table import Table from desiutil.log import get_logger from desispec.maskbits import fibermask as fmsk from desispec.maskbits import specmask def get_fiberbitmasked_frame(frame,bitmask=None,ivar_framemask=True): """ Wrapper script of get_fiberbitmasked_frame_arrays that will return a modified version of the frame instead of just the flux and ivar NOTE: The input "frame" variable itself is modified and returned, not a copy. """ ivar,mask = get_fiberbitmasked_frame_arrays(frame,bitmask,ivar_framemask,return_mask=True) frame.mask = mask frame.ivar = ivar return frame def get_fiberbitmasked_frame_arrays(frame,bitmask=None,ivar_framemask=True,return_mask=False): """ Function that takes a frame object and a bitmask and returns ivar (and optionally mask) array(s) that have fibers with offending bits in fibermap['FIBERSTATUS'] set to 0 in ivar and optionally flips a bit in mask. input: frame: frame object bitmask: int32 or list/array of int32's derived from desispec.maskbits.fibermask OR string indicating a keyword for get_fiberbitmask_comparison_value() ivar_framemask: bool (default=True), tells code whether to multiply the output variance by (frame.mask==0) return_mask: bool, (default=False). Returns the frame.mask with the logic of FIBERSTATUS applied. output: ivar: frame.ivar where the fibers with FIBERSTATUS & bitmask > 0 set to zero ivar mask: (optional) frame.mask logically OR'ed with BADFIBER bit in cases with a bad FIBERSTATUS example bitmask list: bitmask = [fmsk.BROKENFIBER,fmsk.UNASSIGNED,fmsk.BADFIBER,\ fmsk.BADTRACE,fmsk.MANYBADCOL, fmsk.MANYREJECTED] bitmask = get_fiberbitmask_comparison_value(kind='fluxcalib') bitmask = 'fluxcalib' bitmask = 4128780 """ ivar = frame.ivar.copy() mask = frame.mask.copy() if ivar_framemask and frame.mask is not None: ivar *= (frame.mask==0) fmap = Table(frame.fibermap) if frame.fibermap is None: log = get_logger() log.warning("No fibermap was given, so no FIBERSTATUS check applied.") if bitmask is None or frame.fibermap is None: if return_mask: return ivar, mask else: return ivar if type(bitmask) in [int,np.int32]: bad = bitmask elif type(bitmask) == str: if bitmask.isnumeric(): bad = np.int32(bitmask) else: bad = get_fiberbitmask_comparison_value(kind=bitmask) else: bad = bitmask[0] for bit in bitmask[1:]: bad |= bit # find if any fibers have an intersection with the bad bits badfibers = fmap['FIBER'][ (fmap['FIBERSTATUS'] & bad) > 0 ].data badfibers = badfibers % 500 # For the bad fibers, loop through and nullify them for fiber in badfibers: mask[fiber] |= specmask.BADFIBER if ivar_framemask : ivar[fiber] = 0. if return_mask: return ivar,mask else: return ivar def get_fiberbitmask_comparison_value(kind='fluxcalib'): """ Takes a string argument and returns a 32-bit integer representing the logical OR of all relevant fibermask bits for that given reduction step input: kind: str : string designating which combination of bits to use based on the operation possible values are: "all", "sky" (or "skysub"), "flat", "flux" (or "fluxcalib"), "star" (or "stdstars") """ if kind.lower() == 'all': return get_all_fiberbitmask_val() elif kind.lower()[:3] == 'sky': return get_skysub_fiberbitmask_val() elif kind.lower() == 'flat': return get_flat_fiberbitmask_val() elif 'star' in kind.lower(): return get_stdstars_fiberbitmask_val() elif 'flux' in kind.lower(): return get_fluxcalib_fiberbitmask_val() else: log = get_logger() log.warning("Keyword {} given to get_fiberbitmask_comparison_value() is invalid.".format(kind)+\ " Using 'fluxcalib' fiberbitmask.") return get_fluxcalib_fiberbitmask_val() def get_skysub_fiberbitmask_val(): return get_all_fiberbitmask_val() def get_flat_fiberbitmask_val(): return (fmsk.BROKENFIBER | fmsk.BADFIBER | fmsk.BADTRACE | fmsk.BADARC | \ fmsk.MANYBADCOL | fmsk.MANYREJECTED ) def get_fluxcalib_fiberbitmask_val(): return get_all_fiberbitmask_val() def get_stdstars_fiberbitmask_val(): return get_all_fiberbitmask_val() def get_all_nonamp_fiberbitmask_val(): """Return a mask for all bad FIBERSTATUS bits except BADAMPB/R/Z Note: does not include STUCKPOSITIONER or RESTRICTED, which could still be on a valid sky location, or even a target for RESTRICTED. """ return (fmsk.UNASSIGNED | fmsk.BROKENFIBER | fmsk.MISSINGPOSITION | fmsk.BADPOSITION | \ fmsk.BADFIBER | fmsk.BADTRACE | fmsk.BADARC | fmsk.BADFLAT | \ fmsk.MANYBADCOL | fmsk.MANYREJECTED ) def get_justamps_fiberbitmask(): return ( fmsk.BADAMPB | fmsk.BADAMPR | fmsk.BADAMPZ ) def get_all_fiberbitmask_with_amp(band): nonamp_mask = get_all_nonamp_fiberbitmask_val() if band.lower()[0] == 'b': amp_mask = fmsk.BADAMPB elif band.lower()[0] == 'r': amp_mask = fmsk.BADAMPR elif band.lower()[0] == 'z': amp_mask = fmsk.BADAMPZ else: log = get_logger() log.error("Didn't recognize band={}".format(band)) amp_mask = np.int32(0) return ( nonamp_mask | amp_mask ) def get_all_fiberbitmask_val(): return ( get_all_nonamp_fiberbitmask_val() | get_justamps_fiberbitmask() )
[ "desiutil.log.get_logger", "astropy.table.Table", "numpy.int32" ]
[((2333, 2354), 'astropy.table.Table', 'Table', (['frame.fibermap'], {}), '(frame.fibermap)\n', (2338, 2354), False, 'from astropy.table import Table\n'), ((2401, 2413), 'desiutil.log.get_logger', 'get_logger', ([], {}), '()\n', (2411, 2413), False, 'from desiutil.log import get_logger\n'), ((2780, 2797), 'numpy.int32', 'np.int32', (['bitmask'], {}), '(bitmask)\n', (2788, 2797), True, 'import numpy as np\n'), ((5778, 5790), 'desiutil.log.get_logger', 'get_logger', ([], {}), '()\n', (5788, 5790), False, 'from desiutil.log import get_logger\n'), ((5869, 5880), 'numpy.int32', 'np.int32', (['(0)'], {}), '(0)\n', (5877, 5880), True, 'import numpy as np\n'), ((4284, 4296), 'desiutil.log.get_logger', 'get_logger', ([], {}), '()\n', (4294, 4296), False, 'from desiutil.log import get_logger\n')]
from cosmo_tester.framework.test_hosts import Hosts, VM def get_test_prerequisites(ssh_key, module_tmpdir, test_config, logger, request, vm_os, manager_count=1): hosts = Hosts(ssh_key, module_tmpdir, test_config, logger, request, manager_count + 1) hosts.instances[-1] = VM(vm_os, test_config) vm = hosts.instances[-1] return hosts, vm.username, vm.password def validate_agent(manager, example, test_config, broken_system=False, install_method='remote', upgrade=False): agents = list(manager.client.agents.list(tenant_name=example.tenant, _all_tenants=True)) instances = list( manager.client.node_instances.list( tenant_name=example.tenant, node_id='vm', _all_tenants=True ) ) assert len(agents) == 1 assert len(instances) == 1 agent = agents[0] instance = instances[0] if broken_system: expected_system = None else: expected_system = example.example_host.get_distro() if example.tenant.endswith('centos_8'): # Yes, we manage to get different behaviour for this OS expected_system = 'centos 8' expected_agent = { 'ip': example.inputs.get('server_ip', '127.0.0.1'), 'install_method': install_method, 'tenant_name': example.tenant, 'system': expected_system, 'id': instance['host_id'], 'host_id': instance['host_id'], 'version': test_config['testing_version'].replace('-ga', ''), 'node': instance['node_id'], 'deployment': instance['deployment_id'], } if upgrade: # Because it gets a UUID tacked onto the end agent['id'] = agent['id'][:len(expected_agent['id'])] assert agent == expected_agent
[ "cosmo_tester.framework.test_hosts.VM", "cosmo_tester.framework.test_hosts.Hosts" ]
[((203, 281), 'cosmo_tester.framework.test_hosts.Hosts', 'Hosts', (['ssh_key', 'module_tmpdir', 'test_config', 'logger', 'request', '(manager_count + 1)'], {}), '(ssh_key, module_tmpdir, test_config, logger, request, manager_count + 1)\n', (208, 281), False, 'from cosmo_tester.framework.test_hosts import Hosts, VM\n'), ((326, 348), 'cosmo_tester.framework.test_hosts.VM', 'VM', (['vm_os', 'test_config'], {}), '(vm_os, test_config)\n', (328, 348), False, 'from cosmo_tester.framework.test_hosts import Hosts, VM\n')]
import math import operator as op from collections import ChainMap from types import MappingProxyType from .symbol import Symbol from hyperpython import h import imp def eval(x, env=None): """ Avalia expressão no ambiente de execução dado. """ # Cria ambiente padrão, caso o usuário não passe o argumento opcional "env" if env is None: env = ChainMap({}, global_env) # Avalia tipos atômicos if isinstance(x, Symbol): return env[x] elif isinstance(x, (int, float, bool, str)): return x # Avalia formas especiais e listas head, *args = x # Comando (if <test> <then> <other>) # Ex: (if (even? x) (quotient x 2) x) if head == Symbol.IF: return NotImplemented #import submule from module # return ['import', args, str(str(name))] # imp : "import" "{" args "}" "from" name elif head == 'import': submodulos, modulo = args a =__import__(modulo) print(a) aux ={} for sub in submodulos: result = {str(sub): getattr(a,str(sub))} aux.update(result) env[modulo] = aux return aux # Módulo module elif head == 'module': for cmd in args: eval(cmd, env) return None # Comando x = 42; elif head == 'define': name, value = args env[name] = eval(value, env) return value # Comando html; elif head == 'html': tag, attrs, children = args attrs = {str(k): eval(v, env) for k, v in attrs.items()} children = [eval(x, env) for x in children] a = h(tag, attrs, children) return a # comando macro elif head == 'macro': tag, argumentos, expr = args def macro(*args): vars = dict(zip(argumentos, args)) local_env = ChainMap(vars, env) return eval(expr, local_env) env[tag] = macro return macro else: return NotImplemented def env(*args, **kwargs): kwargs = {Symbol(k): v for k, v in kwargs.items()} if len(args) > 1: raise TypeError('accepts zero or one positional arguments') elif len(args): if any(not isinstance(x, Symbol) for x in args[0]): raise ValueError('keys in a environment must be Symbols') args[0].update(kwargs) return ChainMap(args[0], global_env) return ChainMap(kwargs, global_env) def _make_global_env(): dic = { **vars(math), # sin, cos, sqrt, pi, ... '+':op.add, '-':op.sub, '*':op.mul, '/':op.truediv, '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'abs': abs, 'append': op.add, 'apply': lambda proc, args: proc(*args), 'begin': lambda *x: x[-1], 'car': lambda x: head, 'cdr': lambda x: x[1:], 'cons': lambda x,y: [x] + y, 'eq?': op.is_, 'expt': pow, 'equal?': op.eq, 'even?': lambda x: x % 2 == 0, 'length': len, 'list': lambda *x: list(x), 'list?': lambda x: isinstance(x, list), 'map': map, 'max': max, 'min': min, 'not': op.not_, 'null?': lambda x: x == [], 'number?': lambda x: isinstance(x, (float, int)), 'odd?': lambda x: x % 2 == 1, 'print': print, 'procedure?': callable, 'quotient': op.floordiv, 'round': round, 'symbol?': lambda x: isinstance(x, Symbol), } return MappingProxyType({Symbol(k): v for k, v in dic.items()}) global_env = _make_global_env()
[ "collections.ChainMap", "hyperpython.h" ]
[((2466, 2494), 'collections.ChainMap', 'ChainMap', (['kwargs', 'global_env'], {}), '(kwargs, global_env)\n', (2474, 2494), False, 'from collections import ChainMap\n'), ((376, 400), 'collections.ChainMap', 'ChainMap', (['{}', 'global_env'], {}), '({}, global_env)\n', (384, 400), False, 'from collections import ChainMap\n'), ((2425, 2454), 'collections.ChainMap', 'ChainMap', (['args[0]', 'global_env'], {}), '(args[0], global_env)\n', (2433, 2454), False, 'from collections import ChainMap\n'), ((1665, 1688), 'hyperpython.h', 'h', (['tag', 'attrs', 'children'], {}), '(tag, attrs, children)\n', (1666, 1688), False, 'from hyperpython import h\n'), ((1900, 1919), 'collections.ChainMap', 'ChainMap', (['vars', 'env'], {}), '(vars, env)\n', (1908, 1919), False, 'from collections import ChainMap\n')]
# This file is part of astro_metadata_translator. # # Developed for the LSST Data Management System. # This product includes software developed by the LSST Project # (http://www.lsst.org). # See the LICENSE file at the top-level directory of this distribution # for details of code ownership. # # Use of this source code is governed by a 3-clause BSD-style # license that can be found in the LICENSE file. """Implementation of the ``translate_header.py`` script. Read file metadata from the specified files and report the translated content. """ __all__ = ("main", "process_files") import argparse import logging import sys import traceback import importlib import yaml from astro_metadata_translator import ObservationInfo, fix_header, MetadataTranslator from ..file_helpers import find_files, read_basic_metadata_from_file # Output mode choices OUTPUT_MODES = ("auto", "verbose", "table", "yaml", "fixed", "yamlnative", "fixednative", "none") # Definitions for table columns TABLE_COLUMNS = ({ "format": "32.32s", "attr": "observation_id", "label": "ObsId" }, { "format": "8.8s", "attr": "observation_type", "label": "ImgType", }, { "format": "16.16s", "attr": "object", "label": "Object", }, { "format": "16.16s", "attr": "physical_filter", "label": "Filter", }, { "format": ">8.8s", "attr": "detector_unique_name", "label": "Detector" }, { "format": "5.1f", "attr": "exposure_time", "label": "ExpTime", }, ) def build_argparser(): """Construct an argument parser for the ``translate_header.py`` script. Returns ------- argparser : `argparse.ArgumentParser` The argument parser that defines the ``translate_header.py`` command-line interface. """ parser = argparse.ArgumentParser(description="Summarize headers from astronomical data files") parser.add_argument("files", metavar="file", type=str, nargs="+", help="File(s) from which headers will be parsed." " If a directory is given it will be scanned for files matching the regular" " expression defined in --regex.") parser.add_argument("-q", "--quiet", action="store_true", help="Do not report the translation content from each header. This forces " "output mode 'none'.") parser.add_argument("-d", "--dumphdr", action="store_true", help="Dump the header in YAML format to standard output rather than translating it." " This is the same as using mode=yaml") parser.add_argument("--traceback", action="store_true", help="Give detailed trace back when any errors encountered") parser.add_argument("-n", "--hdrnum", default=1, help="HDU number to read. If the HDU can not be found, a warning is issued but " "translation is attempted using the primary header. " "The primary header is always read and merged with this header.") parser.add_argument("-m", "--mode", default="auto", choices=OUTPUT_MODES, help="Display mode for translated parameters. 'verbose' displays all the information" " available. 'table' displays important information in tabular form." " 'yaml' dumps the header in YAML format (this is equivalent to -d option)." " 'fixed' dumps the header in YAML after it has had corrections applied." " Add 'native' suffix to dump YAML in PropertyList or Astropy native form." " 'none' displays no translated header information and is an alias for the " " '--quiet' option." " 'auto' mode is 'verbose' for a single file and 'table' for multiple files.") parser.add_argument("-l", "--log", default="warn", help="Python logging level to use.") re_default = r"\.fit[s]?\b" parser.add_argument("-r", "--regex", default=re_default, help="When looking in a directory, regular expression to use to determine whether" f" a file should be examined. Default: '{re_default}'") parser.add_argument("-p", "--packages", action="append", type=str, help="Python packages to import to register additional translators") return parser def read_file(file, hdrnum, print_trace, outstream=sys.stdout, errstream=sys.stderr, output_mode="verbose", write_heading=False): """Read the specified file and process it. Parameters ---------- file : `str` The file from which the header is to be read. hdrnum : `int` The HDU number to read. The primary header is always read and merged with the header from this HDU. print_trace : `bool` If there is an error reading the file and this parameter is `True`, a full traceback of the exception will be reported. If `False` prints a one line summary of the error condition. outstream : `io.StringIO`, optional Output stream to use for standard messages. Defaults to `sys.stdout`. errstream : `io.StringIO`, optional Stream to send messages that would normally be sent to standard error. Defaults to `sys.stderr`. output_mode : `str`, optional Output mode to use. Must be one of "verbose", "none", "table", "yaml", or "fixed". "yaml" and "fixed" can be modified with a "native" suffix to indicate that the output should be a representation of the native object type representing the header (which can be PropertyList or an Astropy header). Without this modify headers will be dumped as simple `dict` form. "auto" is used to indicate that a single file has been specified but the output will depend on whether the file is a multi-extension FITS file or not. write_heading: `bool`, optional If `True` and in table mode, write a table heading out before writing the content. Returns ------- success : `bool` `True` if the file was handled successfully, `False` if the file could not be processed. """ if output_mode not in OUTPUT_MODES: raise ValueError(f"Output mode of '{output_mode}' is not understood.") # This gets in the way in tabular mode if output_mode != "table": print(f"Analyzing {file}...", file=errstream) try: md = read_basic_metadata_from_file(file, hdrnum, errstream=errstream, can_raise=True) if md is None: raise RuntimeError(f"Failed to read file {file} HDU={hdrnum}") if output_mode.endswith("native"): # Strip native and don't change type of md output_mode = output_mode[:-len("native")] else: # Rewrite md as simple dict for output md = {k: v for k, v in md.items()} if output_mode in ("yaml", "fixed"): if output_mode == "fixed": fix_header(md, filename=file) # The header should be written out in the insertion order print(yaml.dump(md, sort_keys=False), file=outstream) return True # Try to work out a translator class. translator_class = MetadataTranslator.determine_translator(md, filename=file) # Work out which headers to translate, assuming the default if # we have a YAML test file. if file.endswith(".yaml"): headers = [md] else: headers = list(translator_class.determine_translatable_headers(file, md)) if output_mode == "auto": output_mode = "table" if len(headers) > 1 else "verbose" wrote_heading = False for md in headers: obs_info = ObservationInfo(md, pedantic=True, filename=file) if output_mode == "table": columns = ["{:{fmt}}".format(getattr(obs_info, c["attr"]), fmt=c["format"]) for c in TABLE_COLUMNS] if write_heading and not wrote_heading: # Construct headings of the same width as the items # we have calculated. Doing this means we don't have to # work out for ourselves how many characters will be used # for non-strings (especially Quantity) headings = [] separators = [] for thiscol, defn in zip(columns, TABLE_COLUMNS): width = len(thiscol) headings.append("{:{w}.{w}}".format(defn["label"], w=width)) separators.append("-"*width) print(" ".join(headings), file=outstream) print(" ".join(separators), file=outstream) wrote_heading = True row = " ".join(columns) print(row, file=outstream) elif output_mode == "verbose": print(f"{obs_info}", file=outstream) elif output_mode == "none": pass else: raise RuntimeError(f"Output mode of '{output_mode}' not recognized but should be known.") except Exception as e: if print_trace: traceback.print_exc(file=outstream) else: print(f"Failure processing {file}: {e}", file=outstream) return False return True def process_files(files, regex, hdrnum, print_trace, outstream=sys.stdout, errstream=sys.stderr, output_mode="auto"): """Read and translate metadata from the specified files. Parameters ---------- files : iterable of `str` The files or directories from which the headers are to be read. regex : `str` Regular expression string used to filter files when a directory is scanned. hdrnum : `int` The HDU number to read. The primary header is always read and merged with the header from this HDU. print_trace : `bool` If there is an error reading the file and this parameter is `True`, a full traceback of the exception will be reported. If `False` prints a one line summary of the error condition. outstream : `io.StringIO`, optional Output stream to use for standard messages. Defaults to `sys.stdout`. errstream : `io.StringIO`, optional Stream to send messages that would normally be sent to standard error. Defaults to `sys.stderr`. output_mode : `str`, optional Output mode to use for the translated information. "auto" switches based on how many files are found. Returns ------- okay : `list` of `str` All the files that were processed successfully. failed : `list` of `str` All the files that could not be processed. """ found_files = find_files(files, regex) # Convert "auto" to correct mode but for a single file keep it # auto in case that file has multiple headers if output_mode == "auto": if len(found_files) > 1: output_mode = "table" # Process each file failed = [] okay = [] heading = True for path in sorted(found_files): isok = read_file(path, hdrnum, print_trace, outstream, errstream, output_mode, heading) heading = False if isok: okay.append(path) else: failed.append(path) return okay, failed def main(): """Read metadata from the supplied files and translate the content to standard form. Returns ------- status : `int` Exit status to be passed to `sys.exit()`. 0 if any of the files could be translated. 1 otherwise. """ logging.warn("This command is deprecated. Please use 'astrometadata translate' " " or 'astrometadata dump' instead. See 'astrometadata -h' for more details.") args = build_argparser().parse_args() # Process import requests if args.packages: for m in args.packages: importlib.import_module(m) output_mode = args.mode if args.quiet: output_mode = "none" elif args.dumphdr: output_mode = "yaml" # Set the log level. Convert to upper case to allow the user to # specify --log=DEBUG or --log=debug numeric_level = getattr(logging, args.log.upper(), None) if not isinstance(numeric_level, int): raise ValueError(f"Invalid log level: {args.log}") logging.basicConfig(level=numeric_level) # Main loop over files okay, failed = process_files(args.files, args.regex, args.hdrnum, args.traceback, output_mode=output_mode) if failed: print("Files with failed translations:", file=sys.stderr) for f in failed: print(f"\t{f}", file=sys.stderr) if okay: # Good status if anything was returned in okay return 0 else: return 1
[ "astro_metadata_translator.fix_header", "traceback.print_exc", "argparse.ArgumentParser", "logging.basicConfig", "importlib.import_module", "logging.warn", "yaml.dump", "astro_metadata_translator.MetadataTranslator.determine_translator", "astro_metadata_translator.ObservationInfo" ]
[((2222, 2312), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Summarize headers from astronomical data files"""'}), "(description=\n 'Summarize headers from astronomical data files')\n", (2245, 2312), False, 'import argparse\n'), ((12457, 12622), 'logging.warn', 'logging.warn', (['"""This command is deprecated. Please use \'astrometadata translate\' or \'astrometadata dump\' instead. See \'astrometadata -h\' for more details."""'], {}), '(\n "This command is deprecated. Please use \'astrometadata translate\' or \'astrometadata dump\' instead. See \'astrometadata -h\' for more details."\n )\n', (12469, 12622), False, 'import logging\n'), ((13206, 13246), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'numeric_level'}), '(level=numeric_level)\n', (13225, 13246), False, 'import logging\n'), ((7940, 7998), 'astro_metadata_translator.MetadataTranslator.determine_translator', 'MetadataTranslator.determine_translator', (['md'], {'filename': 'file'}), '(md, filename=file)\n', (7979, 7998), False, 'from astro_metadata_translator import ObservationInfo, fix_header, MetadataTranslator\n'), ((8453, 8502), 'astro_metadata_translator.ObservationInfo', 'ObservationInfo', (['md'], {'pedantic': '(True)', 'filename': 'file'}), '(md, pedantic=True, filename=file)\n', (8468, 8502), False, 'from astro_metadata_translator import ObservationInfo, fix_header, MetadataTranslator\n'), ((12773, 12799), 'importlib.import_module', 'importlib.import_module', (['m'], {}), '(m)\n', (12796, 12799), False, 'import importlib\n'), ((7675, 7704), 'astro_metadata_translator.fix_header', 'fix_header', (['md'], {'filename': 'file'}), '(md, filename=file)\n', (7685, 7704), False, 'from astro_metadata_translator import ObservationInfo, fix_header, MetadataTranslator\n'), ((7794, 7824), 'yaml.dump', 'yaml.dump', (['md'], {'sort_keys': '(False)'}), '(md, sort_keys=False)\n', (7803, 7824), False, 'import yaml\n'), ((9947, 9982), 'traceback.print_exc', 'traceback.print_exc', ([], {'file': 'outstream'}), '(file=outstream)\n', (9966, 9982), False, 'import traceback\n')]
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 from acapy_wrapper.models.indy_rev_reg_def import IndyRevRegDef from acapy_wrapper.models.indy_rev_reg_entry import IndyRevRegEntry class IssuerRevRegRecord(BaseModel): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. IssuerRevRegRecord - a model defined in OpenAPI created_at: The created_at of this IssuerRevRegRecord [Optional]. cred_def_id: The cred_def_id of this IssuerRevRegRecord [Optional]. error_msg: The error_msg of this IssuerRevRegRecord [Optional]. issuer_did: The issuer_did of this IssuerRevRegRecord [Optional]. max_cred_num: The max_cred_num of this IssuerRevRegRecord [Optional]. pending_pub: The pending_pub of this IssuerRevRegRecord [Optional]. record_id: The record_id of this IssuerRevRegRecord [Optional]. revoc_def_type: The revoc_def_type of this IssuerRevRegRecord [Optional]. revoc_reg_def: The revoc_reg_def of this IssuerRevRegRecord [Optional]. revoc_reg_entry: The revoc_reg_entry of this IssuerRevRegRecord [Optional]. revoc_reg_id: The revoc_reg_id of this IssuerRevRegRecord [Optional]. state: The state of this IssuerRevRegRecord [Optional]. tag: The tag of this IssuerRevRegRecord [Optional]. tails_hash: The tails_hash of this IssuerRevRegRecord [Optional]. tails_local_path: The tails_local_path of this IssuerRevRegRecord [Optional]. tails_public_uri: The tails_public_uri of this IssuerRevRegRecord [Optional]. updated_at: The updated_at of this IssuerRevRegRecord [Optional]. """ created_at: Optional[str] = None cred_def_id: Optional[str] = None error_msg: Optional[str] = None issuer_did: Optional[str] = None max_cred_num: Optional[int] = None pending_pub: Optional[List[str]] = None record_id: Optional[str] = None revoc_def_type: Optional[str] = None revoc_reg_def: Optional[IndyRevRegDef] = None revoc_reg_entry: Optional[IndyRevRegEntry] = None revoc_reg_id: Optional[str] = None state: Optional[str] = None tag: Optional[str] = None tails_hash: Optional[str] = None tails_local_path: Optional[str] = None tails_public_uri: Optional[str] = None updated_at: Optional[str] = None @validator("created_at") def created_at_pattern(cls, value): assert value is not None and re.match( r"^\d{4}-\d\d-\d\d[T ]\d\d:\d\d(?:\:(?:\d\d(?:\.\d{1,6})?))?(?:[+-]\d\d:?\d\d|Z|)$", value, ) return value @validator("cred_def_id") def cred_def_id_pattern(cls, value): assert value is not None and re.match( r"^([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):3:CL:(([1-9][0-9]*)|([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}:2:.+:[0-9.]+)):(.+)?$", value, ) return value @validator("issuer_did") def issuer_did_pattern(cls, value): assert value is not None and re.match( r"^(did:sov:)?[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}$", value, ) return value @validator("revoc_reg_id") def revoc_reg_id_pattern(cls, value): assert value is not None and re.match( r"^([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):4:([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):3:CL:(([1-9][0-9]*)|([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}:2:.+:[0-9.]+))(:.+)?:CL_ACCUM:(.+$)", value, ) return value @validator("tails_hash") def tails_hash_pattern(cls, value): assert value is not None and re.match( r"^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{43,44}$", value, ) return value @validator("updated_at") def updated_at_pattern(cls, value): assert value is not None and re.match( r"^\d{4}-\d\d-\d\d[T ]\d\d:\d\d(?:\:(?:\d\d(?:\.\d{1,6})?))?(?:[+-]\d\d:?\d\d|Z|)$", value, ) return value IssuerRevRegRecord.update_forward_refs()
[ "pydantic.validator", "re.match" ]
[((2598, 2621), 'pydantic.validator', 'validator', (['"""created_at"""'], {}), "('created_at')\n", (2607, 2621), False, 'from pydantic import AnyUrl, BaseModel, EmailStr, validator\n'), ((2862, 2886), 'pydantic.validator', 'validator', (['"""cred_def_id"""'], {}), "('cred_def_id')\n", (2871, 2886), False, 'from pydantic import AnyUrl, BaseModel, EmailStr, validator\n'), ((3229, 3252), 'pydantic.validator', 'validator', (['"""issuer_did"""'], {}), "('issuer_did')\n", (3238, 3252), False, 'from pydantic import AnyUrl, BaseModel, EmailStr, validator\n'), ((3493, 3518), 'pydantic.validator', 'validator', (['"""revoc_reg_id"""'], {}), "('revoc_reg_id')\n", (3502, 3518), False, 'from pydantic import AnyUrl, BaseModel, EmailStr, validator\n'), ((3948, 3971), 'pydantic.validator', 'validator', (['"""tails_hash"""'], {}), "('tails_hash')\n", (3957, 3971), False, 'from pydantic import AnyUrl, BaseModel, EmailStr, validator\n'), ((4201, 4224), 'pydantic.validator', 'validator', (['"""updated_at"""'], {}), "('updated_at')\n", (4210, 4224), False, 'from pydantic import AnyUrl, BaseModel, EmailStr, validator\n'), ((2699, 2826), 're.match', 're.match', (['"""^\\\\d{4}-\\\\d\\\\d-\\\\d\\\\d[T ]\\\\d\\\\d:\\\\d\\\\d(?:\\\\:(?:\\\\d\\\\d(?:\\\\.\\\\d{1,6})?))?(?:[+-]\\\\d\\\\d:?\\\\d\\\\d|Z|)$"""', 'value'], {}), "(\n '^\\\\d{4}-\\\\d\\\\d-\\\\d\\\\d[T ]\\\\d\\\\d:\\\\d\\\\d(?:\\\\:(?:\\\\d\\\\d(?:\\\\.\\\\d{1,6})?))?(?:[+-]\\\\d\\\\d:?\\\\d\\\\d|Z|)$'\n , value)\n", (2707, 2826), False, 'import re\n'), ((2965, 3175), 're.match', 're.match', (['"""^([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):3:CL:(([1-9][0-9]*)|([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}:2:.+:[0-9.]+)):(.+)?$"""', 'value'], {}), "(\n '^([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):3:CL:(([1-9][0-9]*)|([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}:2:.+:[0-9.]+)):(.+)?$'\n , value)\n", (2973, 3175), False, 'import re\n'), ((3330, 3439), 're.match', 're.match', (['"""^(did:sov:)?[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}$"""', 'value'], {}), "(\n '^(did:sov:)?[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}$'\n , value)\n", (3338, 3439), False, 'import re\n'), ((3598, 3894), 're.match', 're.match', (['"""^([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):4:([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):3:CL:(([1-9][0-9]*)|([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}:2:.+:[0-9.]+))(:.+)?:CL_ACCUM:(.+$)"""', 'value'], {}), "(\n '^([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):4:([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}):3:CL:(([1-9][0-9]*)|([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21,22}:2:.+:[0-9.]+))(:.+)?:CL_ACCUM:(.+$)'\n , value)\n", (3606, 3894), False, 'import re\n'), ((4049, 4146), 're.match', 're.match', (['"""^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{43,44}$"""', 'value'], {}), "(\n '^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{43,44}$',\n value)\n", (4057, 4146), False, 'import re\n'), ((4302, 4429), 're.match', 're.match', (['"""^\\\\d{4}-\\\\d\\\\d-\\\\d\\\\d[T ]\\\\d\\\\d:\\\\d\\\\d(?:\\\\:(?:\\\\d\\\\d(?:\\\\.\\\\d{1,6})?))?(?:[+-]\\\\d\\\\d:?\\\\d\\\\d|Z|)$"""', 'value'], {}), "(\n '^\\\\d{4}-\\\\d\\\\d-\\\\d\\\\d[T ]\\\\d\\\\d:\\\\d\\\\d(?:\\\\:(?:\\\\d\\\\d(?:\\\\.\\\\d{1,6})?))?(?:[+-]\\\\d\\\\d:?\\\\d\\\\d|Z|)$'\n , value)\n", (4310, 4429), False, 'import re\n')]
import math from dataclasses import dataclass from typing import Tuple, List, TypeVar T = TypeVar('T') @dataclass class BrowserConfig: index: int = 0 item_per_line: int = 1 item_per_page: int = 1 tool_bar: bool = True transpose_grid: bool = False # TODO: transpose orientation def range(self, index: int = None) -> Tuple[int, int]: if index is None: index = self.index start = index * self.item_per_page end = start + self.item_per_page return start, end def select(self, model: List[T], index: int): try: first, last = self.range(index) return model[first:last] except: return [] def page_number(self, items: List): if not items: return 0 return math.ceil(len(items) / self.item_per_page)
[ "typing.TypeVar" ]
[((91, 103), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (98, 103), False, 'from typing import Tuple, List, TypeVar\n')]
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class PhoneItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() brand = scrapy.Field() model = scrapy.Field() category = scrapy.Field() price = scrapy.Field() network_type = scrapy.Field() network_2g = scrapy.Field() network_3g = scrapy.Field() network_4g = scrapy.Field() network_5g = scrapy.Field() speed = scrapy.Field() gprs = scrapy.Field() edge = scrapy.Field() launch_announcement = scrapy.Field() launch_date = scrapy.Field() body_dimensions = scrapy.Field() body_weight = scrapy.Field() build = scrapy.Field() network_sim = scrapy.Field() display_type = scrapy.Field() display_size = scrapy.Field() display_resolution = scrapy.Field() display_multitouch = scrapy.Field() display_density = scrapy.Field() display_screen_protection = scrapy.Field() operating_system = scrapy.Field() os_version = scrapy.Field() cpu = scrapy.Field() gpu = scrapy.Field() chipset = scrapy.Field() memory_internal = scrapy.Field() memory_external = scrapy.Field() ram = scrapy.Field() primary_camera = scrapy.Field() secondary_camera = scrapy.Field() camera_features = scrapy.Field() video = scrapy.Field() audio = scrapy.Field() loudspeaker = scrapy.Field() headphone_jack = scrapy.Field() wifi = scrapy.Field() bluetooth = scrapy.Field() usb = scrapy.Field() infrared = scrapy.Field() fm_radio = scrapy.Field() gps = scrapy.Field() sensors = scrapy.Field() messaging = scrapy.Field() browser = scrapy.Field() java = scrapy.Field() battery_type = scrapy.Field() battery_capacity = scrapy.Field() battery_stand_by = scrapy.Field() battery_talk_time = scrapy.Field() music = scrapy.Field() made_by = scrapy.Field() body_color = scrapy.Field() other_features = scrapy.Field() phone_url = scrapy.Field()
[ "scrapy.Field" ]
[((235, 249), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (247, 249), False, 'import scrapy\n'), ((262, 276), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (274, 276), False, 'import scrapy\n'), ((289, 303), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (301, 303), False, 'import scrapy\n'), ((319, 333), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (331, 333), False, 'import scrapy\n'), ((346, 360), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (358, 360), False, 'import scrapy\n'), ((380, 394), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (392, 394), False, 'import scrapy\n'), ((412, 426), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (424, 426), False, 'import scrapy\n'), ((444, 458), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (456, 458), False, 'import scrapy\n'), ((476, 490), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (488, 490), False, 'import scrapy\n'), ((508, 522), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (520, 522), False, 'import scrapy\n'), ((535, 549), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (547, 549), False, 'import scrapy\n'), ((561, 575), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (573, 575), False, 'import scrapy\n'), ((587, 601), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (599, 601), False, 'import scrapy\n'), ((628, 642), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (640, 642), False, 'import scrapy\n'), ((661, 675), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (673, 675), False, 'import scrapy\n'), ((698, 712), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (710, 712), False, 'import scrapy\n'), ((731, 745), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (743, 745), False, 'import scrapy\n'), ((758, 772), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (770, 772), False, 'import scrapy\n'), ((791, 805), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (803, 805), False, 'import scrapy\n'), ((825, 839), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (837, 839), False, 'import scrapy\n'), ((859, 873), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (871, 873), False, 'import scrapy\n'), ((899, 913), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (911, 913), False, 'import scrapy\n'), ((939, 953), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (951, 953), False, 'import scrapy\n'), ((976, 990), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (988, 990), False, 'import scrapy\n'), ((1023, 1037), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1035, 1037), False, 'import scrapy\n'), ((1061, 1075), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1073, 1075), False, 'import scrapy\n'), ((1093, 1107), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1105, 1107), False, 'import scrapy\n'), ((1118, 1132), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1130, 1132), False, 'import scrapy\n'), ((1143, 1157), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1155, 1157), False, 'import scrapy\n'), ((1172, 1186), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1184, 1186), False, 'import scrapy\n'), ((1209, 1223), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1221, 1223), False, 'import scrapy\n'), ((1246, 1260), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1258, 1260), False, 'import scrapy\n'), ((1271, 1285), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1283, 1285), False, 'import scrapy\n'), ((1307, 1321), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1319, 1321), False, 'import scrapy\n'), ((1345, 1359), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1357, 1359), False, 'import scrapy\n'), ((1382, 1396), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1394, 1396), False, 'import scrapy\n'), ((1409, 1423), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1421, 1423), False, 'import scrapy\n'), ((1436, 1450), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1448, 1450), False, 'import scrapy\n'), ((1469, 1483), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1481, 1483), False, 'import scrapy\n'), ((1505, 1519), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1517, 1519), False, 'import scrapy\n'), ((1531, 1545), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1543, 1545), False, 'import scrapy\n'), ((1562, 1576), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1574, 1576), False, 'import scrapy\n'), ((1587, 1601), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1599, 1601), False, 'import scrapy\n'), ((1617, 1631), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1629, 1631), False, 'import scrapy\n'), ((1647, 1661), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1659, 1661), False, 'import scrapy\n'), ((1672, 1686), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1684, 1686), False, 'import scrapy\n'), ((1701, 1715), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1713, 1715), False, 'import scrapy\n'), ((1732, 1746), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1744, 1746), False, 'import scrapy\n'), ((1761, 1775), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1773, 1775), False, 'import scrapy\n'), ((1787, 1801), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1799, 1801), False, 'import scrapy\n'), ((1821, 1835), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1833, 1835), False, 'import scrapy\n'), ((1859, 1873), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1871, 1873), False, 'import scrapy\n'), ((1897, 1911), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1909, 1911), False, 'import scrapy\n'), ((1936, 1950), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1948, 1950), False, 'import scrapy\n'), ((1963, 1977), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (1975, 1977), False, 'import scrapy\n'), ((1992, 2006), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (2004, 2006), False, 'import scrapy\n'), ((2024, 2038), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (2036, 2038), False, 'import scrapy\n'), ((2060, 2074), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (2072, 2074), False, 'import scrapy\n'), ((2091, 2105), 'scrapy.Field', 'scrapy.Field', ([], {}), '()\n', (2103, 2105), False, 'import scrapy\n')]
# Copyright (c) 2015-2018 Cisco Systems, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import os from molecule import logger from molecule import util from molecule.api import Verifier LOG = logger.get_logger(__name__) class Goss(Verifier): """ `Goss`_ is not the default test runner. `Goss`_ is a YAML based serverspec-like tool for validating a server's configuration. `Goss`_ is `not` the default verifier used in Molecule. Molecule executes a playbook (`verify.yml`) located in the role's `scenario.directory`. This playbook will copy YAML files to the instances, and execute Goss using a community written Goss Ansible module bundled with Molecule. Additional options can be passed to ``goss validate`` by modifying the verify playbook. .. code-block:: yaml verifier: name: goss The testing can be disabled by setting ``enabled`` to False. .. code-block:: yaml verifier: name: goss enabled: False Environment variables can be passed to the verifier. .. code-block:: yaml verifier: name: goss env: FOO: bar Change path to the test directory. .. code-block:: yaml verifier: name: goss directory: /foo/bar/ All files starting with test_* will be copied to all molecule hosts. Files matching the regular expression `test_host_$instance_name[-.\\w].yml` will only run on $instance_name. If you have 2 molecule instances, instance1 and instance2, your test files could look like this: .. code-block:: bash test_default.yml (will run on all hosts) test_host_instance1.yml (will run only on instance1) test_host_instance2.yml (will run only on instance2) .. important:: Due to the nature of this verifier. Molecule does not perform options handling in the same fashion as Testinfra. .. _`Goss`: https://github.com/aelsabbahy/goss """ def __init__(self, config=None): """ Sets up the requirements to execute ``goss`` and returns None. :param config: An instance of a Molecule config. :return: None """ super(Goss, self).__init__(config) if config: self._tests = self._get_tests() @property def name(self): return "goss" @property def default_options(self): return {} @property def default_env(self): return util.merge_dicts(os.environ.copy(), self._config.env) def bake(self): pass def execute(self): if not self.enabled: msg = "Skipping, verifier is disabled." LOG.warn(msg) return if not len(self._tests) > 0: msg = "Skipping, no tests found." LOG.warn(msg) return msg = "Executing Goss tests found in {}/...".format(self.directory) LOG.info(msg) self._config.provisioner.verify() msg = "Verifier completed successfully." LOG.success(msg) def _get_tests(self): """ Walk the verifier's directory for tests and returns a list. :return: list """ return [filename for filename in util.os_walk(self.directory, "test_*.yml")] def schema(self): return { "verifier": { "type": "dict", "schema": { "name": {"type": "string", "allowed": ["goss"]}, "options": {"keysrules": {"readonly": True}}, }, } } def template_dir(self): p = os.path.abspath(os.path.join(os.path.dirname(__file__), "cookiecutter")) return p
[ "os.environ.copy", "molecule.util.os_walk", "os.path.dirname", "molecule.logger.get_logger" ]
[((1226, 1253), 'molecule.logger.get_logger', 'logger.get_logger', (['__name__'], {}), '(__name__)\n', (1243, 1253), False, 'from molecule import logger\n'), ((3559, 3576), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (3574, 3576), False, 'import os\n'), ((4309, 4351), 'molecule.util.os_walk', 'util.os_walk', (['self.directory', '"""test_*.yml"""'], {}), "(self.directory, 'test_*.yml')\n", (4321, 4351), False, 'from molecule import util\n'), ((4727, 4752), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (4742, 4752), False, 'import os\n')]
from onegov.core.security import Private from onegov.form import merge_forms from onegov.org.views.payment import view_payments, export_payments from onegov.town6 import TownApp from onegov.org.forms import DateRangeForm, ExportForm from onegov.pay import PaymentCollection from onegov.town6.layout import PaymentCollectionLayout @TownApp.html( model=PaymentCollection, template='payments.pt', permission=Private) def town_view_payments(self, request): return view_payments(self, request, PaymentCollectionLayout(self, request)) @TownApp.form( model=PaymentCollection, name='export', template='form.pt', permission=Private, form=merge_forms(DateRangeForm, ExportForm)) def town_export_payments(self, request, form): return export_payments( self, request, form, PaymentCollectionLayout(self, request))
[ "onegov.form.merge_forms", "onegov.town6.TownApp.html", "onegov.town6.layout.PaymentCollectionLayout" ]
[((334, 420), 'onegov.town6.TownApp.html', 'TownApp.html', ([], {'model': 'PaymentCollection', 'template': '"""payments.pt"""', 'permission': 'Private'}), "(model=PaymentCollection, template='payments.pt', permission=\n Private)\n", (346, 420), False, 'from onegov.town6 import TownApp\n'), ((508, 546), 'onegov.town6.layout.PaymentCollectionLayout', 'PaymentCollectionLayout', (['self', 'request'], {}), '(self, request)\n', (531, 546), False, 'from onegov.town6.layout import PaymentCollectionLayout\n'), ((814, 852), 'onegov.town6.layout.PaymentCollectionLayout', 'PaymentCollectionLayout', (['self', 'request'], {}), '(self, request)\n', (837, 852), False, 'from onegov.town6.layout import PaymentCollectionLayout\n'), ((670, 708), 'onegov.form.merge_forms', 'merge_forms', (['DateRangeForm', 'ExportForm'], {}), '(DateRangeForm, ExportForm)\n', (681, 708), False, 'from onegov.form import merge_forms\n')]
""" TensorMONK :: regularizations """ __all__ = ["DropOut"] def DropOut(tensor_size, p, dropblock=True, **kwargs): import torch.nn as nn if p > 0: if len(tensor_size) == 4: if dropblock: from .dropblock import DropBlock kwgs = {} if "block_size" in kwargs.keys(): kwgs["block_size"] = kwargs["block_size"] if "shared" in kwargs.keys(): kwgs["shared"] = kwargs["shared"] if "iterative_p" in kwargs.keys(): kwgs["iterative_p"] = kwargs["iterative_p"] if "steps_to_max" in kwargs.keys(): kwgs["steps_to_max"] = kwargs["steps_to_max"] return DropBlock(tensor_size, p=p, **kwgs) else: return nn.Dropout2d(p) else: return nn.Dropout(p) else: return None
[ "torch.nn.Dropout", "torch.nn.Dropout2d" ]
[((887, 900), 'torch.nn.Dropout', 'nn.Dropout', (['p'], {}), '(p)\n', (897, 900), True, 'import torch.nn as nn\n'), ((838, 853), 'torch.nn.Dropout2d', 'nn.Dropout2d', (['p'], {}), '(p)\n', (850, 853), True, 'import torch.nn as nn\n')]
import logging # # Local imports from rdigraphs.sgtaskmanager import SgTaskManager # ##################### # PROBABLY USELESS from pathlib import Path import platform # This is to solve a known incompatibility issue between matplotlib and # tkinter on mac os. if platform.system() == 'Darwin': # Darwin is the system name for mac os. # IMPORTANT: THIS CODE MUST BE LOCATED BEFORE ANY OTHER IMPORT TO # MATPLOTLIB OR TO A LIBRARY IMPORTING FROM MATPLOTLIB import matplotlib matplotlib.use('TkAgg') # #################################### # Imports for the VALIDATION module from rdigraphs.supergraph.validator import Validator class ValTaskManager(SgTaskManager): """ Main class of the Everis project. The behavior of this class depends on the state of the project, in dictionary self.state, with the followin entries: - 'isProject' : If True, project created. Metadata variables loaded - 'cfReady' : If True, config file succesfully loaded. Datamanager activated. - 'dbReady' : It True, the project can connect to a database """ # This is a dictionary that contains a list to all subdirectories # that should exist in the project folder _valid_corpus = ['S2', 'K'] _dir_struct = {'val': Path('.'), 'valmodels': Path('models'), 'valoutput': Path('output')} _ref_col = {'S2': 'paperID', 'RG': 'pmid', 'K': 'pmid'} _corpus_name = 'K' _label_RG = 'RG' def __init__(self, path2project, paths2data): """ Initializes the validation task manager object Parameters ---------- path2project : str Path to the graph processing project paths2data : dict Paths to data sources """ super().__init__(path2project, paths2data) self.path2project = Path(self.path2project) print('-- Task Manager object succesfully initialized') # Path to the validation folder for the given corpus self.path2val = self.path2project / self._dir_struct['val'] # Output path to the given corpus self.path2out = self.path2project / self._dir_struct['valoutput'] return def setup(self): """ Sets up the project. To do so: - Loads the configuration file and initializes the data manager. - Informs on whether the DDBB structure is ready or not """ # Creates Data Manager object. Upon creation the object # will try to connect only to the Database of the project itself super().setup() ################## # Validator object self.models_2_validate = {} for corpus in self._valid_corpus: ref_col = self._ref_col[corpus] self.models_2_validate[corpus] = { 'ref_col': ref_col, 'path2nodenames': Path(self.path2tm) / 'metadata_models.csv', 'path2models': Path(self.path2tm)} # Other validation parameters self.val_params = { 'epn': self.global_parameters['validate_all_models']['epn'], 'ref_graph_prefix': self.global_parameters[ 'validate_all_models']['ref_graph_prefix'], 'ref_graph_epn': self.global_parameters[ 'validate_all_models']['ref_graph_epn'], 'ref_graph_nodes_init': self.global_parameters[ 'validate_all_models']['ref_graph_nodes_init'], 'ref_graph_nodes_target': self.global_parameters[ 'validate_all_models']['ref_graph_nodes_target'], 'blocksize': self.global_parameters['algorithms']['blocksize'], 'useGPU': self.global_parameters['algorithms']['useGPU'] == 'True'} self.state['configReady'] = True logging.info('-- Project setup finished') return def compute_all_sim_graphs(self): """ Computes all similarity graphs from the available topic models for a given corpus, and save them in a supergraph structure, to be used later in validation processes. """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.compute_all_sim_graphs() return def compute_reference_graph(self): """ Computes a reference graph for a given corpus, based on metadata. """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.compute_reference_graph() return def subsample_reference_graph(self): """ Computes a reference graph for a given corpus, based on metadata. """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.subsample_reference_graph() return def validate_topic_models(self): """ Analyzes the influence of the topic model on te quality of the similarity graphs The similarity graph is validated using a citations graph. """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.validate_topic_models() return def show_validation_results(self): """ Shows the results of the topic model validation in self.validate_topic_models() """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.show_validation_results() return def analyze_variability(self): """ Analyzes the influence of the topic model on te quality of the similarity graphs The similarity graph is validated from the analisys of the variability of node relationships in the graph """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.analyze_variability() return def show_variability_results(self): """ Shows the results of the topic model validation in self.validate_topic_models() """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.show_variability_results() return def analyze_scalability(self): """ Analyzes the influence of the topic model on te quality of the similarity graphs The similarity graph is validated using a citations graph. """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.analyze_scalability() return def show_scalability_results(self): """ Shows the results of the topic model validation in self.validate_topic_models() """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DMs, model2val, self.path2val, self.path2out, **self.val_params) V.show_scalability_results() return def validate_subtrain_models(self): """ Validates topics models obtained using a reduced corpus, using a gold standard based o a large corpus """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.validate_subtrain_models() return def show_subtrain_results(self): """ Shows the results of the topic model validation in self.validate_subtrain_models() """ # Path to the topic models folder model2val = self.models_2_validate[self._corpus_name] V = Validator(self._corpus_name, self.DM, model2val, self.path2val, self.path2out, **self.val_params) V.show_subtrain_results() return
[ "logging.info", "pathlib.Path", "matplotlib.use", "platform.system", "rdigraphs.supergraph.validator.Validator" ]
[((266, 283), 'platform.system', 'platform.system', ([], {}), '()\n', (281, 283), False, 'import platform\n'), ((507, 530), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (521, 530), False, 'import matplotlib\n'), ((1308, 1317), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (1312, 1317), False, 'from pathlib import Path\n'), ((1351, 1365), 'pathlib.Path', 'Path', (['"""models"""'], {}), "('models')\n", (1355, 1365), False, 'from pathlib import Path\n'), ((1399, 1413), 'pathlib.Path', 'Path', (['"""output"""'], {}), "('output')\n", (1403, 1413), False, 'from pathlib import Path\n'), ((1906, 1929), 'pathlib.Path', 'Path', (['self.path2project'], {}), '(self.path2project)\n', (1910, 1929), False, 'from pathlib import Path\n'), ((3864, 3905), 'logging.info', 'logging.info', (['"""-- Project setup finished"""'], {}), "('-- Project setup finished')\n", (3876, 3905), False, 'import logging\n'), ((4292, 4394), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (4301, 4394), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((4718, 4820), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (4727, 4820), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((5147, 5249), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (5156, 5249), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((5665, 5767), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (5674, 5767), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((6112, 6214), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (6121, 6214), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((6681, 6783), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (6690, 6783), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((7127, 7229), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (7136, 7229), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((7642, 7744), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (7651, 7744), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((8088, 8191), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DMs', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DMs, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (8097, 8191), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((8562, 8664), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (8571, 8664), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((9013, 9115), 'rdigraphs.supergraph.validator.Validator', 'Validator', (['self._corpus_name', 'self.DM', 'model2val', 'self.path2val', 'self.path2out'], {}), '(self._corpus_name, self.DM, model2val, self.path2val, self.\n path2out, **self.val_params)\n', (9022, 9115), False, 'from rdigraphs.supergraph.validator import Validator\n'), ((3019, 3037), 'pathlib.Path', 'Path', (['self.path2tm'], {}), '(self.path2tm)\n', (3023, 3037), False, 'from pathlib import Path\n'), ((2944, 2962), 'pathlib.Path', 'Path', (['self.path2tm'], {}), '(self.path2tm)\n', (2948, 2962), False, 'from pathlib import Path\n')]
# -*- encoding: utf-8 -*- """Information about the backend H2O cluster.""" from __future__ import division, print_function, absolute_import, unicode_literals import sys import time import h2o from h2o.exceptions import H2OConnectionError, H2OServerError from h2o.display import H2ODisplay from h2o.utils.compatibility import * # NOQA from h2o.utils.typechecks import assert_is_type from h2o.utils.shared_utils import get_human_readable_bytes, get_human_readable_time class H2OCluster(object): """ Information about the backend H2O cluster. This object is available from ``h2o.cluster()`` or ``h2o.connection().cluster``, and its purpose is to provide basic information / manipulation methods for the underlying cluster. """ # If information is this many seconds old, it will be refreshed next time you call :meth:`status`. REFRESH_INTERVAL = 1.0 def __init__(self): """Initialize new H2OCluster instance.""" self._props = {} self._retrieved_at = None @staticmethod def from_kvs(keyvals): """ Create H2OCluster object from a list of key-value pairs. TODO: This method should be moved into the base H2OResponse class. """ obj = H2OCluster() obj._retrieved_at = time.time() for k, v in keyvals: if k in {"__meta", "_exclude_fields", "__schema"}: continue if k in _cloud_v3_valid_keys: obj._props[k] = v else: raise AttributeError("Attribute %s cannot be set on H2OCluster (= %r)" % (k, v)) return obj @property def skip_ticks(self): return self._props.get("skip_ticks", None) @property def bad_nodes(self): return self._props["bad_nodes"] @property def branch_name(self): return self._props["branch_name"] @property def build_number(self): return self._props["build_number"] @property def build_age(self): # If the build age is unknown, then the cluster is so old it comes from "prehistoric" times when no # build number reporting was done... return self._props.get("build_age", "PREHISTORIC") @property def build_too_old(self): # If the prop "build_too_old" wasn't reported by the server, then it's definitely too old :) return self._props.get("build_too_old", True) @property def cloud_healthy(self): return self._props["cloud_healthy"] @property def cloud_name(self): return self._props["cloud_name"] @property def cloud_size(self): return self._props["cloud_size"] @property def cloud_uptime_millis(self): return self._props["cloud_uptime_millis"] @property def cloud_internal_timezone(self): return self._props["cloud_internal_timezone"] @property def datafile_parser_timezone(self): return self._props["datafile_parser_timezone"] @property def consensus(self): return self._props["consensus"] @property def is_client(self): return self._props["is_client"] @property def locked(self): return self._props["locked"] @property def node_idx(self): return self._props["node_idx"] @property def nodes(self): return self._props["nodes"] @property def version(self): return self._props["version"] @property def internal_security_enabled(self): return self._props["internal_security_enabled"] def node(self,node_idx): """ Get information about a particular node in an H2O cluster (node index is 0 based) Information includes the following: nthreads: Number of threads pid: PID of current H2O process mem_value_size: Data on Node memory max_disk: Max disk free_disk: Free disk open_fds: Open File Descripters swap_mem: Size of data on node's disk tcps_active: Open TCP connections num_cpus: Number of cpus cpus_allowed: CPU's allowed gflops: Linpack GFlops fjthrds: F/J Thread count, by priority mem_bw: Memory bandwith fjqueue: F/J Task count, by priority my_cpu_pct: System CPU percentage used by this H2O process in last interval pojo_mem: Temp (non Data) memory num_keys: Number of local keys ip_port: IP address and port in the form a.b.c.d:e last_ping: Time (in msec) of last ping rpcs_active: Active Remote Procedure Calls max_mem: Maximum memory size for node healthy: (now-last_ping)<HeartbeatThread.TIMEOUT sys_load: System load; average #runnables/#cores sys_cpu_pct: System CPU percentage used by everything in last interval free_mem: Free heap h2o: IP :param node_idx: An int value indicating which node to extract information from :returns: Dictionary containing node info :examples: >>>import h2o >>>h2o.init() >>>node_one = h2o.cluster().node(0) >>>node_one["pid"] #Get PID for first node in H2O Cluster """ return self.nodes[node_idx] def shutdown(self, prompt=False): """ Shut down the server. This method checks if the H2O cluster is still running, and if it does shuts it down (via a REST API call). :param prompt: A logical value indicating whether to prompt the user before shutting down the H2O server. """ if not self.is_running(): return assert_is_type(prompt, bool) if prompt: question = "Are you sure you want to shutdown the H2O instance running at %s (Y/N)? " \ % h2o.connection().base_url response = input(question) # works in Py2 & Py3 because redefined in h2o.utils.compatibility module else: response = "Y" if response.lower() in {"y", "yes"}: h2o.api("POST /3/Shutdown") h2o.connection().close() def is_running(self): """ Determine if the H2O cluster is running or not. :returns: True if the cluster is up; False otherwise """ try: if h2o.connection().local_server and not h2o.connection().local_server.is_running(): return False h2o.api("GET /") return True except (H2OConnectionError, H2OServerError): return False def show_status(self, detailed=False): """ Print current cluster status information. :param detailed: if True, then also print detailed information about each node. """ if self._retrieved_at + self.REFRESH_INTERVAL < time.time(): # Info is stale, need to refresh new_info = h2o.api("GET /3/Cloud") self._fill_from_h2ocluster(new_info) ncpus = sum(node["num_cpus"] for node in self.nodes) allowed_cpus = sum(node["cpus_allowed"] for node in self.nodes) free_mem = sum(node["free_mem"] for node in self.nodes) unhealthy_nodes = sum(not node["healthy"] for node in self.nodes) status = "locked" if self.locked else "accepting new members" if unhealthy_nodes == 0: status += ", healthy" else: status += ", %d nodes are not healthy" % unhealthy_nodes api_extensions = self.list_api_extensions() H2ODisplay([ ["H2O cluster uptime:", get_human_readable_time(self.cloud_uptime_millis)], ["H2O cluster timezone:", self.cloud_internal_timezone], ["H2O data parsing timezone:", self.datafile_parser_timezone], ["H2O cluster version:", self.version], ["H2O cluster version age:", "{} {}".format(self.build_age, ("!!!" if self.build_too_old else ""))], ["H2O cluster name:", self.cloud_name], ["H2O cluster total nodes:", self.cloud_size], ["H2O cluster free memory:", get_human_readable_bytes(free_mem)], ["H2O cluster total cores:", str(ncpus)], ["H2O cluster allowed cores:", str(allowed_cpus)], ["H2O cluster status:", status], ["H2O connection url:", h2o.connection().base_url], ["H2O connection proxy:", h2o.connection().proxy], ["H2O internal security:", self.internal_security_enabled], ["H2O API Extensions:", ', '.join(api_extensions)], ["Python version:", "%d.%d.%d %s" % tuple(sys.version_info[:4])], ]) if detailed: keys = ["h2o", "healthy", "last_ping", "num_cpus", "sys_load", "mem_value_size", "free_mem", "pojo_mem", "swap_mem", "free_disk", "max_disk", "pid", "num_keys", "tcps_active", "open_fds", "rpcs_active"] header = ["Nodes info:"] + ["Node %d" % (i + 1) for i in range(len(self.nodes))] table = [[k] for k in keys] for node in self.nodes: for i, k in enumerate(keys): table[i].append(node[k]) H2ODisplay(table=table, header=header) def network_test(self): """Test network connectivity.""" res = h2o.api("GET /3/NetworkTest") res["table"].show() def list_all_extensions(self): """List all available extensions on the h2o backend""" return self._list_extensions("Capabilities") def list_core_extensions(self): """List available core extensions on the h2o backend""" return self._list_extensions("Capabilities/Core") def list_api_extensions(self): """List available API extensions on the h2o backend""" return self._list_extensions("Capabilities/API") @property def timezone(self): """Current timezone of the H2O cluster.""" return h2o.rapids("(getTimeZone)")["string"] @timezone.setter def timezone(self, tz): assert_is_type(tz, str) h2o.rapids('(setTimeZone "%s")' % tz) def list_timezones(self): """Return the list of all known timezones.""" from h2o.expr import ExprNode return h2o.H2OFrame._expr(expr=ExprNode("listTimeZones"))._frame() #------------------------------------------------------------------------------------------------------------------- # Private #------------------------------------------------------------------------------------------------------------------- def _fill_from_h2ocluster(self, other): """ Update information in this object from another H2OCluster instance. :param H2OCluster other: source of the new information for this object. """ self._props = other._props self._retrieved_at = other._retrieved_at other._props = {} other._retrieved_at = None def _list_extensions(self, endpoint): res = h2o.api("GET /3/" + endpoint)["capabilities"] return [x["name"] for x in res] _cloud_v3_valid_keys = {"is_client", "build_number", "cloud_name", "locked", "<KEY>", "consensus", "branch_name", "version", "cloud_uptime_millis", "cloud_internal_timezone", "datafile_parser_timezone", "cloud_healthy", "bad_nodes", "cloud_size", "skip_ticks", "nodes", "build_age", "build_too_old", "internal_security_enabled"}
[ "h2o.api", "time.time", "h2o.expr.ExprNode", "h2o.utils.shared_utils.get_human_readable_bytes", "h2o.utils.shared_utils.get_human_readable_time", "h2o.rapids", "h2o.utils.typechecks.assert_is_type", "h2o.connection", "h2o.display.H2ODisplay" ]
[((1282, 1293), 'time.time', 'time.time', ([], {}), '()\n', (1291, 1293), False, 'import time\n'), ((5596, 5624), 'h2o.utils.typechecks.assert_is_type', 'assert_is_type', (['prompt', 'bool'], {}), '(prompt, bool)\n', (5610, 5624), False, 'from h2o.utils.typechecks import assert_is_type\n'), ((9305, 9334), 'h2o.api', 'h2o.api', (['"""GET /3/NetworkTest"""'], {}), "('GET /3/NetworkTest')\n", (9312, 9334), False, 'import h2o\n'), ((10035, 10058), 'h2o.utils.typechecks.assert_is_type', 'assert_is_type', (['tz', 'str'], {}), '(tz, str)\n', (10049, 10058), False, 'from h2o.utils.typechecks import assert_is_type\n'), ((10067, 10104), 'h2o.rapids', 'h2o.rapids', (['(\'(setTimeZone "%s")\' % tz)'], {}), '(\'(setTimeZone "%s")\' % tz)\n', (10077, 10104), False, 'import h2o\n'), ((6006, 6033), 'h2o.api', 'h2o.api', (['"""POST /3/Shutdown"""'], {}), "('POST /3/Shutdown')\n", (6013, 6033), False, 'import h2o\n'), ((6376, 6392), 'h2o.api', 'h2o.api', (['"""GET /"""'], {}), "('GET /')\n", (6383, 6392), False, 'import h2o\n'), ((6759, 6770), 'time.time', 'time.time', ([], {}), '()\n', (6768, 6770), False, 'import time\n'), ((6840, 6863), 'h2o.api', 'h2o.api', (['"""GET /3/Cloud"""'], {}), "('GET /3/Cloud')\n", (6847, 6863), False, 'import h2o\n'), ((9181, 9219), 'h2o.display.H2ODisplay', 'H2ODisplay', ([], {'table': 'table', 'header': 'header'}), '(table=table, header=header)\n', (9191, 9219), False, 'from h2o.display import H2ODisplay\n'), ((9939, 9966), 'h2o.rapids', 'h2o.rapids', (['"""(getTimeZone)"""'], {}), "('(getTimeZone)')\n", (9949, 9966), False, 'import h2o\n'), ((10990, 11019), 'h2o.api', 'h2o.api', (["('GET /3/' + endpoint)"], {}), "('GET /3/' + endpoint)\n", (10997, 11019), False, 'import h2o\n'), ((5769, 5785), 'h2o.connection', 'h2o.connection', ([], {}), '()\n', (5783, 5785), False, 'import h2o\n'), ((6046, 6062), 'h2o.connection', 'h2o.connection', ([], {}), '()\n', (6060, 6062), False, 'import h2o\n'), ((6269, 6285), 'h2o.connection', 'h2o.connection', ([], {}), '()\n', (6283, 6285), False, 'import h2o\n'), ((7520, 7569), 'h2o.utils.shared_utils.get_human_readable_time', 'get_human_readable_time', (['self.cloud_uptime_millis'], {}), '(self.cloud_uptime_millis)\n', (7543, 7569), False, 'from h2o.utils.shared_utils import get_human_readable_bytes, get_human_readable_time\n'), ((8059, 8093), 'h2o.utils.shared_utils.get_human_readable_bytes', 'get_human_readable_bytes', (['free_mem'], {}), '(free_mem)\n', (8083, 8093), False, 'from h2o.utils.shared_utils import get_human_readable_bytes, get_human_readable_time\n'), ((8310, 8326), 'h2o.connection', 'h2o.connection', ([], {}), '()\n', (8324, 8326), False, 'import h2o\n'), ((8381, 8397), 'h2o.connection', 'h2o.connection', ([], {}), '()\n', (8395, 8397), False, 'import h2o\n'), ((10268, 10293), 'h2o.expr.ExprNode', 'ExprNode', (['"""listTimeZones"""'], {}), "('listTimeZones')\n", (10276, 10293), False, 'from h2o.expr import ExprNode\n'), ((6307, 6323), 'h2o.connection', 'h2o.connection', ([], {}), '()\n', (6321, 6323), False, 'import h2o\n')]
from flask import Blueprint, render_template, redirect, url_for from rest_api.forms.address import AddressCreateForm from rest_api.models.address import AddressModel address_bp = Blueprint("address", __name__) @address_bp.route("/create/<int:company_id><int:user_id>", methods=["GET", "POST"]) def address_create(company_id, user_id): form = AddressCreateForm() if form.validate_on_submit(): address = AddressModel( line1=form.line1.data, line2=form.line2.data, city=form.city.data, state=form.state.data, zip=form.zip.data, company_id=company_id, user_id =user_id ) address.save_to_db() return redirect(url_for("company.company_info")) return render_template("address_create.html", form=form) @address_bp.route("/update/<int:address_id>", methods=["GET","POST"]) def address_update(address_id): form = AddressCreateForm() address = AddressModel.find_by_id(address_id) if form.validate_on_submit(): address.line1 = form.line1.data address.line2 = form.line2.data address.city = form.city.data address.state= form.state.data address.zip = form.zip.data address.save_to_db() return redirect(url_for("company.company_info")) form.line1.data = address.line1 form.line2.data = address.line2 form.city.data = address.city form.state.data = address.state form.zip.data = address.zip return render_template("address_create.html", form = form) # @address_bp.route("/info") # def address_info(): # pass @address_bp.route("/delete/<int:address_id>", methods=["GET","POST"]) def address_delete(address_id): address = AddressModel.find_by_id(address_id) if address: address.delete_from_db() return redirect(url_for("company.company_info"))
[ "rest_api.models.address.AddressModel", "flask.Blueprint", "flask.url_for", "flask.render_template", "rest_api.forms.address.AddressCreateForm", "rest_api.models.address.AddressModel.find_by_id" ]
[((179, 209), 'flask.Blueprint', 'Blueprint', (['"""address"""', '__name__'], {}), "('address', __name__)\n", (188, 209), False, 'from flask import Blueprint, render_template, redirect, url_for\n'), ((351, 370), 'rest_api.forms.address.AddressCreateForm', 'AddressCreateForm', ([], {}), '()\n', (368, 370), False, 'from rest_api.forms.address import AddressCreateForm\n'), ((780, 829), 'flask.render_template', 'render_template', (['"""address_create.html"""'], {'form': 'form'}), "('address_create.html', form=form)\n", (795, 829), False, 'from flask import Blueprint, render_template, redirect, url_for\n'), ((945, 964), 'rest_api.forms.address.AddressCreateForm', 'AddressCreateForm', ([], {}), '()\n', (962, 964), False, 'from rest_api.forms.address import AddressCreateForm\n'), ((980, 1015), 'rest_api.models.address.AddressModel.find_by_id', 'AddressModel.find_by_id', (['address_id'], {}), '(address_id)\n', (1003, 1015), False, 'from rest_api.models.address import AddressModel\n'), ((1520, 1569), 'flask.render_template', 'render_template', (['"""address_create.html"""'], {'form': 'form'}), "('address_create.html', form=form)\n", (1535, 1569), False, 'from flask import Blueprint, render_template, redirect, url_for\n'), ((1759, 1794), 'rest_api.models.address.AddressModel.find_by_id', 'AddressModel.find_by_id', (['address_id'], {}), '(address_id)\n', (1782, 1794), False, 'from rest_api.models.address import AddressModel\n'), ((424, 594), 'rest_api.models.address.AddressModel', 'AddressModel', ([], {'line1': 'form.line1.data', 'line2': 'form.line2.data', 'city': 'form.city.data', 'state': 'form.state.data', 'zip': 'form.zip.data', 'company_id': 'company_id', 'user_id': 'user_id'}), '(line1=form.line1.data, line2=form.line2.data, city=form.city.\n data, state=form.state.data, zip=form.zip.data, company_id=company_id,\n user_id=user_id)\n', (436, 594), False, 'from rest_api.models.address import AddressModel\n'), ((1874, 1905), 'flask.url_for', 'url_for', (['"""company.company_info"""'], {}), "('company.company_info')\n", (1881, 1905), False, 'from flask import Blueprint, render_template, redirect, url_for\n'), ((735, 766), 'flask.url_for', 'url_for', (['"""company.company_info"""'], {}), "('company.company_info')\n", (742, 766), False, 'from flask import Blueprint, render_template, redirect, url_for\n'), ((1300, 1331), 'flask.url_for', 'url_for', (['"""company.company_info"""'], {}), "('company.company_info')\n", (1307, 1331), False, 'from flask import Blueprint, render_template, redirect, url_for\n')]
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from cuml.dask.common import raise_exception_from_futures from cuml.dask.common.comms import worker_state, CommsContext from cuml.dask.common.input_utils import to_output from cuml.dask.common.part_utils import flatten_grouped_results from dask.distributed import wait from cuml.dask.common.base import BaseEstimator from cuml.dask.common.input_utils import DistributedDataHandler class BaseDecomposition(BaseEstimator): def __init__(self, model_func, client=None, verbose=False, **kwargs): """ Constructor for distributed decomposition model """ super(BaseDecomposition, self).__init__(client=client, verbose=verbose, **kwargs) self._model_func = model_func # define attributes to make sure they # are available even on untrained object self.local_model = None self.components_ = None self.explained_variance_ = None self.explained_variance_ratio_ = None self.singular_values_ = None class DecompositionSyncFitMixin(object): @staticmethod def _func_fit(m, dfs, M, N, partsToRanks, rank, transform): return m.fit(dfs, M, N, partsToRanks, rank, transform) def _fit(self, X, _transform=False): """ Fit the model with X. Parameters ---------- X : dask cuDF input """ n_cols = X.shape[1] data = DistributedDataHandler.create(data=X, client=self.client) self.datatype = data.datatype comms = CommsContext(comms_p2p=False) comms.init(workers=data.workers) data.calculate_parts_to_sizes(comms) total_rows = data.total_rows models = dict([(data.worker_info[wf[0]]["rank"], self.client.submit( self._create_model, comms.sessionId, self._model_func, self.datatype, **self.kwargs, pure=False, workers=[wf[0]])) for idx, wf in enumerate(data.worker_to_parts.items())]) pca_fit = dict([(wf[0], self.client.submit( DecompositionSyncFitMixin._func_fit, models[data.worker_info[wf[0]]["rank"]], wf[1], total_rows, n_cols, data.parts_to_sizes[data.worker_info[wf[0]]["rank"]], data.worker_info[wf[0]]["rank"], _transform, pure=False, workers=[wf[0]])) for idx, wf in enumerate(data.worker_to_parts.items())]) wait(list(pca_fit.values())) raise_exception_from_futures(list(pca_fit.values())) comms.destroy() self.local_model = list(models.values())[0].result() self.components_ = self.local_model.components_ self.explained_variance_ = self.local_model.explained_variance_ self.explained_variance_ratio_ = \ self.local_model.explained_variance_ratio_ self.singular_values_ = self.local_model.singular_values_ if _transform: out_futures = flatten_grouped_results(self.client, data.gpu_futures, pca_fit) return to_output(out_futures, self.datatype) return self @staticmethod def _create_model(sessionId, model_func, datatype, **kwargs): handle = worker_state(sessionId)["handle"] return model_func(handle, datatype, **kwargs)
[ "cuml.dask.common.comms.CommsContext", "cuml.dask.common.input_utils.DistributedDataHandler.create", "cuml.dask.common.comms.worker_state", "cuml.dask.common.part_utils.flatten_grouped_results", "cuml.dask.common.input_utils.to_output" ]
[((2078, 2135), 'cuml.dask.common.input_utils.DistributedDataHandler.create', 'DistributedDataHandler.create', ([], {'data': 'X', 'client': 'self.client'}), '(data=X, client=self.client)\n', (2107, 2135), False, 'from cuml.dask.common.input_utils import DistributedDataHandler\n'), ((2191, 2220), 'cuml.dask.common.comms.CommsContext', 'CommsContext', ([], {'comms_p2p': '(False)'}), '(comms_p2p=False)\n', (2203, 2220), False, 'from cuml.dask.common.comms import worker_state, CommsContext\n'), ((3685, 3748), 'cuml.dask.common.part_utils.flatten_grouped_results', 'flatten_grouped_results', (['self.client', 'data.gpu_futures', 'pca_fit'], {}), '(self.client, data.gpu_futures, pca_fit)\n', (3708, 3748), False, 'from cuml.dask.common.part_utils import flatten_grouped_results\n'), ((3868, 3905), 'cuml.dask.common.input_utils.to_output', 'to_output', (['out_futures', 'self.datatype'], {}), '(out_futures, self.datatype)\n', (3877, 3905), False, 'from cuml.dask.common.input_utils import to_output\n'), ((4029, 4052), 'cuml.dask.common.comms.worker_state', 'worker_state', (['sessionId'], {}), '(sessionId)\n', (4041, 4052), False, 'from cuml.dask.common.comms import worker_state, CommsContext\n')]
"""Testing utils for jupyter_client tests """ import os import sys from tempfile import TemporaryDirectory from typing import Dict from unittest.mock import patch import pytest from jupyter_client import AsyncKernelManager from jupyter_client import AsyncMultiKernelManager from jupyter_client import KernelManager from jupyter_client import MultiKernelManager pjoin = os.path.join skip_win32 = pytest.mark.skipif(sys.platform.startswith("win"), reason="Windows") class test_env(object): """Set Jupyter path variables to a temporary directory Useful as a context manager or with explicit start/stop """ def start(self): self.test_dir = td = TemporaryDirectory() self.env_patch = patch.dict( os.environ, { "JUPYTER_CONFIG_DIR": pjoin(td.name, "jupyter"), "JUPYTER_DATA_DIR": pjoin(td.name, "jupyter_data"), "JUPYTER_RUNTIME_DIR": pjoin(td.name, "jupyter_runtime"), "IPYTHONDIR": pjoin(td.name, "ipython"), "TEST_VARS": "test_var_1", }, ) self.env_patch.start() def stop(self): self.env_patch.stop() self.test_dir.cleanup() def __enter__(self): self.start() return self.test_dir.name def __exit__(self, *exc_info): self.stop() def execute(code="", kc=None, **kwargs): """wrapper for doing common steps for validating an execution request""" from .test_message_spec import validate_message if kc is None: kc = KC # noqa msg_id = kc.execute(code=code, **kwargs) reply = kc.get_shell_msg(timeout=TIMEOUT) # noqa validate_message(reply, "execute_reply", msg_id) busy = kc.get_iopub_msg(timeout=TIMEOUT) # noqa validate_message(busy, "status", msg_id) assert busy["content"]["execution_state"] == "busy" if not kwargs.get("silent"): execute_input = kc.get_iopub_msg(timeout=TIMEOUT) # noqa validate_message(execute_input, "execute_input", msg_id) assert execute_input["content"]["code"] == code return msg_id, reply["content"] class RecordCallMixin: method_calls: Dict[str, int] def __init__(self, **kwargs): super().__init__(**kwargs) self.method_calls = {} def record(self, method_name: str) -> None: if method_name not in self.method_calls: self.method_calls[method_name] = 0 self.method_calls[method_name] += 1 def call_count(self, method_name: str) -> int: if method_name not in self.method_calls: self.method_calls[method_name] = 0 return self.method_calls[method_name] def reset_counts(self) -> None: for record in self.method_calls: self.method_calls[record] = 0 def subclass_recorder(f): def wrapped(self, *args, **kwargs): # record this call self.record(f.__name__) method = getattr(self._superclass, f.__name__) # call the superclass method r = method(self, *args, **kwargs) # call anything defined in the actual class method f(self, *args, **kwargs) return r return wrapped class KMSubclass(RecordCallMixin): @subclass_recorder def start_kernel(self, **kw): """ Record call and defer to superclass """ @subclass_recorder def shutdown_kernel(self, now=False, restart=False): """ Record call and defer to superclass """ @subclass_recorder def restart_kernel(self, now=False, **kw): """ Record call and defer to superclass """ @subclass_recorder def interrupt_kernel(self): """ Record call and defer to superclass """ @subclass_recorder def request_shutdown(self, restart=False): """ Record call and defer to superclass """ @subclass_recorder def finish_shutdown(self, waittime=None, pollinterval=0.1): """ Record call and defer to superclass """ @subclass_recorder def _launch_kernel(self, kernel_cmd, **kw): """ Record call and defer to superclass """ @subclass_recorder def _kill_kernel(self): """ Record call and defer to superclass """ @subclass_recorder def cleanup_resources(self, restart=False): """ Record call and defer to superclass """ class SyncKMSubclass(KMSubclass, KernelManager): _superclass = KernelManager class AsyncKMSubclass(KMSubclass, AsyncKernelManager): """Used to test subclass hierarchies to ensure methods are called when expected. This class is also used to test deprecation "routes" that are determined by superclass' detection of methods. This class represents a current subclass that overrides "interesting" methods of AsyncKernelManager. """ _superclass = AsyncKernelManager which_cleanup = "" # cleanup deprecation testing @subclass_recorder def cleanup(self, connection_file=True): self.which_cleanup = "cleanup" @subclass_recorder def cleanup_resources(self, restart=False): self.which_cleanup = "cleanup_resources" class AsyncKernelManagerWithCleanup(AsyncKernelManager): """Used to test deprecation "routes" that are determined by superclass' detection of methods. This class represents the older subclass that overrides cleanup(). We should find that cleanup() is called on these instances via TestAsyncKernelManagerWithCleanup. """ def cleanup(self, connection_file=True): super().cleanup(connection_file=connection_file) self.which_cleanup = "cleanup" class MKMSubclass(RecordCallMixin): def _kernel_manager_class_default(self): return "jupyter_client.tests.utils.SyncKMSubclass" @subclass_recorder def get_kernel(self, kernel_id): """ Record call and defer to superclass """ @subclass_recorder def remove_kernel(self, kernel_id): """ Record call and defer to superclass """ @subclass_recorder def start_kernel(self, kernel_name=None, **kwargs): """ Record call and defer to superclass """ @subclass_recorder def shutdown_kernel(self, kernel_id, now=False, restart=False): """ Record call and defer to superclass """ @subclass_recorder def restart_kernel(self, kernel_id, now=False): """ Record call and defer to superclass """ @subclass_recorder def interrupt_kernel(self, kernel_id): """ Record call and defer to superclass """ @subclass_recorder def request_shutdown(self, kernel_id, restart=False): """ Record call and defer to superclass """ @subclass_recorder def finish_shutdown(self, kernel_id, waittime=None, pollinterval=0.1): """ Record call and defer to superclass """ @subclass_recorder def cleanup_resources(self, kernel_id, restart=False): """ Record call and defer to superclass """ @subclass_recorder def shutdown_all(self, now=False): """ Record call and defer to superclass """ class SyncMKMSubclass(MKMSubclass, MultiKernelManager): _superclass = MultiKernelManager def _kernel_manager_class_default(self): return "jupyter_client.tests.utils.SyncKMSubclass" class AsyncMKMSubclass(MKMSubclass, AsyncMultiKernelManager): _superclass = AsyncMultiKernelManager def _kernel_manager_class_default(self): return "jupyter_client.tests.utils.AsyncKMSubclass"
[ "sys.platform.startswith", "tempfile.TemporaryDirectory" ]
[((419, 449), 'sys.platform.startswith', 'sys.platform.startswith', (['"""win"""'], {}), "('win')\n", (442, 449), False, 'import sys\n'), ((674, 694), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (692, 694), False, 'from tempfile import TemporaryDirectory\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- from fastapi import APIRouter, File, UploadFile from plugins.github import Github from utils.spider import put, delete from config import * import time router = APIRouter() @router.get("/trending/", include_in_schema=True) async def trending(type: str = "trending", date: str = "daily", spoken_lang: str = None, language: str = None): log.info("pv,请求一次Github Trending") if type in ['trending', 'developers']: github = Github(type, date, spoken_lang, language) return { "status": 200, "copyright": Copyright, "data": github.trending if type == 'trending' else github.developers, "time": time.ctime(), } @router.post('/upload/', include_in_schema=True) async def upload(user, email, token, repo, path='', file: UploadFile = File(...)): if file.filename: log.info(f'pv,上传文件{file.filename}') url = f'https://api.github.com/repos/{user}/{repo}/contents/{path+file.filename}' data = { "message": "upload By LickingDogAPI", "committer": { "name": user, "email": email }, "content": file } headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,en-US;q=0.7,en;q=0.3", "User-Agent": ua.random, "Authorization": f"token {token}" } # PUT https://api.github.com/repos/{user}/{repo}/contents/{path}/{filename} response = put(url=url, data=data, headers=headers) return response.json() @router.delete('/delete/', include_in_schema=True) async def delete(user, repo, token, path='', filename=File(...)): url = f'https://api.github.com/repos/{user}/{repo}/contents/{path+filename}' # DELETE https://api.github.com/repos/{user}/{repo}/contents/{path}/{filename} headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,en-US;q=0.7,en;q=0.3", "User-Agent": ua.random, "Authorization": f"token {token}" } response = delete(url=url, data=None, headers=headers) return response.json()
[ "time.ctime", "plugins.github.Github", "fastapi.File", "utils.spider.put", "utils.spider.delete", "fastapi.APIRouter" ]
[((207, 218), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (216, 218), False, 'from fastapi import APIRouter, File, UploadFile\n'), ((909, 918), 'fastapi.File', 'File', (['...'], {}), '(...)\n', (913, 918), False, 'from fastapi import APIRouter, File, UploadFile\n'), ((1830, 1839), 'fastapi.File', 'File', (['...'], {}), '(...)\n', (1834, 1839), False, 'from fastapi import APIRouter, File, UploadFile\n'), ((2260, 2303), 'utils.spider.delete', 'delete', ([], {'url': 'url', 'data': 'None', 'headers': 'headers'}), '(url=url, data=None, headers=headers)\n', (2266, 2303), False, 'from utils.spider import put, delete\n'), ((539, 580), 'plugins.github.Github', 'Github', (['type', 'date', 'spoken_lang', 'language'], {}), '(type, date, spoken_lang, language)\n', (545, 580), False, 'from plugins.github import Github\n'), ((1651, 1691), 'utils.spider.put', 'put', ([], {'url': 'url', 'data': 'data', 'headers': 'headers'}), '(url=url, data=data, headers=headers)\n', (1654, 1691), False, 'from utils.spider import put, delete\n'), ((763, 775), 'time.ctime', 'time.ctime', ([], {}), '()\n', (773, 775), False, 'import time\n')]
from urllib.parse import urljoin from twisted.web import resource from twisted.web import server from twisted.web import static from twisted.web import util class SiteTest: def setUp(self): from twisted.internet import reactor super().setUp() self.site = reactor.listenTCP(0, test_site(), interface="127.0.0.1") self.baseurl = "http://localhost:%d/" % self.site.getHost().port def tearDown(self): super().tearDown() self.site.stopListening() def url(self, path): return urljoin(self.baseurl, path) class NoMetaRefreshRedirect(util.Redirect): def render(self, request): content = util.Redirect.render(self, request) return content.replace(b'http-equiv="refresh"', b'http-no-equiv="do-not-refresh-me"') def test_site(): r = resource.Resource() r.putChild(b"text", static.Data(b"Works", "text/plain")) r.putChild( b"html", static.Data( b"<body><p class='one'>Works</p><p class='two'>World</p></body>", "text/html", ), ) r.putChild( b"enc-gb18030", static.Data(b"<p>gb18030 encoding</p>", "text/html; charset=gb18030"), ) r.putChild(b"redirect", util.Redirect(b"/redirected")) r.putChild(b"redirect-no-meta-refresh", NoMetaRefreshRedirect(b"/redirected")) r.putChild(b"redirected", static.Data(b"Redirected here", "text/plain")) return server.Site(r) if __name__ == "__main__": from twisted.internet import reactor port = reactor.listenTCP(0, test_site(), interface="127.0.0.1") print("http://localhost:%d/" % port.getHost().port) reactor.run()
[ "urllib.parse.urljoin", "twisted.web.util.Redirect.render", "twisted.web.static.Data", "twisted.web.resource.Resource", "twisted.internet.reactor.run", "twisted.web.util.Redirect", "twisted.web.server.Site" ]
[((855, 874), 'twisted.web.resource.Resource', 'resource.Resource', ([], {}), '()\n', (872, 874), False, 'from twisted.web import resource\n'), ((1480, 1494), 'twisted.web.server.Site', 'server.Site', (['r'], {}), '(r)\n', (1491, 1494), False, 'from twisted.web import server\n'), ((1694, 1707), 'twisted.internet.reactor.run', 'reactor.run', ([], {}), '()\n', (1705, 1707), False, 'from twisted.internet import reactor\n'), ((544, 571), 'urllib.parse.urljoin', 'urljoin', (['self.baseurl', 'path'], {}), '(self.baseurl, path)\n', (551, 571), False, 'from urllib.parse import urljoin\n'), ((667, 702), 'twisted.web.util.Redirect.render', 'util.Redirect.render', (['self', 'request'], {}), '(self, request)\n', (687, 702), False, 'from twisted.web import util\n'), ((899, 934), 'twisted.web.static.Data', 'static.Data', (["b'Works'", '"""text/plain"""'], {}), "(b'Works', 'text/plain')\n", (910, 934), False, 'from twisted.web import static\n'), ((977, 1071), 'twisted.web.static.Data', 'static.Data', (['b"<body><p class=\'one\'>Works</p><p class=\'two\'>World</p></body>"', '"""text/html"""'], {}), '(b"<body><p class=\'one\'>Works</p><p class=\'two\'>World</p></body>",\n \'text/html\')\n', (988, 1071), False, 'from twisted.web import static\n'), ((1158, 1227), 'twisted.web.static.Data', 'static.Data', (["b'<p>gb18030 encoding</p>'", '"""text/html; charset=gb18030"""'], {}), "(b'<p>gb18030 encoding</p>', 'text/html; charset=gb18030')\n", (1169, 1227), False, 'from twisted.web import static\n'), ((1263, 1292), 'twisted.web.util.Redirect', 'util.Redirect', (["b'/redirected'"], {}), "(b'/redirected')\n", (1276, 1292), False, 'from twisted.web import util\n'), ((1422, 1467), 'twisted.web.static.Data', 'static.Data', (["b'Redirected here'", '"""text/plain"""'], {}), "(b'Redirected here', 'text/plain')\n", (1433, 1467), False, 'from twisted.web import static\n')]
import math import torch import gpytorch import numpy as np import random from matplotlib import pyplot as plt from pssgp.kernels import MyMaternKernel from unittest import TestCase # We will use the simplest form of GP model, exact inference class ExactGPModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood, use_gpy): super(ExactGPModel, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() if use_gpy: self.covar_module = gpytorch.kernels.ScaleKernel( gpytorch.kernels.MaternKernel(nu=1.5)) else: self.covar_module = MyMaternKernel(nu=1.5) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) def run(model,likelihood, train_x, train_y): # Find optimal model hyperparameters model.train() likelihood.train() # Use the adam optimizer optimizer = torch.optim.Adam(model.parameters(), lr=0.1) # Includes GaussianLikelihood parameters # "Loss" for GPs - the marginal log likelihood mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model) for i in range(50): # Zero gradients from previous iteration optimizer.zero_grad() # Output from model output = model(train_x) # Calc loss and backprop gradients loss = -mll(output, train_y) loss.backward() # print('Iter %d/%d - Loss: %.3f lengthscale: %.3f noise: %.3f' % ( # i + 1, 50, loss.item(), # model.covar_module.base_kernel.lengthscale.item(), # model.likelihood.noise.item() # )) optimizer.step() # Get into evaluation (predictive posterior) mode model.eval() likelihood.eval() # Test points are regularly spaced along [0,1] # Make predictions by feeding model through likelihood with torch.no_grad(), gpytorch.settings.fast_pred_var(): test_x = torch.linspace(0, 1, 51) observed_pred = likelihood(model(test_x)) return observed_pred class TestCompatitibilityWithGpyTorch(TestCase): def setUp(self) -> None: torch.manual_seed(0) np.random.seed(0) random.seed(0) torch.use_deterministic_algorithms(True) torch.backends.cudnn.benchmark = True # Training data is 100 points in [0,1] inclusive regularly spaced self.train_x = torch.linspace(0, 1, 100) # True function is sin(2*pi*x) with Gaussian noise self.train_y = torch.sin(self.train_x * (2 * math.pi)) + \ torch.randn(self.train_x.size()) * math.sqrt(0.04) # self.likelihood = gpytorch.likelihoods.GaussianLikelihood() def test_result(self): likelihood1 = gpytorch.likelihoods.GaussianLikelihood() gpymodel = ExactGPModel(self.train_x, self.train_y, likelihood1, use_gpy=True) likelihood2 = gpytorch.likelihoods.GaussianLikelihood() mymodel = ExactGPModel(self.train_x, self.train_y, likelihood2, use_gpy=False) result1 = run(gpymodel, likelihood1, train_x=self.train_x, train_y=self.train_y) result2 = run(mymodel, likelihood2, train_x=self.train_x, train_y=self.train_y) assert torch.allclose(result1.loc, result2.loc)
[ "numpy.random.seed", "gpytorch.distributions.MultivariateNormal", "gpytorch.mlls.ExactMarginalLogLikelihood", "math.sqrt", "torch.manual_seed", "gpytorch.settings.fast_pred_var", "pssgp.kernels.MyMaternKernel", "gpytorch.kernels.MaternKernel", "random.seed", "gpytorch.likelihoods.GaussianLikelihood", "gpytorch.means.ConstantMean", "torch.linspace", "torch.use_deterministic_algorithms", "torch.no_grad", "torch.allclose", "torch.sin" ]
[((1210, 1269), 'gpytorch.mlls.ExactMarginalLogLikelihood', 'gpytorch.mlls.ExactMarginalLogLikelihood', (['likelihood', 'model'], {}), '(likelihood, model)\n', (1250, 1269), False, 'import gpytorch\n'), ((453, 482), 'gpytorch.means.ConstantMean', 'gpytorch.means.ConstantMean', ([], {}), '()\n', (480, 482), False, 'import gpytorch\n'), ((828, 886), 'gpytorch.distributions.MultivariateNormal', 'gpytorch.distributions.MultivariateNormal', (['mean_x', 'covar_x'], {}), '(mean_x, covar_x)\n', (869, 886), False, 'import gpytorch\n'), ((2017, 2032), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2030, 2032), False, 'import torch\n'), ((2034, 2067), 'gpytorch.settings.fast_pred_var', 'gpytorch.settings.fast_pred_var', ([], {}), '()\n', (2065, 2067), False, 'import gpytorch\n'), ((2086, 2110), 'torch.linspace', 'torch.linspace', (['(0)', '(1)', '(51)'], {}), '(0, 1, 51)\n', (2100, 2110), False, 'import torch\n'), ((2276, 2296), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (2293, 2296), False, 'import torch\n'), ((2305, 2322), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2319, 2322), True, 'import numpy as np\n'), ((2331, 2345), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (2342, 2345), False, 'import random\n'), ((2354, 2394), 'torch.use_deterministic_algorithms', 'torch.use_deterministic_algorithms', (['(True)'], {}), '(True)\n', (2388, 2394), False, 'import torch\n'), ((2539, 2564), 'torch.linspace', 'torch.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (2553, 2564), False, 'import torch\n'), ((2881, 2922), 'gpytorch.likelihoods.GaussianLikelihood', 'gpytorch.likelihoods.GaussianLikelihood', ([], {}), '()\n', (2920, 2922), False, 'import gpytorch\n'), ((3144, 3185), 'gpytorch.likelihoods.GaussianLikelihood', 'gpytorch.likelihoods.GaussianLikelihood', ([], {}), '()\n', (3183, 3185), False, 'import gpytorch\n'), ((3563, 3603), 'torch.allclose', 'torch.allclose', (['result1.loc', 'result2.loc'], {}), '(result1.loc, result2.loc)\n', (3577, 3603), False, 'import torch\n'), ((687, 709), 'pssgp.kernels.MyMaternKernel', 'MyMaternKernel', ([], {'nu': '(1.5)'}), '(nu=1.5)\n', (701, 709), False, 'from pssgp.kernels import MyMaternKernel\n'), ((2647, 2686), 'torch.sin', 'torch.sin', (['(self.train_x * (2 * math.pi))'], {}), '(self.train_x * (2 * math.pi))\n', (2656, 2686), False, 'import torch\n'), ((602, 639), 'gpytorch.kernels.MaternKernel', 'gpytorch.kernels.MaternKernel', ([], {'nu': '(1.5)'}), '(nu=1.5)\n', (631, 639), False, 'import gpytorch\n'), ((2744, 2759), 'math.sqrt', 'math.sqrt', (['(0.04)'], {}), '(0.04)\n', (2753, 2759), False, 'import math\n')]
import builtins import hashlib import json import base64 from flask import Flask from flask.globals import request from google.cloud import bigquery import datetime app = Flask(__name__) def process_jenkins_event(msg): envelope = json.loads(base64.b64decode(msg["data"]).decode("utf-8").strip()) #envelope = request.get_json() #headers = dict(request.headers) source = "jenkins" #body = request.data e_id = envelope.get("id") epoch = envelope.get("timestamp")/1000 time_created = datetime.datetime.utcfromtimestamp(epoch).strftime('%Y-%m-%d %H:%M:%S') #msg_id = envelope.get("number") actions = envelope.get("actions") commit = actions[3].get("lastBuiltRevision").get("SHA1") if commit: main_commit = commit else: main_commit = actions[4].get("lastBuiltRevision").get("SHA1") metadata = { "result": envelope.get("result"), "url": envelope.get("url"), "mainCommit": main_commit } msg_for_sign = envelope.get("fullDisplayName") signature = create_unique_id(msg_for_sign) build_event = { "event_type": 'build', "id": e_id, "metadata": json.dumps(metadata), "time_created": time_created, "signature": signature, "msg_id": msg["message_id"], "source": source, } # Publish to Pub/Sub # publish_to_pubsub(source, body, headers) insert_row_into_bigquery(build_event) return build_event def insert_row_into_bigquery(event): if not event: raise Exception("No data to insert") # Set up bigquery instance client = bigquery.Client() dataset_id = "four_keys" table_id = "events_raw" if is_unique(client, event["signature"]): table_ref = client.dataset(dataset_id).table(table_id) table = client.get_table(table_ref) # Insert row row_to_insert = [ ( event["event_type"], event["id"], event["metadata"], event["time_created"], event["signature"], event["msg_id"], event["source"], ) ] bq_errors = client.insert_rows(table, row_to_insert) # If errors, log to Stackdriver if bq_errors: entry = { "severity": "WARNING", "msg": "Row not inserted.", "errors": bq_errors, "row": row_to_insert, } print(json.dumps(entry)) def create_unique_id(msg): hashed = hashlib.sha1(bytes(json.dumps(msg), "utf-8")) return hashed.hexdigest() def is_unique(client, signature): sql = "SELECT signature FROM four_keys.events_raw WHERE signature = '%s'" query_job = client.query(sql % signature) results = query_job.result() return not results.total_rows @app.route('/', methods=['POST']) def index(): event = None envelope = request.get_json() # Check that data has been posted if not envelope: raise Exception("Expecting JSON payload") # Check that message is a valid pub/sub message if "message" not in envelope: raise Exception("Not a valid Pub/Sub Message") msg = envelope["message"] event = process_jenkins_event(msg) #return process_jenkins_event(request)
[ "google.cloud.bigquery.Client", "flask.Flask", "json.dumps", "flask.globals.request.get_json", "base64.b64decode", "datetime.datetime.utcfromtimestamp" ]
[((173, 188), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (178, 188), False, 'from flask import Flask\n'), ((1628, 1645), 'google.cloud.bigquery.Client', 'bigquery.Client', ([], {}), '()\n', (1643, 1645), False, 'from google.cloud import bigquery\n'), ((2966, 2984), 'flask.globals.request.get_json', 'request.get_json', ([], {}), '()\n', (2982, 2984), False, 'from flask.globals import request\n'), ((1181, 1201), 'json.dumps', 'json.dumps', (['metadata'], {}), '(metadata)\n', (1191, 1201), False, 'import json\n'), ((517, 558), 'datetime.datetime.utcfromtimestamp', 'datetime.datetime.utcfromtimestamp', (['epoch'], {}), '(epoch)\n', (551, 558), False, 'import datetime\n'), ((2602, 2617), 'json.dumps', 'json.dumps', (['msg'], {}), '(msg)\n', (2612, 2617), False, 'import json\n'), ((2521, 2538), 'json.dumps', 'json.dumps', (['entry'], {}), '(entry)\n', (2531, 2538), False, 'import json\n'), ((250, 279), 'base64.b64decode', 'base64.b64decode', (["msg['data']"], {}), "(msg['data'])\n", (266, 279), False, 'import base64\n')]
"""Metadata table.""" from typing import List from pma_api.app import PmaApiFlask from pma_api.utils import get_app_instance from pma_api.models import db app: PmaApiFlask = get_app_instance() class Task(db.Model): """Tasks Attribute 'id' is not auto-generated / auto-incremented, but is actually a unique task ID assigned by celery. """ __tablename__ = 'task' id = db.Column(db.String, primary_key=True) is_active = db.Column('is_active', db.Boolean(), nullable=False) def __init__(self, task_id: str, is_active: bool = False): """Task init""" self.id = task_id self.is_active = is_active @classmethod def register_active(cls, task_id: str): """Register task as active Side effects: - Adds record to DB if doesn't exist - Modifies record """ with app.app_context(): task: Task = cls.query.filter_by(id=task_id).first() if not task: task = cls(task_id=task_id, is_active=True) db.session.add(task) else: task.is_active = True db.session.commit() @classmethod def register_inactive(cls, task_id: str): """Register task as inactive Side effects: - Modifies record """ with app.app_context(): task: Task = cls.query.filter_by(id=task_id).first() task.is_active = False db.session.commit() @classmethod def get_present_tasks(cls, validate: bool = True, update: bool = True) \ -> List[str]: """Get list of IDs for active tasks Side effects: - Modifies records if update arg is True Args: validate (bool): If True, will query task queue message broker to see if tasks marked as active in the PMA API db are in fact correctly marked as such. If update arg is True, validation will also run validation even if the arg validate is False. update (bool): If True, will: (1) also set validation to True, (2) also modify records to correctly mark them as inactive if they fail to validate as active tasks. TODO 2019.04.15-jef: Ideally, we want to use a more standard way to get a list of present (active/scheduled/reserved tasks). Unfortunately, there are some issues making this difficult in Celery 4. Presently, best solution seems to be either: a. downgrade to Celery 3, or b. use rabbitmq-admin available on pip. Useful link: https://stackoverflow. com/questions/5544629/retrieve-list-of-tasks-in-a-queue-in-celery Returns: list(str): Present tasks """ from pma_api.task_utils import validate_active_task_status validation: bool = True if update or validate else False with app.app_context(): all_tasks: List[Task] = cls.query.all() tasks: List[Task] = [x for x in all_tasks if x.is_active] actually_inactive_tasks: List[Task] = [] if not validation else \ [x for x in tasks if not validate_active_task_status(x.id)] if update: for x in actually_inactive_tasks: x.is_active = False with app.app_context(): db.session.commit() task_ids: List[str] = [x.id for x in tasks] if not validation else \ [x.id for x in tasks if x not in actually_inactive_tasks] return task_ids
[ "pma_api.models.db.Column", "pma_api.task_utils.validate_active_task_status", "pma_api.utils.get_app_instance", "pma_api.models.db.session.add", "pma_api.models.db.session.commit", "pma_api.models.db.Boolean" ]
[((178, 196), 'pma_api.utils.get_app_instance', 'get_app_instance', ([], {}), '()\n', (194, 196), False, 'from pma_api.utils import get_app_instance\n'), ((398, 436), 'pma_api.models.db.Column', 'db.Column', (['db.String'], {'primary_key': '(True)'}), '(db.String, primary_key=True)\n', (407, 436), False, 'from pma_api.models import db\n'), ((476, 488), 'pma_api.models.db.Boolean', 'db.Boolean', ([], {}), '()\n', (486, 488), False, 'from pma_api.models import db\n'), ((1153, 1172), 'pma_api.models.db.session.commit', 'db.session.commit', ([], {}), '()\n', (1170, 1172), False, 'from pma_api.models import db\n'), ((1483, 1502), 'pma_api.models.db.session.commit', 'db.session.commit', ([], {}), '()\n', (1500, 1502), False, 'from pma_api.models import db\n'), ((1064, 1084), 'pma_api.models.db.session.add', 'db.session.add', (['task'], {}), '(task)\n', (1078, 1084), False, 'from pma_api.models import db\n'), ((3379, 3398), 'pma_api.models.db.session.commit', 'db.session.commit', ([], {}), '()\n', (3396, 3398), False, 'from pma_api.models import db\n'), ((3190, 3223), 'pma_api.task_utils.validate_active_task_status', 'validate_active_task_status', (['x.id'], {}), '(x.id)\n', (3217, 3223), False, 'from pma_api.task_utils import validate_active_task_status\n')]
from pytorch_lightning import Trainer from models import TSPAgent from argparse import ArgumentParser def main(args): model = TSPAgent(args) trainer = Trainer.from_argparse_args(args) trainer.fit(model) trainer.save_checkpoint(f'tsp{args.n_node}_ep{trainer.current_epoch}.ckpt') if __name__ == '__main__': parser = ArgumentParser() # hparams parser.add_argument('--max_epochs', type=int, default=100) parser.add_argument('--gpus', type=int, default=-1) parser.add_argument('--gradient_clip_val', type=int, default=1) # network structure parser.add_argument('--input_dim', type=int, default=2) parser.add_argument('--hidden_dim', type=int, default=128) parser.add_argument('--ff_dim', type=int, default=512) parser.add_argument('--n_layer', type=int, default=3) parser.add_argument('--k_dim', type=int, default=16) parser.add_argument('--v_dim', type=int, default=16) parser.add_argument('--n_head', type=int, default=8) # train set parser.add_argument('--n_batch_per_epoch', type=int, default=2500) parser.add_argument('--batch_size', type=int, default=512) parser.add_argument('--n_node', type=int, default=20) # validation set parser.add_argument('--val_set', type=str, default=None) # baseline set parser.add_argument('--baseline_set_size', type=int, default=10000) # num_workers of DataLoaders parser.add_argument('--num_workers', type=int, default=4) # optimizer parser.add_argument('--lr', type=float, default=1e-4) args = parser.parse_args() main(args)
[ "models.TSPAgent", "pytorch_lightning.Trainer.from_argparse_args", "argparse.ArgumentParser" ]
[((132, 146), 'models.TSPAgent', 'TSPAgent', (['args'], {}), '(args)\n', (140, 146), False, 'from models import TSPAgent\n'), ((161, 193), 'pytorch_lightning.Trainer.from_argparse_args', 'Trainer.from_argparse_args', (['args'], {}), '(args)\n', (187, 193), False, 'from pytorch_lightning import Trainer\n'), ((339, 355), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (353, 355), False, 'from argparse import ArgumentParser\n')]
import matplotlib as mpl import numpy as np import pandas import sys from matplotlib import pyplot as pp from pprint import pprint from prep_data import get_raw_xy from prep_data import get_vpo sizes = [[15, 8, 10], [20, 10, 20]] sidx = 1 def setup_plot(sidx=sidx, yfrom=1973, yto=2020, step=4, xls=sizes[sidx][2]): pp.rcParams['figure.figsize'] = sizes[sidx][:2] mpl.rc('xtick', labelsize=xls) mpl.rc('ytick', labelsize=sizes[sidx][2]) pp.style.use('dark_background') ticks_range = list(range(yfrom, yto, step)) ax = pp.gca() ax.set_xticks(ticks_range) ax.tick_params(grid_alpha=0.5) pp.ylabel('Passangers in billions', fontsize=sizes[sidx][2]) pp.xlabel('Year', fontsize=sizes[sidx][2]) pp.grid() return pp, ax def plotme(values, years, prep_values=[], train_x=np.array([None]), test_x=np.array([None]), baseline=[], trscore='', tscore='', title='', bttscore=''): pp, ax = setup_plot() pp.plot(years, values, label='Raw values', color='red', linewidth=2) if prep_values != []: pp.plot(years, prep_values, label='Prepared values') if train_x.all() != None: pp.plot(years, train_x, label='Training prediction'.ljust( 25) + '%s' % trscore, color='green', linewidth=2) if test_x.all() != None: pp.plot(years, test_x, label='Test prediction '.ljust( 27) + '%s' % tscore, color='blue', linewidth=2) if baseline != []: pp.plot(years, baseline, label='Baseline Training/Test prediction'.ljust(35) + '%s' % bttscore, color='yellow', linewidth=2) ax.legend(loc='best', fontsize=sizes[sidx][2]) if title: pp.title(title) pp.show() def plothist(history, sidx=sidx): pp.rcParams['figure.figsize'] = sizes[sidx][:2] mpl.rc('xtick', labelsize=sizes[sidx][2]) mpl.rc('ytick', labelsize=sizes[sidx][2]) pp.ylabel('Mean absolute percentage error', fontsize=sizes[sidx][2]) pp.xlabel('Epoch', fontsize=sizes[sidx][2]) pp.grid() h = history.history m = 'mean_absolute_percentage_error' pp.plot(range(1, len(h[m]) + 1), h[m]) ax = pp.gca() ax.set_yticks(range(1, 100, 9)) ax.set_xticks(range(1, len(h[m]) + 1), 1) pp.title('Learning curve') pp.show() def plotpred(values, years, predicted, error, title=''): pp, ax = setup_plot(yfrom=2016, yto=2040, step=2, xls=12) years += [years[-1] + 1] v = values + [np.nan] p = [np.nan for i in values] p += [predicted[0][0]] p[-2] = v[-2] pv = predicted[0][0] pp.plot(years, v, label='Raw values', color='red', linewidth=2) pp.plot(years, p, label='Prediction %s +/- %s' % ("{:,.0f}".format(pv), "{:,.0f}".format(error)), color='green', linewidth=4, linestyle=":") ax.legend(loc='best', fontsize=sizes[sidx][2]) pp.title(title) pp.show() def prep_tt_for_plot(model, years, train_x, train_y, test_x, test_y): trainPredict = model.predict(train_x) testPredict = model.predict(test_x) trainPredictPlot = np.empty((len(years), 1)) trainPredictPlot[:] = np.nan trainPredictPlot[:len(trainPredict)] = trainPredict # Remove the gap in graph by duplicating the last value # at the end of our training data set trainPredictPlot[len(trainPredict)] = trainPredict[-1] testPredictPlot = np.empty((len(years), 1)) testPredictPlot[:] = np.nan testPredictPlot[len(trainPredict):] = testPredict return trainPredictPlot, testPredictPlot if __name__ == '__main__': d = pandas.read_csv(sys.argv[1], header=2) values, years = get_raw_xy(d) p_values = get_vpo(values) print('Year\tCurrent\tFuture') pprint(list(zip(zip(years, values), p_values))) plotme(values, years, prep_values=p_values)
[ "matplotlib.pyplot.title", "matplotlib.rc", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "prep_data.get_raw_xy", "pandas.read_csv", "matplotlib.pyplot.style.use", "prep_data.get_vpo", "numpy.array", "matplotlib.pyplot.gca", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.grid" ]
[((376, 406), 'matplotlib.rc', 'mpl.rc', (['"""xtick"""'], {'labelsize': 'xls'}), "('xtick', labelsize=xls)\n", (382, 406), True, 'import matplotlib as mpl\n'), ((411, 452), 'matplotlib.rc', 'mpl.rc', (['"""ytick"""'], {'labelsize': 'sizes[sidx][2]'}), "('ytick', labelsize=sizes[sidx][2])\n", (417, 452), True, 'import matplotlib as mpl\n'), ((457, 488), 'matplotlib.pyplot.style.use', 'pp.style.use', (['"""dark_background"""'], {}), "('dark_background')\n", (469, 488), True, 'from matplotlib import pyplot as pp\n'), ((546, 554), 'matplotlib.pyplot.gca', 'pp.gca', ([], {}), '()\n', (552, 554), True, 'from matplotlib import pyplot as pp\n'), ((625, 685), 'matplotlib.pyplot.ylabel', 'pp.ylabel', (['"""Passangers in billions"""'], {'fontsize': 'sizes[sidx][2]'}), "('Passangers in billions', fontsize=sizes[sidx][2])\n", (634, 685), True, 'from matplotlib import pyplot as pp\n'), ((690, 732), 'matplotlib.pyplot.xlabel', 'pp.xlabel', (['"""Year"""'], {'fontsize': 'sizes[sidx][2]'}), "('Year', fontsize=sizes[sidx][2])\n", (699, 732), True, 'from matplotlib import pyplot as pp\n'), ((737, 746), 'matplotlib.pyplot.grid', 'pp.grid', ([], {}), '()\n', (744, 746), True, 'from matplotlib import pyplot as pp\n'), ((817, 833), 'numpy.array', 'np.array', (['[None]'], {}), '([None])\n', (825, 833), True, 'import numpy as np\n'), ((842, 858), 'numpy.array', 'np.array', (['[None]'], {}), '([None])\n', (850, 858), True, 'import numpy as np\n'), ((950, 1018), 'matplotlib.pyplot.plot', 'pp.plot', (['years', 'values'], {'label': '"""Raw values"""', 'color': '"""red"""', 'linewidth': '(2)'}), "(years, values, label='Raw values', color='red', linewidth=2)\n", (957, 1018), True, 'from matplotlib import pyplot as pp\n'), ((1683, 1692), 'matplotlib.pyplot.show', 'pp.show', ([], {}), '()\n', (1690, 1692), True, 'from matplotlib import pyplot as pp\n'), ((1785, 1826), 'matplotlib.rc', 'mpl.rc', (['"""xtick"""'], {'labelsize': 'sizes[sidx][2]'}), "('xtick', labelsize=sizes[sidx][2])\n", (1791, 1826), True, 'import matplotlib as mpl\n'), ((1831, 1872), 'matplotlib.rc', 'mpl.rc', (['"""ytick"""'], {'labelsize': 'sizes[sidx][2]'}), "('ytick', labelsize=sizes[sidx][2])\n", (1837, 1872), True, 'import matplotlib as mpl\n'), ((1877, 1945), 'matplotlib.pyplot.ylabel', 'pp.ylabel', (['"""Mean absolute percentage error"""'], {'fontsize': 'sizes[sidx][2]'}), "('Mean absolute percentage error', fontsize=sizes[sidx][2])\n", (1886, 1945), True, 'from matplotlib import pyplot as pp\n'), ((1950, 1993), 'matplotlib.pyplot.xlabel', 'pp.xlabel', (['"""Epoch"""'], {'fontsize': 'sizes[sidx][2]'}), "('Epoch', fontsize=sizes[sidx][2])\n", (1959, 1993), True, 'from matplotlib import pyplot as pp\n'), ((1998, 2007), 'matplotlib.pyplot.grid', 'pp.grid', ([], {}), '()\n', (2005, 2007), True, 'from matplotlib import pyplot as pp\n'), ((2125, 2133), 'matplotlib.pyplot.gca', 'pp.gca', ([], {}), '()\n', (2131, 2133), True, 'from matplotlib import pyplot as pp\n'), ((2220, 2246), 'matplotlib.pyplot.title', 'pp.title', (['"""Learning curve"""'], {}), "('Learning curve')\n", (2228, 2246), True, 'from matplotlib import pyplot as pp\n'), ((2251, 2260), 'matplotlib.pyplot.show', 'pp.show', ([], {}), '()\n', (2258, 2260), True, 'from matplotlib import pyplot as pp\n'), ((2544, 2607), 'matplotlib.pyplot.plot', 'pp.plot', (['years', 'v'], {'label': '"""Raw values"""', 'color': '"""red"""', 'linewidth': '(2)'}), "(years, v, label='Raw values', color='red', linewidth=2)\n", (2551, 2607), True, 'from matplotlib import pyplot as pp\n'), ((2820, 2835), 'matplotlib.pyplot.title', 'pp.title', (['title'], {}), '(title)\n', (2828, 2835), True, 'from matplotlib import pyplot as pp\n'), ((2840, 2849), 'matplotlib.pyplot.show', 'pp.show', ([], {}), '()\n', (2847, 2849), True, 'from matplotlib import pyplot as pp\n'), ((3522, 3560), 'pandas.read_csv', 'pandas.read_csv', (['sys.argv[1]'], {'header': '(2)'}), '(sys.argv[1], header=2)\n', (3537, 3560), False, 'import pandas\n'), ((3581, 3594), 'prep_data.get_raw_xy', 'get_raw_xy', (['d'], {}), '(d)\n', (3591, 3594), False, 'from prep_data import get_raw_xy\n'), ((3610, 3625), 'prep_data.get_vpo', 'get_vpo', (['values'], {}), '(values)\n', (3617, 3625), False, 'from prep_data import get_vpo\n'), ((1053, 1105), 'matplotlib.pyplot.plot', 'pp.plot', (['years', 'prep_values'], {'label': '"""Prepared values"""'}), "(years, prep_values, label='Prepared values')\n", (1060, 1105), True, 'from matplotlib import pyplot as pp\n'), ((1663, 1678), 'matplotlib.pyplot.title', 'pp.title', (['title'], {}), '(title)\n', (1671, 1678), True, 'from matplotlib import pyplot as pp\n')]
import mxnet as mx from mxnet import ndarray as nd from mxnet.gluon import nn from mxnet import gluon import utils import mrt as _mrt import gluon_zoo as zoo import sym_pass as spass import sym_utils as sutils import sim_quant_helper as sim import dataset import logging def load_fname(suffix=None, with_ext=False): suffix = "."+suffix if suffix is not None else "" prefix = "./data/faster_rcnn_resnet50_v1b%s"%(suffix) return utils.extend_fname(prefix, with_ext) def validate(net, val_data, eval_metric, iter_num, logger=logging): """Test on validation dataset.""" eval_metric.reset() # set nms threshold and topk constraint # net.set_nms(nms_thresh=0.45, nms_topk=400) mx.nd.waitall() for idx, batch in enumerate(val_data): if idx >= iter_num: break data, label = batch[0], batch[1] acc = validate_data(net, data, label, eval_metric) logger.info('Validation: {:5.2%}'.format(acc)) def validate_data(net, data, label, eval_metric): det_ids, det_scores, det_bboxes = [], [], [] gt_ids, gt_bboxes, gt_difficults = [], [], [] # get prediction results x, y = data, label ids, scores, bboxes = net(x) det_ids.append(ids) det_scores.append(scores) # clip to image size det_bboxes.append(bboxes.clip(0, x.shape[2])) # split ground truths gt_ids.append(y.slice_axis(axis=-1, begin=4, end=5)) gt_bboxes.append(y.slice_axis(axis=-1, begin=0, end=4)) gt_difficults.append(y.slice_axis(axis=-1, begin=5, end=6) if y.shape[-1] > 5 else None) # update metric eval_metric.update(det_bboxes, det_ids, det_scores, gt_bboxes, gt_ids, gt_difficults) map_name, mean_ap = eval_metric.get() acc = {k:v for k,v in zip(map_name, mean_ap)}['mAP'] return acc def test_mrt_quant(batch_size=1, iter_num=10): logger = logging.getLogger("log.test.mrt.quantize") ctx = mx.gpu(1) qctx = mx.gpu(3) input_size = 512 h, w = input_size, input_size inputs_ext = { 'data': { 'shape': (batch_size, 3, h, w), } } val_data = dataset.load_voc(batch_size, input_size) val_data_iter = iter(val_data) def data_iter_func(): data, label = next(val_data_iter) return data, label sym_file, param_file = load_fname() sym, params = mx.sym.load(sym_file), nd.load(param_file) sym, params = spass.sym_quant_prepare(sym, params, inputs_ext) keys = [ "ssd0_multiperclassdecoder0_concat0", "ssd0_multiperclassdecoder0__mulscalar0", "ssd0_multiperclassdecoder0_slice_axis0", "ssd0_multiperclassdecoder0_zeros_like1", "ssd0_normalizedboxcenterdecoder0_concat0", ] base, base_params, base_inputs_ext, top, top_params, top_inputs_ext \ = _mrt.split_model(sym, params, inputs_ext, keys) dump_sym, dump_params = load_fname("mrt.base") open(dump_sym, "w").write(base.tojson()) nd.save(dump_params, base_params) dump_sym, dump_params, dump_ext = load_fname("mrt.top", True) open(dump_sym, "w").write(top.tojson()) nd.save(dump_params, top_params) sim.save_ext(dump_ext, top_inputs_ext) dump_sym, dump_params = load_fname("mrt.base") base, base_params = mx.sym.load(dump_sym), nd.load(dump_params) dump_sym, dump_params, dump_ext = load_fname("mrt.top", True) top, top_params = mx.sym.load(dump_sym), nd.load(dump_params) (top_inputs_ext,) = sim.load_ext(dump_ext) base_inputs = [mx.sym.var(n) for n in inputs_ext] base_graph = mx.gluon.nn.SymbolBlock(base, base_inputs) utils.load_parameters(base_graph, base_params, ctx=ctx) top_inputs = [mx.sym.var(n) for n in top_inputs_ext] top_graph = mx.gluon.nn.SymbolBlock(top, top_inputs) utils.load_parameters(top_graph, top_params, ctx=ctx) metric = dataset.load_voc_metric() metric.reset() def yolov3(data, label): def net(data): tmp = base_graph(data.as_in_context(ctx)) outs = top_graph(*tmp) return outs acc = validate_data(net, data, label, metric) return "{:6.2%}".format(acc) # utils.multi_validate(yolov3, data_iter_func, # iter_num=iter_num, logger=logger) # exit() if False: mrt = _mrt.MRT(base, base_params, inputs_ext) for i in range(16): data, _ = data_iter_func() mrt.set_data('data', data) th_dict = mrt.calibrate(ctx=ctx) _, _, dump_ext = load_fname("mrt.dict", True) sim.save_ext(dump_ext, th_dict) _, _, dump_ext = load_fname("mrt.dict", True) (th_dict,) = sim.load_ext(dump_ext) if True: mrt = _mrt.MRT(base, base_params, base_inputs_ext) mrt.set_th_dict(th_dict) mrt.set_threshold('data', 2.64) mrt.set_fixed("ssd0_multiperclassdecoder0_concat0") mrt.set_fixed("ssd0_multiperclassdecoder0__mulscalar0") mrt.set_fixed("ssd0_multiperclassdecoder0_zeros_like1") mrt.set_threshold("ssd0_multiperclassdecoder0_slice_axis0", 1) # mrt.set_threshold("ssd0_normalizedboxcenterdecoder0_concat0", 512) mrt.set_output_prec(30) qbase, qbase_params, qbase_inputs_ext = mrt.quantize() oscales = mrt.get_output_scales() maps = mrt.get_maps() dump_sym, dump_params, dump_ext = load_fname("mrt.quantize", True) open(dump_sym, "w").write(qbase.tojson()) nd.save(dump_params, qbase_params) sim.save_ext(dump_ext, qbase_inputs_ext, oscales, maps) # merge quantize model if True: qb_sym, qb_params, qb_ext = load_fname("mrt.quantize", True) qbase, qbase_params = mx.sym.load(qb_sym), nd.load(qb_params) qbase_inputs_ext, oscales, maps = sim.load_ext(qb_ext) name_maps = { "ssd0_slice_axis41": "ssd0_multiperclassdecoder0_concat0", "ssd0_slice_axis42": "ssd0_multiperclassdecoder0_slice_axis0", "ssd0_slice_axis43": "ssd0_normalizedboxcenterdecoder0_concat0", } oscales_dict = dict(zip([c.attr('name') for c in base], oscales)) oscales = [oscales_dict[name_maps[c.attr('name')]] for c in top] def box_nms(node, params, graph): name, op_name = node.attr('name'), node.attr('op_name') childs, attr = sutils.sym_iter(node.get_children()), node.list_attr() if op_name == '_greater_scalar': valid_thresh = sutils.get_attr(attr, 'scalar', 0) attr['scalar'] = int(valid_thresh * oscales[1]) node = sutils.get_mxnet_op(op_name)(*childs, **attr, name=name) elif op_name == '_contrib_box_nms': valid_thresh = sutils.get_attr(attr, 'valid_thresh', 0) attr['valid_thresh'] = int(valid_thresh * oscales[1]) node = sutils.get_mxnet_op(op_name)(*childs, **attr, name=name) return node qsym, qparams = _mrt.merge_model(qbase, qbase_params, top, top_params, maps, box_nms) sym_file, param_file, ext_file = load_fname("mrt.all.quantize", True) open(sym_file, "w").write(qsym.tojson()) nd.save(param_file, qparams) sim.save_ext(ext_file, qbase_inputs_ext, oscales) if True: dump_sym, dump_params, dump_ext = load_fname("mrt.all.quantize", True) net2_inputs_ext, oscales = sim.load_ext(dump_ext) inputs = [mx.sym.var(n) for n in net2_inputs_ext] net2 = utils.load_model(dump_sym, dump_params, inputs, ctx=qctx) net2_metric = dataset.load_voc_metric() net2_metric.reset() def mrt_quantize(data, label): def net(data): data = sim.load_real_data(data, 'data', net2_inputs_ext) outs = net2(data.as_in_context(qctx)) outs = [o.as_in_context(ctx) / oscales[i] for i, o in enumerate(outs)] return outs acc = validate_data(net, data, label, net2_metric) return "{:6.2%}".format(acc) utils.multi_validate(yolov3, data_iter_func, mrt_quantize, iter_num=iter_num, logger=logger) def test_sym_nnvm(batch_size, iter_num): logger = logging.getLogger("log.test.nnvm") logger.info("=== Log Test NNVM ===") sym_file, param_file, ext_file = load_fname("mrt.all.quantize", True) sym, params = mx.sym.load(sym_file), nd.load(param_file) inputs_ext, _ = sim.load_ext(ext_file) val_data = dataset.load_voc(1, 512) val_data_iter = iter(val_data) data, _ = next(val_data_iter) if False: data = sim.load_real_data(data, 'data', inputs_ext) inputs_ext['data']['data'] = data spass.sym_dump_ops(sym, params, inputs_ext, datadir="/data/wlt", ctx=mx.gpu(1), cleanDir=True, ops=[ "broadcast_div0", ]) else: _mrt.std_dump(sym, params, inputs_ext, data, "ssd", max_num=100) # nnvm_sym, nnvm_params = spass.mxnet_to_nnvm(sym, params, inputs_ext) # spass.cvm_build(nnvm_sym, nnvm_params, inputs_ext, *load_fname("nnvm")) if __name__ == '__main__': utils.log_init() zoo.save_model('faster_rcnn_resnet50_v1b_voc') # test_mrt_quant(1, 100) # test_sym_nnvm(16, 0)
[ "sim_quant_helper.load_real_data", "sym_utils.get_mxnet_op", "gluon_zoo.save_model", "logging.getLogger", "mrt.split_model", "utils.extend_fname", "sim_quant_helper.load_ext", "sym_pass.sym_quant_prepare", "mxnet.sym.var", "mrt.MRT", "utils.multi_validate", "mxnet.gpu", "mxnet.gluon.nn.SymbolBlock", "mrt.merge_model", "dataset.load_voc_metric", "utils.load_model", "mxnet.nd.waitall", "mxnet.sym.load", "dataset.load_voc", "sim_quant_helper.save_ext", "utils.load_parameters", "mxnet.ndarray.load", "mxnet.ndarray.save", "mrt.std_dump", "sym_utils.get_attr", "utils.log_init" ]
[((442, 478), 'utils.extend_fname', 'utils.extend_fname', (['prefix', 'with_ext'], {}), '(prefix, with_ext)\n', (460, 478), False, 'import utils\n'), ((707, 722), 'mxnet.nd.waitall', 'mx.nd.waitall', ([], {}), '()\n', (720, 722), True, 'import mxnet as mx\n'), ((1854, 1896), 'logging.getLogger', 'logging.getLogger', (['"""log.test.mrt.quantize"""'], {}), "('log.test.mrt.quantize')\n", (1871, 1896), False, 'import logging\n'), ((1908, 1917), 'mxnet.gpu', 'mx.gpu', (['(1)'], {}), '(1)\n', (1914, 1917), True, 'import mxnet as mx\n'), ((1929, 1938), 'mxnet.gpu', 'mx.gpu', (['(3)'], {}), '(3)\n', (1935, 1938), True, 'import mxnet as mx\n'), ((2087, 2127), 'dataset.load_voc', 'dataset.load_voc', (['batch_size', 'input_size'], {}), '(batch_size, input_size)\n', (2103, 2127), False, 'import dataset\n'), ((2378, 2426), 'sym_pass.sym_quant_prepare', 'spass.sym_quant_prepare', (['sym', 'params', 'inputs_ext'], {}), '(sym, params, inputs_ext)\n', (2401, 2426), True, 'import sym_pass as spass\n'), ((2774, 2821), 'mrt.split_model', '_mrt.split_model', (['sym', 'params', 'inputs_ext', 'keys'], {}), '(sym, params, inputs_ext, keys)\n', (2790, 2821), True, 'import mrt as _mrt\n'), ((2922, 2955), 'mxnet.ndarray.save', 'nd.save', (['dump_params', 'base_params'], {}), '(dump_params, base_params)\n', (2929, 2955), True, 'from mxnet import ndarray as nd\n'), ((3070, 3102), 'mxnet.ndarray.save', 'nd.save', (['dump_params', 'top_params'], {}), '(dump_params, top_params)\n', (3077, 3102), True, 'from mxnet import ndarray as nd\n'), ((3107, 3145), 'sim_quant_helper.save_ext', 'sim.save_ext', (['dump_ext', 'top_inputs_ext'], {}), '(dump_ext, top_inputs_ext)\n', (3119, 3145), True, 'import sim_quant_helper as sim\n'), ((3422, 3444), 'sim_quant_helper.load_ext', 'sim.load_ext', (['dump_ext'], {}), '(dump_ext)\n', (3434, 3444), True, 'import sim_quant_helper as sim\n'), ((3517, 3559), 'mxnet.gluon.nn.SymbolBlock', 'mx.gluon.nn.SymbolBlock', (['base', 'base_inputs'], {}), '(base, base_inputs)\n', (3540, 3559), True, 'import mxnet as mx\n'), ((3564, 3619), 'utils.load_parameters', 'utils.load_parameters', (['base_graph', 'base_params'], {'ctx': 'ctx'}), '(base_graph, base_params, ctx=ctx)\n', (3585, 3619), False, 'import utils\n'), ((3694, 3734), 'mxnet.gluon.nn.SymbolBlock', 'mx.gluon.nn.SymbolBlock', (['top', 'top_inputs'], {}), '(top, top_inputs)\n', (3717, 3734), True, 'import mxnet as mx\n'), ((3739, 3792), 'utils.load_parameters', 'utils.load_parameters', (['top_graph', 'top_params'], {'ctx': 'ctx'}), '(top_graph, top_params, ctx=ctx)\n', (3760, 3792), False, 'import utils\n'), ((3807, 3832), 'dataset.load_voc_metric', 'dataset.load_voc_metric', ([], {}), '()\n', (3830, 3832), False, 'import dataset\n'), ((4599, 4621), 'sim_quant_helper.load_ext', 'sim.load_ext', (['dump_ext'], {}), '(dump_ext)\n', (4611, 4621), True, 'import sim_quant_helper as sim\n'), ((7998, 8095), 'utils.multi_validate', 'utils.multi_validate', (['yolov3', 'data_iter_func', 'mrt_quantize'], {'iter_num': 'iter_num', 'logger': 'logger'}), '(yolov3, data_iter_func, mrt_quantize, iter_num=\n iter_num, logger=logger)\n', (8018, 8095), False, 'import utils\n'), ((8170, 8204), 'logging.getLogger', 'logging.getLogger', (['"""log.test.nnvm"""'], {}), "('log.test.nnvm')\n", (8187, 8204), False, 'import logging\n'), ((8402, 8424), 'sim_quant_helper.load_ext', 'sim.load_ext', (['ext_file'], {}), '(ext_file)\n', (8414, 8424), True, 'import sim_quant_helper as sim\n'), ((8440, 8464), 'dataset.load_voc', 'dataset.load_voc', (['(1)', '(512)'], {}), '(1, 512)\n', (8456, 8464), False, 'import dataset\n'), ((9120, 9136), 'utils.log_init', 'utils.log_init', ([], {}), '()\n', (9134, 9136), False, 'import utils\n'), ((9142, 9188), 'gluon_zoo.save_model', 'zoo.save_model', (['"""faster_rcnn_resnet50_v1b_voc"""'], {}), "('faster_rcnn_resnet50_v1b_voc')\n", (9156, 9188), True, 'import gluon_zoo as zoo\n'), ((2317, 2338), 'mxnet.sym.load', 'mx.sym.load', (['sym_file'], {}), '(sym_file)\n', (2328, 2338), True, 'import mxnet as mx\n'), ((2340, 2359), 'mxnet.ndarray.load', 'nd.load', (['param_file'], {}), '(param_file)\n', (2347, 2359), True, 'from mxnet import ndarray as nd\n'), ((3222, 3243), 'mxnet.sym.load', 'mx.sym.load', (['dump_sym'], {}), '(dump_sym)\n', (3233, 3243), True, 'import mxnet as mx\n'), ((3245, 3265), 'mxnet.ndarray.load', 'nd.load', (['dump_params'], {}), '(dump_params)\n', (3252, 3265), True, 'from mxnet import ndarray as nd\n'), ((3354, 3375), 'mxnet.sym.load', 'mx.sym.load', (['dump_sym'], {}), '(dump_sym)\n', (3365, 3375), True, 'import mxnet as mx\n'), ((3377, 3397), 'mxnet.ndarray.load', 'nd.load', (['dump_params'], {}), '(dump_params)\n', (3384, 3397), True, 'from mxnet import ndarray as nd\n'), ((3465, 3478), 'mxnet.sym.var', 'mx.sym.var', (['n'], {}), '(n)\n', (3475, 3478), True, 'import mxnet as mx\n'), ((3639, 3652), 'mxnet.sym.var', 'mx.sym.var', (['n'], {}), '(n)\n', (3649, 3652), True, 'import mxnet as mx\n'), ((4246, 4285), 'mrt.MRT', '_mrt.MRT', (['base', 'base_params', 'inputs_ext'], {}), '(base, base_params, inputs_ext)\n', (4254, 4285), True, 'import mrt as _mrt\n'), ((4499, 4530), 'sim_quant_helper.save_ext', 'sim.save_ext', (['dump_ext', 'th_dict'], {}), '(dump_ext, th_dict)\n', (4511, 4530), True, 'import sim_quant_helper as sim\n'), ((4649, 4693), 'mrt.MRT', '_mrt.MRT', (['base', 'base_params', 'base_inputs_ext'], {}), '(base, base_params, base_inputs_ext)\n', (4657, 4693), True, 'import mrt as _mrt\n'), ((5404, 5438), 'mxnet.ndarray.save', 'nd.save', (['dump_params', 'qbase_params'], {}), '(dump_params, qbase_params)\n', (5411, 5438), True, 'from mxnet import ndarray as nd\n'), ((5447, 5502), 'sim_quant_helper.save_ext', 'sim.save_ext', (['dump_ext', 'qbase_inputs_ext', 'oscales', 'maps'], {}), '(dump_ext, qbase_inputs_ext, oscales, maps)\n', (5459, 5502), True, 'import sim_quant_helper as sim\n'), ((5725, 5745), 'sim_quant_helper.load_ext', 'sim.load_ext', (['qb_ext'], {}), '(qb_ext)\n', (5737, 5745), True, 'import sim_quant_helper as sim\n'), ((6915, 6984), 'mrt.merge_model', '_mrt.merge_model', (['qbase', 'qbase_params', 'top', 'top_params', 'maps', 'box_nms'], {}), '(qbase, qbase_params, top, top_params, maps, box_nms)\n', (6931, 6984), True, 'import mrt as _mrt\n'), ((7136, 7164), 'mxnet.ndarray.save', 'nd.save', (['param_file', 'qparams'], {}), '(param_file, qparams)\n', (7143, 7164), True, 'from mxnet import ndarray as nd\n'), ((7173, 7222), 'sim_quant_helper.save_ext', 'sim.save_ext', (['ext_file', 'qbase_inputs_ext', 'oscales'], {}), '(ext_file, qbase_inputs_ext, oscales)\n', (7185, 7222), True, 'import sim_quant_helper as sim\n'), ((7351, 7373), 'sim_quant_helper.load_ext', 'sim.load_ext', (['dump_ext'], {}), '(dump_ext)\n', (7363, 7373), True, 'import sim_quant_helper as sim\n'), ((7447, 7504), 'utils.load_model', 'utils.load_model', (['dump_sym', 'dump_params', 'inputs'], {'ctx': 'qctx'}), '(dump_sym, dump_params, inputs, ctx=qctx)\n', (7463, 7504), False, 'import utils\n'), ((7527, 7552), 'dataset.load_voc_metric', 'dataset.load_voc_metric', ([], {}), '()\n', (7550, 7552), False, 'import dataset\n'), ((8339, 8360), 'mxnet.sym.load', 'mx.sym.load', (['sym_file'], {}), '(sym_file)\n', (8350, 8360), True, 'import mxnet as mx\n'), ((8362, 8381), 'mxnet.ndarray.load', 'nd.load', (['param_file'], {}), '(param_file)\n', (8369, 8381), True, 'from mxnet import ndarray as nd\n'), ((8564, 8608), 'sim_quant_helper.load_real_data', 'sim.load_real_data', (['data', '"""data"""', 'inputs_ext'], {}), "(data, 'data', inputs_ext)\n", (8582, 8608), True, 'import sim_quant_helper as sim\n'), ((8867, 8931), 'mrt.std_dump', '_mrt.std_dump', (['sym', 'params', 'inputs_ext', 'data', '"""ssd"""'], {'max_num': '(100)'}), "(sym, params, inputs_ext, data, 'ssd', max_num=100)\n", (8880, 8931), True, 'import mrt as _mrt\n'), ((5643, 5662), 'mxnet.sym.load', 'mx.sym.load', (['qb_sym'], {}), '(qb_sym)\n', (5654, 5662), True, 'import mxnet as mx\n'), ((5664, 5682), 'mxnet.ndarray.load', 'nd.load', (['qb_params'], {}), '(qb_params)\n', (5671, 5682), True, 'from mxnet import ndarray as nd\n'), ((7392, 7405), 'mxnet.sym.var', 'mx.sym.var', (['n'], {}), '(n)\n', (7402, 7405), True, 'import mxnet as mx\n'), ((6418, 6452), 'sym_utils.get_attr', 'sutils.get_attr', (['attr', '"""scalar"""', '(0)'], {}), "(attr, 'scalar', 0)\n", (6433, 6452), True, 'import sym_utils as sutils\n'), ((7670, 7719), 'sim_quant_helper.load_real_data', 'sim.load_real_data', (['data', '"""data"""', 'net2_inputs_ext'], {}), "(data, 'data', net2_inputs_ext)\n", (7688, 7719), True, 'import sim_quant_helper as sim\n'), ((8744, 8753), 'mxnet.gpu', 'mx.gpu', (['(1)'], {}), '(1)\n', (8750, 8753), True, 'import mxnet as mx\n'), ((6540, 6568), 'sym_utils.get_mxnet_op', 'sutils.get_mxnet_op', (['op_name'], {}), '(op_name)\n', (6559, 6568), True, 'import sym_utils as sutils\n'), ((6676, 6716), 'sym_utils.get_attr', 'sutils.get_attr', (['attr', '"""valid_thresh"""', '(0)'], {}), "(attr, 'valid_thresh', 0)\n", (6691, 6716), True, 'import sym_utils as sutils\n'), ((6810, 6838), 'sym_utils.get_mxnet_op', 'sutils.get_mxnet_op', (['op_name'], {}), '(op_name)\n', (6829, 6838), True, 'import sym_utils as sutils\n')]
#!/usr/bin/env python # coding: utf-8 # vim:softtabstop=4:ts=4:sw=4:expandtab:tw=120 import argparse import datetime import git import hashlib import logging import logging.handlers import os import sys import traceback def _update_logger(verbosity): if verbosity == 0: _log.setLevel(logging.ERROR) elif verbosity == 1: _log.setLevel(logging.INFO) elif verbosity >= 2: _log.setLevel(logging.DEBUG) def _initialize_logger(): logger = logging.getLogger(__name__) logging.captureWarnings(True) logger.propagate = False formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s") #handler = logging.handlers.TimedRotatingFileHandler(config_file.log_file, # when="midnight", # interval=1, # backupCount=7) #handler.setFormatter(formatter) #logger.addHandler(handler) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger _log = _initialize_logger() def _is_directory(directory): if not os.path.isdir(directory): msg = "{0} is not a valid directory".format(directory) raise argparse.ArgumentTypeError(msg) return os.path.normpath(os.path.abspath(directory)) def _parse_args(): parser = argparse.ArgumentParser(description='Get all the files that are not in the git repository') parser.add_argument('directory', default=os.getcwd(), type=_is_directory, help='directory which contains the .git directory') parser.add_argument('-p', '--pretty-print', default=False, action='store_true', help='output results in pretty print fashion') parser.add_argument('-v', '--verbose', action='count', default=0, help='output verbose debugging information') args = parser.parse_args() _update_logger(args.verbose) directory = os.path.abspath(args.directory) _log.info('verbose: %d, pretty print: %s, directory: %s', args.verbose, args.pretty_print, directory) return args.pretty_print, directory def _gethash(s): m = hashlib.md5() m.update(s) return m.hexdigest() def _get_repository_files(directory): _log.info('getting all files within the repository') repo = git.Git(directory) files = {} for filename in repo.ls_files().split(): fullname = os.path.join(directory, filename) files[_gethash(fullname)] = fullname return files def _get_all_files(directory): _log.info('getting all files within %s' % directory) all_files = {} for root, dirs, files in os.walk(directory): if root.startswith(os.path.abspath(os.path.join(directory, '.git'))): continue dir_entry = {} for filename in files: if not filename.endswith('.swp'): fullname = os.path.join(root, filename) dir_entry[_gethash(fullname)] = fullname all_files[root] = dir_entry return all_files def _collapse_directories(filenames): files = filenames[:] files.sort(key=len) for i in files: for j in files: if i != j and j.startswith(i): files.remove(j) files.sort() return files def get_files_not_in_repo(directory): files = [] repo_files = _get_repository_files(directory) filesystem_files = _get_all_files(directory) for dirname in list(filesystem_files.keys()): dir_entries = filesystem_files[dirname] new_files = [] for filehash, filename in dir_entries.items(): if filehash not in list(repo_files.keys()): new_files.append(filename) if len(new_files) != len(dir_entries): files += new_files else: files.append(dirname) return _collapse_directories(files) def main(): pretty_print, directory = _parse_args() try: if pretty_print: print('\n'.join(get_files_not_in_repo(directory))) else: print(' '.join(get_files_not_in_repo(directory))) except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout) return 1 return 0 if __name__ == '__main__': sys.exit(main())
[ "git.Git", "os.path.abspath", "hashlib.md5", "argparse.ArgumentParser", "os.path.isdir", "os.getcwd", "logging.StreamHandler", "os.walk", "logging.Formatter", "logging.captureWarnings", "sys.exc_info", "traceback.print_exception", "os.path.join", "logging.getLogger", "argparse.ArgumentTypeError" ]
[((476, 503), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (493, 503), False, 'import logging\n'), ((508, 537), 'logging.captureWarnings', 'logging.captureWarnings', (['(True)'], {}), '(True)\n', (531, 537), False, 'import logging\n'), ((583, 643), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s [%(levelname)s] %(message)s"""'], {}), "('%(asctime)s [%(levelname)s] %(message)s')\n", (600, 643), False, 'import logging\n'), ((1021, 1054), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (1042, 1054), False, 'import logging\n'), ((1469, 1565), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Get all the files that are not in the git repository"""'}), "(description=\n 'Get all the files that are not in the git repository')\n", (1492, 1565), False, 'import argparse\n'), ((2089, 2120), 'os.path.abspath', 'os.path.abspath', (['args.directory'], {}), '(args.directory)\n', (2104, 2120), False, 'import os\n'), ((2293, 2306), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (2304, 2306), False, 'import hashlib\n'), ((2455, 2473), 'git.Git', 'git.Git', (['directory'], {}), '(directory)\n', (2462, 2473), False, 'import git\n'), ((2786, 2804), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (2793, 2804), False, 'import os\n'), ((1245, 1269), 'os.path.isdir', 'os.path.isdir', (['directory'], {}), '(directory)\n', (1258, 1269), False, 'import os\n'), ((1348, 1379), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['msg'], {}), '(msg)\n', (1374, 1379), False, 'import argparse\n'), ((1408, 1434), 'os.path.abspath', 'os.path.abspath', (['directory'], {}), '(directory)\n', (1423, 1434), False, 'import os\n'), ((2553, 2586), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (2565, 2586), False, 'import os\n'), ((1606, 1617), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1615, 1617), False, 'import os\n'), ((4309, 4323), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (4321, 4323), False, 'import sys\n'), ((4332, 4410), 'traceback.print_exception', 'traceback.print_exception', (['exc_type', 'exc_value', 'exc_traceback'], {'file': 'sys.stdout'}), '(exc_type, exc_value, exc_traceback, file=sys.stdout)\n', (4357, 4410), False, 'import traceback\n'), ((2849, 2880), 'os.path.join', 'os.path.join', (['directory', '""".git"""'], {}), "(directory, '.git')\n", (2861, 2880), False, 'import os\n'), ((3032, 3060), 'os.path.join', 'os.path.join', (['root', 'filename'], {}), '(root, filename)\n', (3044, 3060), False, 'import os\n')]
# this code performes a dimension reduction on the dataset, # using a DenseNet121 pretrained model. import tensorflow as tf from scipy.io import loadmat, savemat import numpy as np FV = loadmat('images.mat') data = FV['data'] labels = FV['labels'] print(data.shape) labels = labels.transpose() labels = labels.ravel() print(labels.shape) inputs = tf.keras.Input(shape=(224, 224, 3)) # here different models were tested, # TODO : add all the models in parallel with the best model. model = tf.keras.applications.DenseNet121(include_top=False, weights='imagenet', input_shape=(224,224,3)) # possibly try other models here. model_outputs = model(inputs) outputs = tf.keras.layers.GlobalAveragePooling2D(name='ga')(model_outputs) feature_extractor = tf.keras.models.Model(inputs=inputs, outputs=outputs) # get features X = [] samples = data.shape[0] for i in range(samples): X.append(feature_extractor(np.array([data[i]]))) X = np.array(X) # replace old images with features. data = X.reshape(746, 1024) del X savemat('features.mat', {'data': data, 'labels': labels})
[ "scipy.io.loadmat", "tensorflow.keras.Input", "scipy.io.savemat", "tensorflow.keras.models.Model", "numpy.array", "tensorflow.keras.layers.GlobalAveragePooling2D", "tensorflow.keras.applications.DenseNet121" ]
[((189, 210), 'scipy.io.loadmat', 'loadmat', (['"""images.mat"""'], {}), "('images.mat')\n", (196, 210), False, 'from scipy.io import loadmat, savemat\n'), ((350, 385), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': '(224, 224, 3)'}), '(shape=(224, 224, 3))\n', (364, 385), True, 'import tensorflow as tf\n'), ((493, 596), 'tensorflow.keras.applications.DenseNet121', 'tf.keras.applications.DenseNet121', ([], {'include_top': '(False)', 'weights': '"""imagenet"""', 'input_shape': '(224, 224, 3)'}), "(include_top=False, weights='imagenet',\n input_shape=(224, 224, 3))\n", (526, 596), True, 'import tensorflow as tf\n'), ((792, 845), 'tensorflow.keras.models.Model', 'tf.keras.models.Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (813, 845), True, 'import tensorflow as tf\n'), ((973, 984), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (981, 984), True, 'import numpy as np\n'), ((1056, 1113), 'scipy.io.savemat', 'savemat', (['"""features.mat"""', "{'data': data, 'labels': labels}"], {}), "('features.mat', {'data': data, 'labels': labels})\n", (1063, 1113), False, 'from scipy.io import loadmat, savemat\n'), ((707, 756), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'tf.keras.layers.GlobalAveragePooling2D', ([], {'name': '"""ga"""'}), "(name='ga')\n", (745, 756), True, 'import tensorflow as tf\n'), ((947, 966), 'numpy.array', 'np.array', (['[data[i]]'], {}), '([data[i]])\n', (955, 966), True, 'import numpy as np\n')]
import numpy as np from matplotlib import pyplot as plt from ..Xfit.basic import fitline, fitline0, fitconstant from ..Xfit.MCMC_straight_line import mcmc_sl from ..Xfit.fit_basic import fit_basic from ..Xplot.niceplot import niceplot from matplotlib.offsetbox import AnchoredText from matplotlib import ticker def plot_parameters(pars, parameter, R=250e-9, T=22, fit=None, modes=1, ax=None, marker='o', textbox=False, alpha=1, log='', label=None, ci=0, corner_axes=0, mfc=None, format_ticks=True, cmap=None, init={}, fix=None, viscosity=False, fit_report=False, emcee=False, exc=None, excfit=None, excbad=True, weighted=True, xl=None, xlim=[None,None], ylim=[None,None], **kwargs): def getD(eta, err=0): dD = 0 D = kb*(T+273.15)/(6*np.pi*R*eta) if err: dD = D*err/eta return D, dD def geteta(D, err=0): deta = 0 eta = kb*(T+273.15)/(6*np.pi*R*D*1e-18) if err: deta = eta*err/D return eta, deta def blc(q, L, k, lc): def A(q): return 4*np.pi/lc*q/k*np.sqrt(1-q**2/(4*k**2)) return 2*(A(q)*L-1+np.exp(-A(q)*L))/(A(q)*L)**2 def line(x, p): return p[0]*x + p[1] def power(x, p): return p[0]*x**p[1] + p[2] if type(modes) == int: modes = np.arange(modes-1, modes) else: modes = np.array(modes) modes -= 1 if parameter in [0, 'G', 'dispersion', 'tau']: name = 't' elif parameter in [1, 'kww']: name = 'g' elif parameter in [2, 'f0', 'ergodicity']: name = 'b' if 'ax' is None: fig, ax = plt.subplots(1, 1, figsize=(9, 4)) kb = 1.381e-23 m_unit = { 'G': 'nm{} s-1'.format(alpha), 'kww': 'nm{}'.format(alpha), 'f0': 'nm{}'.format(alpha), 'tau': 'nm{} s'.format(alpha), } b_unit = { 'G': 's-1', 'kww': '', 'f0': '', 'tau': 's' } y_label = { 'G': r'$\Gamma (s^{-1})$', 'kww': 'kww', 'f0': 'ergodicity', 'tau': r'$\tau\,(s)$' } if fit == '' or fit is None: dofit = False else: dofit = True qv = pars['q'] qv = qv**alpha # values to be excluded iip = np.arange(qv.size) iif = iip.copy() if exc is not None: iip = np.delete(iip, exc) if excfit is not None: iif = np.delete(iif, np.hstack((excfit))) if xl is None: x = np.linspace(np.min(qv[iif]), np.max(qv[iif]), 100) else: x = np.linspace(xl[0], xl[1], 100) textstr = "" markers = ['^', 'v'] if (len(modes)<3) else ['o'] for ii, i in enumerate(modes): if label is None: labstr = 'mode {}: {}'.format(i+1, parameter) else: labstr = label textstr += labstr # -------plot decay rates-------- try: y = np.asarray(pars['{}{}'.format(name, i)], dtype=np.float32) dy = np.asarray(pars['d{}{}'.format(name, i)], dtype=np.float32) except KeyError: return np.zeros(5) y = np.ma.masked_where(~np.isfinite(y), y) dy = np.ma.masked_array(dy, mask=y.mask) if parameter == 'G': y = 1/y dy = y**2*dy else: pass nf = np.where(dy.filled(0) <= 0)[0] bad_points = nf.size if bad_points: print('Found {} points with zero error\n'.format(bad_points)) if excbad: iff = np.array([p for p in iif if p not in nf]) iip = np.array([p for p in iip if p not in nf]) print('Excluded bad points.') if len(iff)==0 or len(iip)==0: return np.zeros(5) color = cmap(ci) marker = markers[i] ax.errorbar(qv[iip], y[iip], dy[iip], fmt=marker, label=labstr, color=color, mfc=mfc) if dofit: if fit == 'mcmc_line': m, b, f_m, m_ls, b_ls = mcmc_sl( qv[iif], y[iif], dy[iif], doplot=corner_axes) # ax[0].plot(x2,m_ls*x2+b_ls) m, b = [(x[0], np.mean(x[1:])) for x in (m, b)] else: res = fit_basic(qv[iif], y[iif], dy[iif], fit, dict(init), fix, emcee) fitpar = res[0].astype(np.float32) yf = res[4].eval(res[2].params, x=x) ax.plot(x, yf, color=color, label=None) if parameter in ['G', 'tau']: if viscosity: power = 1 if (parameter=='G') else -1 textstr += '\neta = {0[0]:.4g} +/- {0[1]:.2g} [cP]'.format( np.array(geteta(*fitpar[0]))*1e3)**power elif parameter == 'f0' and dofit and 't' in res[2].params.keys(): msd = 1/(2*res[2].params['t'].value) dmsd = 2*msd**2*res[2].params['t'].stderr r_loc = np.sqrt(6*(msd)) dr_loc = 6/2/r_loc*dmsd textstr += 'localization length: {:.2f} +/- {:.2f} nm\n'.format( r_loc, dr_loc) if fit_report and dofit: print('\n' + textstr) print('-'*16) print(res[3]) # if format_ticks: # x_labels = ax.get_xticks() # try: # @ticker.FuncFormatter # def major_formatter(x, pos): # return "{:.2f}".format(x) # ax.ticklabel_format(axis='x', useMathText=True, # style='sci', scilimits=(0, 0)) # except: # pass # set style if alpha == 1: x_lab = r'$\mathrm{q} (nm^{-1})$' else: x_lab = r'$\mathrm{{q}}^{0} (nm^{{-{0}}})$'.format(alpha) ax.set_xlabel(x_lab) ax.set_ylabel(y_label[parameter]) if 'x' in log: ax.set_xscale('log') if 'y' in log: ax.set_yscale('log') if textbox: at = AnchoredText(textstr, loc=2,) ax.add_artist(at) ax.legend(loc='best') # ax.get_yaxis().get_major_formatter().set_useOffset(False) # niceplot(ax,) ax.set_xlim(xlim) ax.set_ylim(ylim) if dofit: return res else: return np.zeros(5)
[ "matplotlib.offsetbox.AnchoredText", "numpy.zeros", "numpy.isfinite", "numpy.hstack", "numpy.min", "numpy.max", "numpy.array", "numpy.arange", "numpy.linspace", "numpy.ma.masked_array", "numpy.mean", "matplotlib.pyplot.subplots", "numpy.delete", "numpy.sqrt" ]
[((2329, 2347), 'numpy.arange', 'np.arange', (['qv.size'], {}), '(qv.size)\n', (2338, 2347), True, 'import numpy as np\n'), ((1386, 1413), 'numpy.arange', 'np.arange', (['(modes - 1)', 'modes'], {}), '(modes - 1, modes)\n', (1395, 1413), True, 'import numpy as np\n'), ((1438, 1453), 'numpy.array', 'np.array', (['modes'], {}), '(modes)\n', (1446, 1453), True, 'import numpy as np\n'), ((1703, 1737), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(9, 4)'}), '(1, 1, figsize=(9, 4))\n', (1715, 1737), True, 'from matplotlib import pyplot as plt\n'), ((2407, 2426), 'numpy.delete', 'np.delete', (['iip', 'exc'], {}), '(iip, exc)\n', (2416, 2426), True, 'import numpy as np\n'), ((2609, 2639), 'numpy.linspace', 'np.linspace', (['xl[0]', 'xl[1]', '(100)'], {}), '(xl[0], xl[1], 100)\n', (2620, 2639), True, 'import numpy as np\n'), ((3223, 3258), 'numpy.ma.masked_array', 'np.ma.masked_array', (['dy'], {'mask': 'y.mask'}), '(dy, mask=y.mask)\n', (3241, 3258), True, 'import numpy as np\n'), ((6001, 6029), 'matplotlib.offsetbox.AnchoredText', 'AnchoredText', (['textstr'], {'loc': '(2)'}), '(textstr, loc=2)\n', (6013, 6029), False, 'from matplotlib.offsetbox import AnchoredText\n'), ((6272, 6283), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (6280, 6283), True, 'import numpy as np\n'), ((2483, 2500), 'numpy.hstack', 'np.hstack', (['excfit'], {}), '(excfit)\n', (2492, 2500), True, 'import numpy as np\n'), ((2548, 2563), 'numpy.min', 'np.min', (['qv[iif]'], {}), '(qv[iif])\n', (2554, 2563), True, 'import numpy as np\n'), ((2565, 2580), 'numpy.max', 'np.max', (['qv[iif]'], {}), '(qv[iif])\n', (2571, 2580), True, 'import numpy as np\n'), ((1154, 1188), 'numpy.sqrt', 'np.sqrt', (['(1 - q ** 2 / (4 * k ** 2))'], {}), '(1 - q ** 2 / (4 * k ** 2))\n', (1161, 1188), True, 'import numpy as np\n'), ((3146, 3157), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (3154, 3157), True, 'import numpy as np\n'), ((3191, 3205), 'numpy.isfinite', 'np.isfinite', (['y'], {}), '(y)\n', (3202, 3205), True, 'import numpy as np\n'), ((3581, 3622), 'numpy.array', 'np.array', (['[p for p in iif if p not in nf]'], {}), '([p for p in iif if p not in nf])\n', (3589, 3622), True, 'import numpy as np\n'), ((3645, 3686), 'numpy.array', 'np.array', (['[p for p in iip if p not in nf]'], {}), '([p for p in iip if p not in nf])\n', (3653, 3686), True, 'import numpy as np\n'), ((5013, 5029), 'numpy.sqrt', 'np.sqrt', (['(6 * msd)'], {}), '(6 * msd)\n', (5020, 5029), True, 'import numpy as np\n'), ((3807, 3818), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (3815, 3818), True, 'import numpy as np\n'), ((4233, 4247), 'numpy.mean', 'np.mean', (['x[1:]'], {}), '(x[1:])\n', (4240, 4247), True, 'import numpy as np\n')]
import numpy as np import os import shutil import tempfile import unittest import yt from yt.utilities.exceptions import \ YTProfileDataShape from yt.data_objects.particle_filters import add_particle_filter from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D,\ create_profile from yt.testing import \ assert_equal, \ assert_raises,\ assert_rel_equal, \ fake_random_ds, \ requires_module from yt.utilities.exceptions import YTIllDefinedProfile from yt.visualization.profile_plotter import ProfilePlot, PhasePlot _fields = ("density", "temperature", "dinosaurs", "tribbles") _units = ("g/cm**3", "K", "dyne", "erg") def test_profiles(): ds = fake_random_ds(64, nprocs = 8, fields = _fields, units = _units) nv = ds.domain_dimensions.prod() dd = ds.all_data() (rmi, rma), (tmi, tma), (dmi, dma) = dd.quantities["Extrema"]( ["density", "temperature", "dinosaurs"]) rt, tt, dt = dd.quantities["TotalQuantity"]( ["density", "temperature", "dinosaurs"]) e1, e2 = 0.9, 1.1 for nb in [8, 16, 32, 64]: for input_units in ['mks', 'cgs']: for ex in [rmi, rma, tmi, tma, dmi, dma]: getattr(ex, 'convert_to_%s' % input_units)() # We log all the fields or don't log 'em all. No need to do them # individually. for lf in [True, False]: direct_profile = Profile1D( dd, "density", nb, rmi*e1, rma*e2, lf, weight_field=None) direct_profile.add_fields(["ones", "temperature"]) indirect_profile_s = create_profile( dd, "density", ["ones", "temperature"], n_bins=nb, extrema={'density': (rmi*e1, rma*e2)}, logs={'density': lf}, weight_field=None) indirect_profile_t = create_profile( dd, ("gas", "density"), [("index", "ones"), ("gas", "temperature")], n_bins=nb, extrema={'density': (rmi*e1, rma*e2)}, logs={'density': lf}, weight_field=None) for p1d in [direct_profile, indirect_profile_s, indirect_profile_t]: assert_equal(p1d["index", "ones"].sum(), nv) assert_rel_equal(tt, p1d["gas", "temperature"].sum(), 7) p2d = Profile2D( dd, "density", nb, rmi*e1, rma*e2, lf, "temperature", nb, tmi*e1, tma*e2, lf, weight_field=None) p2d.add_fields(["ones", "temperature"]) assert_equal(p2d["ones"].sum(), nv) assert_rel_equal(tt, p2d["temperature"].sum(), 7) p3d = Profile3D( dd, "density", nb, rmi*e1, rma*e2, lf, "temperature", nb, tmi*e1, tma*e2, lf, "dinosaurs", nb, dmi*e1, dma*e2, lf, weight_field=None) p3d.add_fields(["ones", "temperature"]) assert_equal(p3d["ones"].sum(), nv) assert_rel_equal(tt, p3d["temperature"].sum(), 7) p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field = None) p1d.add_fields("ones") av = nv / nb assert_equal(p1d["ones"], np.ones(nb)*av) # We re-bin ones with a weight now p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field = "temperature") p1d.add_fields(["ones"]) assert_equal(p1d["ones"], np.ones(nb)) # Verify we can access "ones" after adding a new field # See issue 988 p1d.add_fields(["density"]) assert_equal(p1d["ones"], np.ones(nb)) p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field = None) p2d.add_fields("ones") av = nv / nb**2 assert_equal(p2d["ones"], np.ones((nb, nb))*av) # We re-bin ones with a weight now p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field = "temperature") p2d.add_fields(["ones"]) assert_equal(p2d["ones"], np.ones((nb, nb))) p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field = None) p3d.add_fields("ones") av = nv / nb**3 assert_equal(p3d["ones"], np.ones((nb, nb, nb))*av) # We re-bin ones with a weight now p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field = "temperature") p3d.add_fields(["ones"]) assert_equal(p3d["ones"], np.ones((nb,nb,nb))) p2d = create_profile(dd, ('gas', 'density'), ('gas', 'temperature'), weight_field=('gas', 'cell_mass'), extrema={'density': (None, rma*e2)}) assert_equal(p2d.x_bins[0], rmi - np.spacing(rmi)) assert_equal(p2d.x_bins[-1], rma*e2) assert str(ds.field_info['gas', 'cell_mass'].units) == str(p2d.weight.units) p2d = create_profile(dd, ('gas', 'density'), ('gas', 'temperature'), weight_field=('gas', 'cell_mass'), extrema={'density': (rmi*e2, None)}) assert_equal(p2d.x_bins[0], rmi*e2) assert_equal(p2d.x_bins[-1], rma + np.spacing(rma)) extrema_s = {'particle_position_x': (0, 1)} logs_s = {'particle_position_x': False} extrema_t = {('all', 'particle_position_x'): (0, 1)} logs_t = {('all', 'particle_position_x'): False} def test_particle_profiles(): for nproc in [1, 2, 4, 8]: ds = fake_random_ds(32, nprocs=nproc, particles = 32**3) dd = ds.all_data() p1d = Profile1D(dd, "particle_position_x", 128, 0.0, 1.0, False, weight_field = None) p1d.add_fields(["particle_ones"]) assert_equal(p1d["particle_ones"].sum(), 32**3) p1d = create_profile(dd, ["particle_position_x"], ["particle_ones"], weight_field=None, n_bins=128, extrema=extrema_s, logs=logs_s) assert_equal(p1d["particle_ones"].sum(), 32**3) p1d = create_profile(dd, [("all", "particle_position_x")], [("all", "particle_ones")], weight_field=None, n_bins=128, extrema=extrema_t, logs=logs_t) assert_equal(p1d["particle_ones"].sum(), 32**3) p2d = Profile2D(dd, "particle_position_x", 128, 0.0, 1.0, False, "particle_position_y", 128, 0.0, 1.0, False, weight_field = None) p2d.add_fields(["particle_ones"]) assert_equal(p2d["particle_ones"].sum(), 32**3) p3d = Profile3D(dd, "particle_position_x", 128, 0.0, 1.0, False, "particle_position_y", 128, 0.0, 1.0, False, "particle_position_z", 128, 0.0, 1.0, False, weight_field = None) p3d.add_fields(["particle_ones"]) assert_equal(p3d["particle_ones"].sum(), 32**3) def test_mixed_particle_mesh_profiles(): ds = fake_random_ds(32, particles=10) ad = ds.all_data() assert_raises( YTIllDefinedProfile, ProfilePlot, ad, 'radius', 'particle_mass') assert_raises( YTIllDefinedProfile, ProfilePlot, ad, 'radius', ['particle_mass', 'particle_ones']) assert_raises( YTIllDefinedProfile, ProfilePlot, ad, 'radius', ['particle_mass', 'ones']) assert_raises( YTIllDefinedProfile, ProfilePlot, ad, 'particle_radius', 'particle_mass', 'cell_mass') assert_raises( YTIllDefinedProfile, ProfilePlot, ad, 'radius', 'cell_mass', 'particle_ones') assert_raises( YTIllDefinedProfile, PhasePlot, ad, 'radius', 'particle_mass', 'velocity_x') assert_raises( YTIllDefinedProfile, PhasePlot, ad, 'particle_radius', 'particle_mass', 'cell_mass') assert_raises( YTIllDefinedProfile, PhasePlot, ad, 'radius', 'cell_mass', 'particle_ones') assert_raises( YTIllDefinedProfile, PhasePlot, ad, 'particle_radius', 'particle_mass', 'particle_ones') def test_particle_profile_negative_field(): # see Issue #1340 n_particles = int(1e4) ppx, ppy, ppz = np.random.normal(size=[3, n_particles]) pvx, pvy, pvz = - np.ones((3, n_particles)) data = {'particle_position_x': ppx, 'particle_position_y': ppy, 'particle_position_z': ppz, 'particle_velocity_x': pvx, 'particle_velocity_y': pvy, 'particle_velocity_z': pvz} bbox = 1.1*np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)], [min(ppz), max(ppz)]]) ds = yt.load_particles(data, bbox=bbox) ad = ds.all_data() profile = yt.create_profile( ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", logs = {'particle_position_x': True, 'particle_position_y': True, 'particle_position_z': True}, weight_field=None) assert profile['particle_velocity_x'].min() < 0 assert profile.x_bins.min() > 0 assert profile.y_bins.min() > 0 profile = yt.create_profile( ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", weight_field=None) assert profile['particle_velocity_x'].min() < 0 assert profile.x_bins.min() < 0 assert profile.y_bins.min() < 0 # can't use CIC deposition with log-scaled bin fields with assert_raises(RuntimeError): yt.create_profile( ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", logs = {'particle_position_x': True, 'particle_position_y': False, 'particle_position_z': False}, weight_field=None, deposition='cic') # can't use CIC deposition with accumulation or fractional with assert_raises(RuntimeError): yt.create_profile( ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", logs = {'particle_position_x': False, 'particle_position_y': False, 'particle_position_z': False}, weight_field=None, deposition='cic', accumulation=True, fractional=True) def test_profile_zero_weight(): def DMparticles(pfilter, data): filter = data[(pfilter.filtered_type, "particle_type")] == 1 return filter def DM_in_cell_mass(field, data): return data['deposit', 'DM_density']*data['index', 'cell_volume'] add_particle_filter("DM", function=DMparticles, filtered_type='io', requires=["particle_type"]) _fields = ("particle_position_x", "particle_position_y", "particle_position_z", "particle_mass", "particle_velocity_x", "particle_velocity_y", "particle_velocity_z", "particle_type") _units = ('cm', 'cm', 'cm', 'g', 'cm/s', 'cm/s', 'cm/s', 'dimensionless') ds = fake_random_ds(32, particle_fields=_fields, particle_field_units=_units, particles=16) ds.add_particle_filter('DM') ds.add_field(("gas", "DM_cell_mass"), units="g", function=DM_in_cell_mass, sampling_type='cell') sp = ds.sphere(ds.domain_center, (10, 'kpc')) profile = yt.create_profile(sp, [("gas", "density")], [("gas", "radial_velocity")], weight_field=("gas", "DM_cell_mass")) assert not np.any(np.isnan(profile['gas', 'radial_velocity'])) def test_profile_override_limits(): ds = fake_random_ds(64, nprocs = 8, fields = _fields, units = _units) sp = ds.sphere(ds.domain_center, (10, 'kpc')) obins = np.linspace(-5,5,10) profile = yt.create_profile(sp, [ "density"],["temperature"], override_bins={"density":(obins, "g/cm**3")}) assert_equal(ds.arr(obins, "g/cm**3"), profile.x_bins) profile = yt.create_profile(sp, [ "density", "dinosaurs"],["temperature"], override_bins={"density":(obins, "g/cm**3"), "dinosaurs":obins}) assert_equal(ds.arr(obins, "g/cm**3"), profile.x_bins) assert_equal(ds.arr(obins, "dyne"), profile.y_bins) profile = yt.create_profile(sp, [ "density", "dinosaurs", "tribbles"],["temperature"], override_bins={"density":(obins, "g/cm**3"), "dinosaurs":obins, "tribbles":(obins, "erg")}) assert_equal(ds.arr(obins, "g/cm**3"), profile.x_bins) assert_equal(ds.arr(obins, "dyne"), profile.y_bins) assert_equal(ds.arr(obins, "erg"), profile.z_bins) class TestBadProfiles(unittest.TestCase): tmpdir = None curdir = None def setUp(self): self.tmpdir = tempfile.mkdtemp() self.curdir = os.getcwd() os.chdir(self.tmpdir) def tearDown(self): os.chdir(self.curdir) # clean up shutil.rmtree(self.tmpdir) @requires_module('h5py') def test_unequal_data_shape_profile(self): density = np.random.random(128) temperature = np.random.random(128) cell_mass = np.random.random((128, 128)) my_data = { "density": density, "temperature": temperature, "cell_mass": cell_mass} fake_ds_med = {"current_time": yt.YTQuantity(10, "Myr")} yt.save_as_dataset(fake_ds_med, "mydata.h5", my_data) ds = yt.load('mydata.h5') assert_raises( YTProfileDataShape, yt.PhasePlot, ds.data, 'temperature', 'density', 'cell_mass') @requires_module('h5py') def test_unequal_bin_field_profile(self): density = np.random.random(128) temperature = np.random.random(127) cell_mass = np.random.random((128, 128)) my_data = { "density": density, "temperature": temperature, "cell_mass": cell_mass} fake_ds_med = {"current_time": yt.YTQuantity(10, "Myr")} yt.save_as_dataset(fake_ds_med, "mydata.h5", my_data) ds = yt.load('mydata.h5') assert_raises( YTProfileDataShape, yt.PhasePlot, ds.data, 'temperature', 'density', 'cell_mass') def test_index_field_units(): # see #1849 ds = fake_random_ds(16, length_unit=2) ad = ds.all_data() icv_units = ad['index', 'cell_volume'].units assert str(icv_units) == 'code_length**3' gcv_units = ad['gas', 'cell_volume'].units assert str(gcv_units) == 'cm**3' prof = ad.profile(['density', 'velocity_x'], [('gas', 'cell_volume'), ('index', 'cell_volume')], weight_field=None) assert str(prof['index', 'cell_volume'].units) == 'code_length**3' assert str(prof['gas', 'cell_volume'].units) == 'cm**3' @requires_module("astropy") def test_export_astropy(): from yt.units.yt_array import YTArray ds = fake_random_ds(64) ad = ds.all_data() prof = ad.profile('radius', [('gas', 'density'), ('gas', 'velocity_x')], weight_field=('index','ones'), n_bins=32) # export to AstroPy table at1 = prof.to_astropy_table() assert 'radius' in at1.colnames assert 'density' in at1.colnames assert 'velocity_x' in at1.colnames assert_equal(prof.x.d, at1["radius"].value) assert_equal(prof["density"].d, at1["density"].value) assert_equal(prof["velocity_x"].d, at1["velocity_x"].value) assert prof.x.units == YTArray.from_astropy(at1["radius"]).units assert prof["density"].units == YTArray.from_astropy(at1["density"]).units assert prof["velocity_x"].units == YTArray.from_astropy(at1["velocity_x"]).units assert np.all(at1.mask['density'] == prof.used) at2 = prof.to_astropy_table(fields="density", only_used=True) assert 'radius' in at2.colnames assert 'velocity_x' not in at2.colnames assert_equal(prof.x.d[prof.used], at2["radius"].value) assert_equal(prof["density"].d[prof.used], at2["density"].value) @requires_module("pandas") def test_export_pandas(): ds = fake_random_ds(64) ad = ds.all_data() prof = ad.profile('radius', [('gas', 'density'), ('gas', 'velocity_x')], weight_field=('index','ones'), n_bins=32) # export to pandas DataFrame df1 = prof.to_dataframe() assert 'radius' in df1.columns assert 'density' in df1.columns assert 'velocity_x' in df1.columns assert_equal(prof.x.d, df1["radius"]) assert_equal(prof["density"].d, np.nan_to_num(df1["density"])) assert_equal(prof["velocity_x"].d, np.nan_to_num(df1["velocity_x"])) df2 = prof.to_dataframe(fields="density", only_used=True) assert 'radius' in df2.columns assert 'velocity_x' not in df2.columns assert_equal(prof.x.d[prof.used], df2["radius"]) assert_equal(prof["density"].d[prof.used], df2["density"])
[ "numpy.nan_to_num", "yt.YTQuantity", "yt.data_objects.profiles.Profile2D", "numpy.ones", "numpy.isnan", "numpy.random.normal", "shutil.rmtree", "os.chdir", "yt.data_objects.profiles.create_profile", "yt.testing.assert_equal", "yt.load_particles", "yt.testing.fake_random_ds", "tempfile.mkdtemp", "numpy.linspace", "yt.data_objects.profiles.Profile3D", "yt.testing.requires_module", "yt.testing.assert_raises", "yt.data_objects.profiles.Profile1D", "yt.save_as_dataset", "numpy.spacing", "yt.load", "yt.data_objects.particle_filters.add_particle_filter", "yt.create_profile", "numpy.all", "os.getcwd", "yt.units.yt_array.YTArray.from_astropy", "numpy.random.random" ]
[((15715, 15741), 'yt.testing.requires_module', 'requires_module', (['"""astropy"""'], {}), "('astropy')\n", (15730, 15741), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((16912, 16937), 'yt.testing.requires_module', 'requires_module', (['"""pandas"""'], {}), "('pandas')\n", (16927, 16937), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((693, 751), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(64)'], {'nprocs': '(8)', 'fields': '_fields', 'units': '_units'}), '(64, nprocs=8, fields=_fields, units=_units)\n', (707, 751), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((7616, 7648), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(32)'], {'particles': '(10)'}), '(32, particles=10)\n', (7630, 7648), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((7676, 7754), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'ProfilePlot', 'ad', '"""radius"""', '"""particle_mass"""'], {}), "(YTIllDefinedProfile, ProfilePlot, ad, 'radius', 'particle_mass')\n", (7689, 7754), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((7768, 7870), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'ProfilePlot', 'ad', '"""radius"""', "['particle_mass', 'particle_ones']"], {}), "(YTIllDefinedProfile, ProfilePlot, ad, 'radius', [\n 'particle_mass', 'particle_ones'])\n", (7781, 7870), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((7887, 7980), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'ProfilePlot', 'ad', '"""radius"""', "['particle_mass', 'ones']"], {}), "(YTIllDefinedProfile, ProfilePlot, ad, 'radius', [\n 'particle_mass', 'ones'])\n", (7900, 7980), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((7997, 8101), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'ProfilePlot', 'ad', '"""particle_radius"""', '"""particle_mass"""', '"""cell_mass"""'], {}), "(YTIllDefinedProfile, ProfilePlot, ad, 'particle_radius',\n 'particle_mass', 'cell_mass')\n", (8010, 8101), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((8119, 8214), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'ProfilePlot', 'ad', '"""radius"""', '"""cell_mass"""', '"""particle_ones"""'], {}), "(YTIllDefinedProfile, ProfilePlot, ad, 'radius', 'cell_mass',\n 'particle_ones')\n", (8132, 8214), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((8233, 8327), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'PhasePlot', 'ad', '"""radius"""', '"""particle_mass"""', '"""velocity_x"""'], {}), "(YTIllDefinedProfile, PhasePlot, ad, 'radius', 'particle_mass',\n 'velocity_x')\n", (8246, 8327), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((8345, 8447), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'PhasePlot', 'ad', '"""particle_radius"""', '"""particle_mass"""', '"""cell_mass"""'], {}), "(YTIllDefinedProfile, PhasePlot, ad, 'particle_radius',\n 'particle_mass', 'cell_mass')\n", (8358, 8447), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((8465, 8558), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'PhasePlot', 'ad', '"""radius"""', '"""cell_mass"""', '"""particle_ones"""'], {}), "(YTIllDefinedProfile, PhasePlot, ad, 'radius', 'cell_mass',\n 'particle_ones')\n", (8478, 8558), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((8576, 8682), 'yt.testing.assert_raises', 'assert_raises', (['YTIllDefinedProfile', 'PhasePlot', 'ad', '"""particle_radius"""', '"""particle_mass"""', '"""particle_ones"""'], {}), "(YTIllDefinedProfile, PhasePlot, ad, 'particle_radius',\n 'particle_mass', 'particle_ones')\n", (8589, 8682), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((8811, 8850), 'numpy.random.normal', 'np.random.normal', ([], {'size': '[3, n_particles]'}), '(size=[3, n_particles])\n', (8827, 8850), True, 'import numpy as np\n'), ((9242, 9276), 'yt.load_particles', 'yt.load_particles', (['data'], {'bbox': 'bbox'}), '(data, bbox=bbox)\n', (9259, 9276), False, 'import yt\n'), ((9315, 9533), 'yt.create_profile', 'yt.create_profile', (['ad', "['particle_position_x', 'particle_position_y']", '"""particle_velocity_x"""'], {'logs': "{'particle_position_x': True, 'particle_position_y': True,\n 'particle_position_z': True}", 'weight_field': 'None'}), "(ad, ['particle_position_x', 'particle_position_y'],\n 'particle_velocity_x', logs={'particle_position_x': True,\n 'particle_position_y': True, 'particle_position_z': True}, weight_field\n =None)\n", (9332, 9533), False, 'import yt\n'), ((9735, 9850), 'yt.create_profile', 'yt.create_profile', (['ad', "['particle_position_x', 'particle_position_y']", '"""particle_velocity_x"""'], {'weight_field': 'None'}), "(ad, ['particle_position_x', 'particle_position_y'],\n 'particle_velocity_x', weight_field=None)\n", (9752, 9850), False, 'import yt\n'), ((11204, 11303), 'yt.data_objects.particle_filters.add_particle_filter', 'add_particle_filter', (['"""DM"""'], {'function': 'DMparticles', 'filtered_type': '"""io"""', 'requires': "['particle_type']"}), "('DM', function=DMparticles, filtered_type='io',\n requires=['particle_type'])\n", (11223, 11303), False, 'from yt.data_objects.particle_filters import add_particle_filter\n'), ((11629, 11719), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(32)'], {'particle_fields': '_fields', 'particle_field_units': '_units', 'particles': '(16)'}), '(32, particle_fields=_fields, particle_field_units=_units,\n particles=16)\n', (11643, 11719), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((11958, 12073), 'yt.create_profile', 'yt.create_profile', (['sp', "[('gas', 'density')]", "[('gas', 'radial_velocity')]"], {'weight_field': "('gas', 'DM_cell_mass')"}), "(sp, [('gas', 'density')], [('gas', 'radial_velocity')],\n weight_field=('gas', 'DM_cell_mass'))\n", (11975, 12073), False, 'import yt\n'), ((12280, 12338), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(64)'], {'nprocs': '(8)', 'fields': '_fields', 'units': '_units'}), '(64, nprocs=8, fields=_fields, units=_units)\n', (12294, 12338), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((12408, 12430), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', '(10)'], {}), '(-5, 5, 10)\n', (12419, 12430), True, 'import numpy as np\n'), ((12443, 12546), 'yt.create_profile', 'yt.create_profile', (['sp', "['density']", "['temperature']"], {'override_bins': "{'density': (obins, 'g/cm**3')}"}), "(sp, ['density'], ['temperature'], override_bins={\n 'density': (obins, 'g/cm**3')})\n", (12460, 12546), False, 'import yt\n'), ((12679, 12814), 'yt.create_profile', 'yt.create_profile', (['sp', "['density', 'dinosaurs']", "['temperature']"], {'override_bins': "{'density': (obins, 'g/cm**3'), 'dinosaurs': obins}"}), "(sp, ['density', 'dinosaurs'], ['temperature'],\n override_bins={'density': (obins, 'g/cm**3'), 'dinosaurs': obins})\n", (12696, 12814), False, 'import yt\n'), ((13050, 13229), 'yt.create_profile', 'yt.create_profile', (['sp', "['density', 'dinosaurs', 'tribbles']", "['temperature']"], {'override_bins': "{'density': (obins, 'g/cm**3'), 'dinosaurs': obins, 'tribbles': (obins, 'erg')}"}), "(sp, ['density', 'dinosaurs', 'tribbles'], ['temperature'],\n override_bins={'density': (obins, 'g/cm**3'), 'dinosaurs': obins,\n 'tribbles': (obins, 'erg')})\n", (13067, 13229), False, 'import yt\n'), ((13869, 13892), 'yt.testing.requires_module', 'requires_module', (['"""h5py"""'], {}), "('h5py')\n", (13884, 13892), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((14500, 14523), 'yt.testing.requires_module', 'requires_module', (['"""h5py"""'], {}), "('h5py')\n", (14515, 14523), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((15181, 15214), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(16)'], {'length_unit': '(2)'}), '(16, length_unit=2)\n', (15195, 15214), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((15820, 15838), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(64)'], {}), '(64)\n', (15834, 15838), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((16184, 16227), 'yt.testing.assert_equal', 'assert_equal', (['prof.x.d', "at1['radius'].value"], {}), "(prof.x.d, at1['radius'].value)\n", (16196, 16227), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((16232, 16285), 'yt.testing.assert_equal', 'assert_equal', (["prof['density'].d", "at1['density'].value"], {}), "(prof['density'].d, at1['density'].value)\n", (16244, 16285), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((16290, 16349), 'yt.testing.assert_equal', 'assert_equal', (["prof['velocity_x'].d", "at1['velocity_x'].value"], {}), "(prof['velocity_x'].d, at1['velocity_x'].value)\n", (16302, 16349), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((16594, 16634), 'numpy.all', 'np.all', (["(at1.mask['density'] == prof.used)"], {}), "(at1.mask['density'] == prof.used)\n", (16600, 16634), True, 'import numpy as np\n'), ((16785, 16839), 'yt.testing.assert_equal', 'assert_equal', (['prof.x.d[prof.used]', "at2['radius'].value"], {}), "(prof.x.d[prof.used], at2['radius'].value)\n", (16797, 16839), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((16844, 16908), 'yt.testing.assert_equal', 'assert_equal', (["prof['density'].d[prof.used]", "at2['density'].value"], {}), "(prof['density'].d[prof.used], at2['density'].value)\n", (16856, 16908), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((16973, 16991), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(64)'], {}), '(64)\n', (16987, 16991), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((17333, 17370), 'yt.testing.assert_equal', 'assert_equal', (['prof.x.d', "df1['radius']"], {}), "(prof.x.d, df1['radius'])\n", (17345, 17370), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((17655, 17703), 'yt.testing.assert_equal', 'assert_equal', (['prof.x.d[prof.used]', "df2['radius']"], {}), "(prof.x.d[prof.used], df2['radius'])\n", (17667, 17703), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((17708, 17766), 'yt.testing.assert_equal', 'assert_equal', (["prof['density'].d[prof.used]", "df2['density']"], {}), "(prof['density'].d[prof.used], df2['density'])\n", (17720, 17766), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((3223, 3281), 'yt.data_objects.profiles.Profile1D', 'Profile1D', (['dd', '"""x"""', 'nb', '(0.0)', '(1.0)', '(False)'], {'weight_field': 'None'}), "(dd, 'x', nb, 0.0, 1.0, False, weight_field=None)\n", (3232, 3281), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((3468, 3535), 'yt.data_objects.profiles.Profile1D', 'Profile1D', (['dd', '"""x"""', 'nb', '(0.0)', '(1.0)', '(False)'], {'weight_field': '"""temperature"""'}), "(dd, 'x', nb, 0.0, 1.0, False, weight_field='temperature')\n", (3477, 3535), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((3828, 3916), 'yt.data_objects.profiles.Profile2D', 'Profile2D', (['dd', '"""x"""', 'nb', '(0.0)', '(1.0)', '(False)', '"""y"""', 'nb', '(0.0)', '(1.0)', '(False)'], {'weight_field': 'None'}), "(dd, 'x', nb, 0.0, 1.0, False, 'y', nb, 0.0, 1.0, False,\n weight_field=None)\n", (3837, 3916), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((4140, 4237), 'yt.data_objects.profiles.Profile2D', 'Profile2D', (['dd', '"""x"""', 'nb', '(0.0)', '(1.0)', '(False)', '"""y"""', 'nb', '(0.0)', '(1.0)', '(False)'], {'weight_field': '"""temperature"""'}), "(dd, 'x', nb, 0.0, 1.0, False, 'y', nb, 0.0, 1.0, False,\n weight_field='temperature')\n", (4149, 4237), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((4393, 4508), 'yt.data_objects.profiles.Profile3D', 'Profile3D', (['dd', '"""x"""', 'nb', '(0.0)', '(1.0)', '(False)', '"""y"""', 'nb', '(0.0)', '(1.0)', '(False)', '"""z"""', 'nb', '(0.0)', '(1.0)', '(False)'], {'weight_field': 'None'}), "(dd, 'x', nb, 0.0, 1.0, False, 'y', nb, 0.0, 1.0, False, 'z', nb, \n 0.0, 1.0, False, weight_field=None)\n", (4402, 4508), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((4763, 4887), 'yt.data_objects.profiles.Profile3D', 'Profile3D', (['dd', '"""x"""', 'nb', '(0.0)', '(1.0)', '(False)', '"""y"""', 'nb', '(0.0)', '(1.0)', '(False)', '"""z"""', 'nb', '(0.0)', '(1.0)', '(False)'], {'weight_field': '"""temperature"""'}), "(dd, 'x', nb, 0.0, 1.0, False, 'y', nb, 0.0, 1.0, False, 'z', nb, \n 0.0, 1.0, False, weight_field='temperature')\n", (4772, 4887), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((5072, 5213), 'yt.data_objects.profiles.create_profile', 'create_profile', (['dd', "('gas', 'density')", "('gas', 'temperature')"], {'weight_field': "('gas', 'cell_mass')", 'extrema': "{'density': (None, rma * e2)}"}), "(dd, ('gas', 'density'), ('gas', 'temperature'), weight_field\n =('gas', 'cell_mass'), extrema={'density': (None, rma * e2)})\n", (5086, 5213), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((5332, 5370), 'yt.testing.assert_equal', 'assert_equal', (['p2d.x_bins[-1]', '(rma * e2)'], {}), '(p2d.x_bins[-1], rma * e2)\n', (5344, 5370), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((5469, 5610), 'yt.data_objects.profiles.create_profile', 'create_profile', (['dd', "('gas', 'density')", "('gas', 'temperature')"], {'weight_field': "('gas', 'cell_mass')", 'extrema': "{'density': (rmi * e2, None)}"}), "(dd, ('gas', 'density'), ('gas', 'temperature'), weight_field\n =('gas', 'cell_mass'), extrema={'density': (rmi * e2, None)})\n", (5483, 5610), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((5670, 5707), 'yt.testing.assert_equal', 'assert_equal', (['p2d.x_bins[0]', '(rmi * e2)'], {}), '(p2d.x_bins[0], rmi * e2)\n', (5682, 5707), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((6030, 6081), 'yt.testing.fake_random_ds', 'fake_random_ds', (['(32)'], {'nprocs': 'nproc', 'particles': '(32 ** 3)'}), '(32, nprocs=nproc, particles=32 ** 3)\n', (6044, 6081), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((6124, 6201), 'yt.data_objects.profiles.Profile1D', 'Profile1D', (['dd', '"""particle_position_x"""', '(128)', '(0.0)', '(1.0)', '(False)'], {'weight_field': 'None'}), "(dd, 'particle_position_x', 128, 0.0, 1.0, False, weight_field=None)\n", (6133, 6201), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((6341, 6471), 'yt.data_objects.profiles.create_profile', 'create_profile', (['dd', "['particle_position_x']", "['particle_ones']"], {'weight_field': 'None', 'n_bins': '(128)', 'extrema': 'extrema_s', 'logs': 'logs_s'}), "(dd, ['particle_position_x'], ['particle_ones'], weight_field\n =None, n_bins=128, extrema=extrema_s, logs=logs_s)\n", (6355, 6471), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((6596, 6747), 'yt.data_objects.profiles.create_profile', 'create_profile', (['dd', "[('all', 'particle_position_x')]", "[('all', 'particle_ones')]"], {'weight_field': 'None', 'n_bins': '(128)', 'extrema': 'extrema_t', 'logs': 'logs_t'}), "(dd, [('all', 'particle_position_x')], [('all',\n 'particle_ones')], weight_field=None, n_bins=128, extrema=extrema_t,\n logs=logs_t)\n", (6610, 6747), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((6927, 7053), 'yt.data_objects.profiles.Profile2D', 'Profile2D', (['dd', '"""particle_position_x"""', '(128)', '(0.0)', '(1.0)', '(False)', '"""particle_position_y"""', '(128)', '(0.0)', '(1.0)', '(False)'], {'weight_field': 'None'}), "(dd, 'particle_position_x', 128, 0.0, 1.0, False,\n 'particle_position_y', 128, 0.0, 1.0, False, weight_field=None)\n", (6936, 7053), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((7217, 7392), 'yt.data_objects.profiles.Profile3D', 'Profile3D', (['dd', '"""particle_position_x"""', '(128)', '(0.0)', '(1.0)', '(False)', '"""particle_position_y"""', '(128)', '(0.0)', '(1.0)', '(False)', '"""particle_position_z"""', '(128)', '(0.0)', '(1.0)', '(False)'], {'weight_field': 'None'}), "(dd, 'particle_position_x', 128, 0.0, 1.0, False,\n 'particle_position_y', 128, 0.0, 1.0, False, 'particle_position_z', 128,\n 0.0, 1.0, False, weight_field=None)\n", (7226, 7392), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((8873, 8898), 'numpy.ones', 'np.ones', (['(3, n_particles)'], {}), '((3, n_particles))\n', (8880, 8898), True, 'import numpy as np\n'), ((10072, 10099), 'yt.testing.assert_raises', 'assert_raises', (['RuntimeError'], {}), '(RuntimeError)\n', (10085, 10099), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((10109, 10346), 'yt.create_profile', 'yt.create_profile', (['ad', "['particle_position_x', 'particle_position_y']", '"""particle_velocity_x"""'], {'logs': "{'particle_position_x': True, 'particle_position_y': False,\n 'particle_position_z': False}", 'weight_field': 'None', 'deposition': '"""cic"""'}), "(ad, ['particle_position_x', 'particle_position_y'],\n 'particle_velocity_x', logs={'particle_position_x': True,\n 'particle_position_y': False, 'particle_position_z': False},\n weight_field=None, deposition='cic')\n", (10126, 10346), False, 'import yt\n'), ((10511, 10538), 'yt.testing.assert_raises', 'assert_raises', (['RuntimeError'], {}), '(RuntimeError)\n', (10524, 10538), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((10548, 10822), 'yt.create_profile', 'yt.create_profile', (['ad', "['particle_position_x', 'particle_position_y']", '"""particle_velocity_x"""'], {'logs': "{'particle_position_x': False, 'particle_position_y': False,\n 'particle_position_z': False}", 'weight_field': 'None', 'deposition': '"""cic"""', 'accumulation': '(True)', 'fractional': '(True)'}), "(ad, ['particle_position_x', 'particle_position_y'],\n 'particle_velocity_x', logs={'particle_position_x': False,\n 'particle_position_y': False, 'particle_position_z': False},\n weight_field=None, deposition='cic', accumulation=True, fractional=True)\n", (10565, 10822), False, 'import yt\n'), ((13671, 13689), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (13687, 13689), False, 'import tempfile\n'), ((13712, 13723), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (13721, 13723), False, 'import os\n'), ((13732, 13753), 'os.chdir', 'os.chdir', (['self.tmpdir'], {}), '(self.tmpdir)\n', (13740, 13753), False, 'import os\n'), ((13787, 13808), 'os.chdir', 'os.chdir', (['self.curdir'], {}), '(self.curdir)\n', (13795, 13808), False, 'import os\n'), ((13836, 13862), 'shutil.rmtree', 'shutil.rmtree', (['self.tmpdir'], {}), '(self.tmpdir)\n', (13849, 13862), False, 'import shutil\n'), ((13958, 13979), 'numpy.random.random', 'np.random.random', (['(128)'], {}), '(128)\n', (13974, 13979), True, 'import numpy as np\n'), ((14002, 14023), 'numpy.random.random', 'np.random.random', (['(128)'], {}), '(128)\n', (14018, 14023), True, 'import numpy as np\n'), ((14044, 14072), 'numpy.random.random', 'np.random.random', (['(128, 128)'], {}), '((128, 128))\n', (14060, 14072), True, 'import numpy as np\n'), ((14275, 14328), 'yt.save_as_dataset', 'yt.save_as_dataset', (['fake_ds_med', '"""mydata.h5"""', 'my_data'], {}), "(fake_ds_med, 'mydata.h5', my_data)\n", (14293, 14328), False, 'import yt\n'), ((14343, 14363), 'yt.load', 'yt.load', (['"""mydata.h5"""'], {}), "('mydata.h5')\n", (14350, 14363), False, 'import yt\n'), ((14373, 14472), 'yt.testing.assert_raises', 'assert_raises', (['YTProfileDataShape', 'yt.PhasePlot', 'ds.data', '"""temperature"""', '"""density"""', '"""cell_mass"""'], {}), "(YTProfileDataShape, yt.PhasePlot, ds.data, 'temperature',\n 'density', 'cell_mass')\n", (14386, 14472), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((14588, 14609), 'numpy.random.random', 'np.random.random', (['(128)'], {}), '(128)\n', (14604, 14609), True, 'import numpy as np\n'), ((14632, 14653), 'numpy.random.random', 'np.random.random', (['(127)'], {}), '(127)\n', (14648, 14653), True, 'import numpy as np\n'), ((14674, 14702), 'numpy.random.random', 'np.random.random', (['(128, 128)'], {}), '((128, 128))\n', (14690, 14702), True, 'import numpy as np\n'), ((14905, 14958), 'yt.save_as_dataset', 'yt.save_as_dataset', (['fake_ds_med', '"""mydata.h5"""', 'my_data'], {}), "(fake_ds_med, 'mydata.h5', my_data)\n", (14923, 14958), False, 'import yt\n'), ((14973, 14993), 'yt.load', 'yt.load', (['"""mydata.h5"""'], {}), "('mydata.h5')\n", (14980, 14993), False, 'import yt\n'), ((15003, 15102), 'yt.testing.assert_raises', 'assert_raises', (['YTProfileDataShape', 'yt.PhasePlot', 'ds.data', '"""temperature"""', '"""density"""', '"""cell_mass"""'], {}), "(YTProfileDataShape, yt.PhasePlot, ds.data, 'temperature',\n 'density', 'cell_mass')\n", (15016, 15102), False, 'from yt.testing import assert_equal, assert_raises, assert_rel_equal, fake_random_ds, requires_module\n'), ((17407, 17436), 'numpy.nan_to_num', 'np.nan_to_num', (["df1['density']"], {}), "(df1['density'])\n", (17420, 17436), True, 'import numpy as np\n'), ((17477, 17509), 'numpy.nan_to_num', 'np.nan_to_num', (["df1['velocity_x']"], {}), "(df1['velocity_x'])\n", (17490, 17509), True, 'import numpy as np\n'), ((3629, 3640), 'numpy.ones', 'np.ones', (['nb'], {}), '(nb)\n', (3636, 3640), True, 'import numpy as np\n'), ((3800, 3811), 'numpy.ones', 'np.ones', (['nb'], {}), '(nb)\n', (3807, 3811), True, 'import numpy as np\n'), ((4359, 4376), 'numpy.ones', 'np.ones', (['(nb, nb)'], {}), '((nb, nb))\n', (4366, 4376), True, 'import numpy as np\n'), ((5036, 5057), 'numpy.ones', 'np.ones', (['(nb, nb, nb)'], {}), '((nb, nb, nb))\n', (5043, 5057), True, 'import numpy as np\n'), ((12189, 12232), 'numpy.isnan', 'np.isnan', (["profile['gas', 'radial_velocity']"], {}), "(profile['gas', 'radial_velocity'])\n", (12197, 12232), True, 'import numpy as np\n'), ((14241, 14265), 'yt.YTQuantity', 'yt.YTQuantity', (['(10)', '"""Myr"""'], {}), "(10, 'Myr')\n", (14254, 14265), False, 'import yt\n'), ((14871, 14895), 'yt.YTQuantity', 'yt.YTQuantity', (['(10)', '"""Myr"""'], {}), "(10, 'Myr')\n", (14884, 14895), False, 'import yt\n'), ((16377, 16412), 'yt.units.yt_array.YTArray.from_astropy', 'YTArray.from_astropy', (["at1['radius']"], {}), "(at1['radius'])\n", (16397, 16412), False, 'from yt.units.yt_array import YTArray\n'), ((16455, 16491), 'yt.units.yt_array.YTArray.from_astropy', 'YTArray.from_astropy', (["at1['density']"], {}), "(at1['density'])\n", (16475, 16491), False, 'from yt.units.yt_array import YTArray\n'), ((16537, 16576), 'yt.units.yt_array.YTArray.from_astropy', 'YTArray.from_astropy', (["at1['velocity_x']"], {}), "(at1['velocity_x'])\n", (16557, 16576), False, 'from yt.units.yt_array import YTArray\n'), ((1420, 1491), 'yt.data_objects.profiles.Profile1D', 'Profile1D', (['dd', '"""density"""', 'nb', '(rmi * e1)', '(rma * e2)', 'lf'], {'weight_field': 'None'}), "(dd, 'density', nb, rmi * e1, rma * e2, lf, weight_field=None)\n", (1429, 1491), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((1614, 1768), 'yt.data_objects.profiles.create_profile', 'create_profile', (['dd', '"""density"""', "['ones', 'temperature']"], {'n_bins': 'nb', 'extrema': "{'density': (rmi * e1, rma * e2)}", 'logs': "{'density': lf}", 'weight_field': 'None'}), "(dd, 'density', ['ones', 'temperature'], n_bins=nb, extrema={\n 'density': (rmi * e1, rma * e2)}, logs={'density': lf}, weight_field=None)\n", (1628, 1768), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((1859, 2045), 'yt.data_objects.profiles.create_profile', 'create_profile', (['dd', "('gas', 'density')", "[('index', 'ones'), ('gas', 'temperature')]"], {'n_bins': 'nb', 'extrema': "{'density': (rmi * e1, rma * e2)}", 'logs': "{'density': lf}", 'weight_field': 'None'}), "(dd, ('gas', 'density'), [('index', 'ones'), ('gas',\n 'temperature')], n_bins=nb, extrema={'density': (rmi * e1, rma * e2)},\n logs={'density': lf}, weight_field=None)\n", (1873, 2045), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((2394, 2512), 'yt.data_objects.profiles.Profile2D', 'Profile2D', (['dd', '"""density"""', 'nb', '(rmi * e1)', '(rma * e2)', 'lf', '"""temperature"""', 'nb', '(tmi * e1)', '(tma * e2)', 'lf'], {'weight_field': 'None'}), "(dd, 'density', nb, rmi * e1, rma * e2, lf, 'temperature', nb, tmi *\n e1, tma * e2, lf, weight_field=None)\n", (2403, 2512), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((2783, 2947), 'yt.data_objects.profiles.Profile3D', 'Profile3D', (['dd', '"""density"""', 'nb', '(rmi * e1)', '(rma * e2)', 'lf', '"""temperature"""', 'nb', '(tmi * e1)', '(tma * e2)', 'lf', '"""dinosaurs"""', 'nb', '(dmi * e1)', '(dma * e2)', 'lf'], {'weight_field': 'None'}), "(dd, 'density', nb, rmi * e1, rma * e2, lf, 'temperature', nb, tmi *\n e1, tma * e2, lf, 'dinosaurs', nb, dmi * e1, dma * e2, lf, weight_field\n =None)\n", (2792, 2947), False, 'from yt.data_objects.profiles import Profile1D, Profile2D, Profile3D, create_profile\n'), ((3394, 3405), 'numpy.ones', 'np.ones', (['nb'], {}), '(nb)\n', (3401, 3405), True, 'import numpy as np\n'), ((4060, 4077), 'numpy.ones', 'np.ones', (['(nb, nb)'], {}), '((nb, nb))\n', (4067, 4077), True, 'import numpy as np\n'), ((4679, 4700), 'numpy.ones', 'np.ones', (['(nb, nb, nb)'], {}), '((nb, nb, nb))\n', (4686, 4700), True, 'import numpy as np\n'), ((5307, 5322), 'numpy.spacing', 'np.spacing', (['rmi'], {}), '(rmi)\n', (5317, 5322), True, 'import numpy as np\n'), ((5749, 5764), 'numpy.spacing', 'np.spacing', (['rma'], {}), '(rma)\n', (5759, 5764), True, 'import numpy as np\n')]
"""Reconcile Halo issues against Jira.""" import os import logging from concurrent.futures import ThreadPoolExecutor, as_completed from cloudpassage.exceptions import CloudPassageResourceExistence from itertools import groupby import json import hashlib from .halo import Halo from .jira_local import JiraLocal from .logger import Logger class Reconciler(object): """Reconcile issues between Halo and Jira. Args: halo (obj): Instance of jlib.Halo() jira (obj): Instance of jlib.JiraLocal() dynamic_mapping (dict): Dictionary describing dynamic field mapping from Halo to Jira. See README.md for details. static_mapping (dict): Statically-defined fields for Jira. See README.md for more info. """ def __init__(self, config, rule): self.logger = Logger() self.config = config self.halo = Halo(config.halo_api_key, config.halo_api_secret_key, config.halo_api_hostname) self.jira = JiraLocal(config.jira_api_url, config.jira_api_user, config.jira_api_token, rule, config.jira_fields_dict) self.rule = rule def reconcile_issues(self, halo_issues, project_key): jira_issues_dict = self.jira.get_jira_issues(project_key, halo_issues) jira_epics_dict = self.jira.get_jira_epics_or_issues(project_key, "Epic") issues_with_gk = [] futures_to_group_key = {} groupby_params = self.rule.get("groupby", []) sorted_issues = sorted(halo_issues, key=lambda issue: [issue[x] for x in groupby_params]) with ThreadPoolExecutor(max_workers=os.cpu_count()*2) as executor: for group_key, issues_group in groupby( sorted_issues, key=lambda issue: {x: issue[x] for x in groupby_params}): group_key_hash = "" if group_key: group_key_str = json.dumps(group_key) group_key_hash = hashlib.sha256(group_key_str.encode()).hexdigest() if group_key_hash not in jira_epics_dict: futures_to_group_key[executor.submit( self.jira.create_jira_epic, group_key_hash, group_key_str, project_key )] = group_key_hash for issue in issues_group: issue["groupby_key"] = group_key_hash issues_with_gk.append(issue) for future in as_completed(futures_to_group_key): jira_epics_dict[futures_to_group_key[future]] = future.result() fields = self.rule.get("fields") or {} self.jira.push_issues( issues_with_gk, jira_epics_dict, jira_issues_dict, self.config.jira_fields_dict, fields, project_key ) def get_jira_halo_issues(self, jira_issues_dict): issues = [] with ThreadPoolExecutor(max_workers=os.cpu_count()*2) as executor: futures = [executor.submit(self.halo.issue.describe, issue_id) for issue_id in jira_issues_dict] for future in as_completed(futures): try: issues.append(future.result()["issue"]) except (CloudPassageResourceExistence, KeyError): pass return issues def update_all_jira_issues(self): jira_issues_dict = self.jira.get_jira_epics_or_issues( self.rule["jira_config"]["project_keys"], self.rule["jira_config"]["jira_issue_type"] ) jira_epics_dict = {} fields = self.rule.get("fields") or {} halo_issues = self.get_jira_halo_issues(jira_issues_dict) if halo_issues: self.logger.info(f"Updating {len(halo_issues)} active Jira issues") halo_issues = self.halo.get_asset_and_findings(halo_issues) halo_issues = self.halo.get_cve_details(halo_issues) self.jira.push_issues( halo_issues, jira_epics_dict, jira_issues_dict, self.config.jira_fields_dict, fields ) def cleanup(self, project_keys): self.jira.cleanup_epics(project_keys)
[ "itertools.groupby", "os.cpu_count", "concurrent.futures.as_completed", "json.dumps" ]
[((1699, 1778), 'itertools.groupby', 'groupby', (['sorted_issues'], {'key': '(lambda issue: {x: issue[x] for x in groupby_params})'}), '(sorted_issues, key=lambda issue: {x: issue[x] for x in groupby_params})\n', (1706, 1778), False, 'from itertools import groupby\n'), ((2457, 2491), 'concurrent.futures.as_completed', 'as_completed', (['futures_to_group_key'], {}), '(futures_to_group_key)\n', (2469, 2491), False, 'from concurrent.futures import ThreadPoolExecutor, as_completed\n'), ((3120, 3141), 'concurrent.futures.as_completed', 'as_completed', (['futures'], {}), '(futures)\n', (3132, 3141), False, 'from concurrent.futures import ThreadPoolExecutor, as_completed\n'), ((1903, 1924), 'json.dumps', 'json.dumps', (['group_key'], {}), '(group_key)\n', (1913, 1924), False, 'import json\n'), ((1625, 1639), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (1637, 1639), False, 'import os\n'), ((2954, 2968), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (2966, 2968), False, 'import os\n')]
""" @author: <NAME> @contact: U{<EMAIL><mailto:<EMAIL>>} @since: 2011-11-23 """ from abc import abstractmethod from pytest_splunk_addon.helmut.manager import Manager from pytest_splunk_addon.helmut.misc.collection import Collection from pytest_splunk_addon.helmut.misc.manager_utils import ( create_wrapper_from_connector_mapping, ) PATH_PERFIX = "/servicesNS/nobody/system/data/indexes/" COUNT_OFFSET = "?count=-1&offset=0" DISABLE = "/disable" ENABLE = "/enable" SYSTEM_MESSAGE = "/servicesNS/nobody/system/messages" RESTART = "/services/server/control/restart" ROLL_HOT_BUCKETS = "/roll-hot-buckets" class Indexes(Manager, Collection): """ This class represents the Indexes endpoint in REST which is a collection of L{Index}es. """ def __init__(self, connector): """ Indexes' constructor. @param connector: The connector through which Splunk is reached. @type connector: Connector """ Manager.__init__(self, connector) Collection.__init__(self) def __new__(cls, connector): """ The function called when creating a new Indexes object. An internal map stores mappings from connector type to corresponding Indexes subclass, making sure that the appropriate Indexes class is evoked. @param connector: The connector through which Splunk is reached. @type connector: Connector """ mappings = _CONNECTOR_TO_WRAPPER_MAPPINGS return create_wrapper_from_connector_mapping(cls, connector, mappings) @abstractmethod def create_index(self, index_name): """ Create an index. @param index_name: The name of the new index. @type index_name: String """ pass @abstractmethod def __getitem__(self, index_name): """ Retrieve an index. @param index_name: Index name. @type index_name: L{String} """ pass class IndexNotFound(RuntimeError): def __init__(self, index_name): self.index_name = index_name super(IndexNotFound, self).__init__(self._error_message) @property def _error_message(self): f = "Could not find index with name {name}" return f.format(name=self.index_name) class OperationError(Exception): """Raised for a failed operation, such as a time out.""" pass # We need to do this at the bottom to avoid import errors from pytest_splunk_addon.helmut.connector.sdk import SDKConnector from pytest_splunk_addon.helmut.connector.rest import RESTConnector from pytest_splunk_addon.helmut.manager.indexes.sdk import SDKIndexesWrapper from pytest_splunk_addon.helmut.manager.indexes.rest import RESTIndexesWrapper _CONNECTOR_TO_WRAPPER_MAPPINGS = { SDKConnector: SDKIndexesWrapper, RESTConnector: RESTIndexesWrapper, }
[ "pytest_splunk_addon.helmut.manager.Manager.__init__", "pytest_splunk_addon.helmut.misc.manager_utils.create_wrapper_from_connector_mapping", "pytest_splunk_addon.helmut.misc.collection.Collection.__init__" ]
[((966, 999), 'pytest_splunk_addon.helmut.manager.Manager.__init__', 'Manager.__init__', (['self', 'connector'], {}), '(self, connector)\n', (982, 999), False, 'from pytest_splunk_addon.helmut.manager import Manager\n'), ((1008, 1033), 'pytest_splunk_addon.helmut.misc.collection.Collection.__init__', 'Collection.__init__', (['self'], {}), '(self)\n', (1027, 1033), False, 'from pytest_splunk_addon.helmut.misc.collection import Collection\n'), ((1499, 1562), 'pytest_splunk_addon.helmut.misc.manager_utils.create_wrapper_from_connector_mapping', 'create_wrapper_from_connector_mapping', (['cls', 'connector', 'mappings'], {}), '(cls, connector, mappings)\n', (1536, 1562), False, 'from pytest_splunk_addon.helmut.misc.manager_utils import create_wrapper_from_connector_mapping\n')]
import os import subprocess import pytest from unit.applications.lang.java import TestApplicationJava from unit.option import option class TestJavaIsolationRootfs(TestApplicationJava): prerequisites = {'modules': {'java': 'all'}} def setup_method(self, is_su): if not is_su: return os.makedirs(option.temp_dir + '/jars') os.makedirs(option.temp_dir + '/tmp') os.chmod(option.temp_dir + '/tmp', 0o777) try: process = subprocess.Popen( [ "mount", "--bind", option.current_dir + "/build", option.temp_dir + "/jars", ], stderr=subprocess.STDOUT, ) process.communicate() except KeyboardInterrupt: raise except: pytest.fail('Can\'t run mount process.') def teardown_method(self, is_su): if not is_su: return try: process = subprocess.Popen( ["umount", "--lazy", option.temp_dir + "/jars"], stderr=subprocess.STDOUT, ) process.communicate() except KeyboardInterrupt: raise except: pytest.fail('Can\'t run mount process.') def test_java_isolation_rootfs_chroot_war(self, is_su, temp_dir): if not is_su: pytest.skip('require root') isolation = { 'rootfs': temp_dir, } self.load('empty_war', isolation=isolation) assert 'success' in self.conf( '"/"', '/config/applications/empty_war/working_directory', ) assert 'success' in self.conf( '"/jars"', 'applications/empty_war/unit_jars' ) assert 'success' in self.conf( '"/java/empty.war"', 'applications/empty_war/webapp' ) assert self.get()['status'] == 200, 'war'
[ "subprocess.Popen", "os.chmod", "os.makedirs", "pytest.fail", "pytest.skip" ]
[((323, 361), 'os.makedirs', 'os.makedirs', (["(option.temp_dir + '/jars')"], {}), "(option.temp_dir + '/jars')\n", (334, 361), False, 'import os\n'), ((370, 407), 'os.makedirs', 'os.makedirs', (["(option.temp_dir + '/tmp')"], {}), "(option.temp_dir + '/tmp')\n", (381, 407), False, 'import os\n'), ((416, 455), 'os.chmod', 'os.chmod', (["(option.temp_dir + '/tmp')", '(511)'], {}), "(option.temp_dir + '/tmp', 511)\n", (424, 455), False, 'import os\n'), ((494, 620), 'subprocess.Popen', 'subprocess.Popen', (["['mount', '--bind', option.current_dir + '/build', option.temp_dir + '/jars']"], {'stderr': 'subprocess.STDOUT'}), "(['mount', '--bind', option.current_dir + '/build', option.\n temp_dir + '/jars'], stderr=subprocess.STDOUT)\n", (510, 620), False, 'import subprocess\n'), ((1036, 1132), 'subprocess.Popen', 'subprocess.Popen', (["['umount', '--lazy', option.temp_dir + '/jars']"], {'stderr': 'subprocess.STDOUT'}), "(['umount', '--lazy', option.temp_dir + '/jars'], stderr=\n subprocess.STDOUT)\n", (1052, 1132), False, 'import subprocess\n'), ((1438, 1465), 'pytest.skip', 'pytest.skip', (['"""require root"""'], {}), "('require root')\n", (1449, 1465), False, 'import pytest\n'), ((879, 918), 'pytest.fail', 'pytest.fail', (['"""Can\'t run mount process."""'], {}), '("Can\'t run mount process.")\n', (890, 918), False, 'import pytest\n'), ((1292, 1331), 'pytest.fail', 'pytest.fail', (['"""Can\'t run mount process."""'], {}), '("Can\'t run mount process.")\n', (1303, 1331), False, 'import pytest\n')]
# Generated by Django 2.2.3 on 2019-07-30 12:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quotes', '0002_auto_20190722_2143'), ] operations = [ migrations.AddField( model_name='quote', name='no_user_favourites', field=models.PositiveIntegerField(default=0), ), migrations.AddField( model_name='quote', name='no_user_likes', field=models.PositiveIntegerField(default=0), ), migrations.AlterField( model_name='quote', name='date_posted', field=models.DateTimeField(auto_now_add=True), ), ]
[ "django.db.models.DateTimeField", "django.db.models.PositiveIntegerField" ]
[((344, 382), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (371, 382), False, 'from django.db import migrations, models\n'), ((508, 546), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (535, 546), False, 'from django.db import migrations, models\n'), ((672, 711), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (692, 711), False, 'from django.db import migrations, models\n')]
import cgi from docify.lib.formatter import Formatter from docify import Document, components as c __all__ = [ 'DOC_TMPL', 'HTML' ] DOC_TMPL = '''\ <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Docify Document</title> </head> <body> <div id="container"> {} </div> </body> </html> ''' class HTML(Formatter): '''HTML formatter to format document into plain HTML.''' def __init__(self, *args, **kwargs): super(HTML, self).__init__(*args, **kwargs) self.tmpl = DOC_TMPL self.indent = 4 self._spacing = 12 def tag(self, tag, components=[], properties={}): attrs = '' for k in properties: v = properties[k] attrs += ' {}="{}"'.format(k, v.replace('"', '\\"')) if len(components) == 0: return '<{0}{1} />'.format(tag, attrs) return '<{0}{1}>{2}</{0}>'.format( tag, attrs, ''.join([self.f(c) for c in components])) def update_handlers(self): '''Overriding parent method''' super(HTML, self).update_handlers() @self.handles(Document) def handle_doc(self, obj): return self.tmpl.format(('\n' + (' ' * self._spacing)).join( [self.f(c) for c in obj.components])) @self.handles(c.Text) def handle_text(self, obj): return cgi.escape(obj.value) @self.handles(c.Nbsp) def handle_nbsp(self, obj): return '&nbsp;' @self.handles(c.Break) def handle_br(self, obj): return '<br />' @self.handles(c.HorizontalRule) def handle_hr(self, obj): return '<hr />' @self.handles(c.Anchor) def handle_a(self, obj): return self.tag('a', [obj.value], obj.props) @self.handles(c.Image) def handle_img(self, obj): return self.tag('img', [], obj.props) @self.handles(c.Header1) def handle_h1(self, obj): return self.tag('h1', obj.components, obj.props) @self.handles(c.Header2) def handle_h2(self, obj): return self.tag('h2', obj.components, obj.props) @self.handles(c.Header3) def handle_h3(self, obj): return self.tag('h3', obj.components, obj.props) @self.handles(c.Header4) def handle_h4(self, obj): return self.tag('h4', obj.components, obj.props) @self.handles(c.Header5) def handle_h5(self, obj): return self.tag('h5', obj.components, obj.props) @self.handles(c.Header6) def handle_h6(self, obj): return self.tag('h6', obj.components, obj.props) @self.handles(c.Footer) def handle_footer(self, obj): return self.tag('footer', obj.components, obj.props) @self.handles(c.Small) def handle_small(self, obj): return self.tag('small', obj.components, obj.props) @self.handles(c.Cite) def handle_cite(self, obj): return self.tag('cite', obj.components, obj.props) @self.handles(c.Italic) def handle_i(self, obj): return self.tag('i', obj.components, obj.props) @self.handles(c.Bold) def handle_b(self, obj): return self.tag('b', obj.components, obj.props) @self.handles(c.Blockquote) def handle_blockquote(self, obj): return self.tag('blockquote', obj.components, obj.props) @self.handles(c.Pre) def handle_pre(self, obj): return self.tag('pre', obj.components, obj.props) @self.handles(c.Code) def handle_code(self, obj): return self.tag('code', obj.components, obj.props) @self.handles(c.Del) def handle_del(self, obj): return self.tag('del', obj.components, obj.props) @self.handles(c.Section) def handle_section(self, obj): return self.tag('section', obj.components, obj.props) @self.handles(c.Paragraph) def handle_p(self, obj): return self.tag('p', obj.components, obj.props) @self.handles(c.Span) def handle_span(self, obj): return self.tag('span', obj.components, obj.props) @self.handles(c.OrderedList) def handle_ol(self, obj): return self.tag('ol', obj.components, obj.props) @self.handles(c.UnorderedList) def handle_ul(self, obj): return self.tag('ul', obj.components, obj.props) @self.handles(c.ListItem) def handle_li(self, obj): return self.tag('li', obj.components, obj.props) @self.handles(c.Table) def handle_table(self, obj): return self.tag('table', obj.components, obj.props) @self.handles(c.TableHeader) def handle_th(self, obj): return self.tag('th', obj.components, obj.props) @self.handles(c.TableRow) def handle_tr(self, obj): return self.tag('tr', obj.components, obj.props) @self.handles(c.TableData) def handle_td(self, obj): return self.tag('td', obj.components, obj.props)
[ "cgi.escape" ]
[((1515, 1536), 'cgi.escape', 'cgi.escape', (['obj.value'], {}), '(obj.value)\n', (1525, 1536), False, 'import cgi\n')]
#!/usr/bin/python """ Custom Smart Substation Communication Topology ---------------------------------- Model built using Sayon (a MIT License Software). ---------------------------------- W A R N I N G: ---------------------------------- --> Please make sure you know Mininet Python API very well before editing this file. --> Read Mininet Python API Documentation Here: http://mininet.org/walkthrough/#custom-topologies --> This program may not work properly if this file gets messed up. --> To troubleshoot, ask questions on StackOverflow with tags "sayon" and/or "mininet", --> 24x7 Email Support: <<EMAIL>> or, <<EMAIL>> """ from mininet.topo import Topo from mininet.net import Mininet from mininet.util import dumpNodeConnections from mininet.log import setLogLevel from mininet.link import TCLink class Topo(Topo): def __init__(self): #initializing topology Topo.__init__(self, link=TCLink) #Add Switches s1 = self.addSwitch('s1') #Add Hosts h1 = self.addHost('h1') h2 = self.addHost('h2') h3 = self.addHost('h3') #Adding Links and Their properties self.addLink(s1,h1,bw=14, delay='0ms', loss= 0, use_htb=True) self.addLink(s1,h2,bw=20, delay='5ms', loss= 0, use_htb=True) self.addLink(s1,h3,bw=20, delay='1ms', loss= 0, use_htb=True) self.addLink(h2,h3,bw=48, delay='1ms', loss= 0, use_htb=True) topos = { 'topo': ( lambda: Topo() )}
[ "mininet.topo.Topo.__init__", "mininet.topo.Topo" ]
[((879, 911), 'mininet.topo.Topo.__init__', 'Topo.__init__', (['self'], {'link': 'TCLink'}), '(self, link=TCLink)\n', (892, 911), False, 'from mininet.topo import Topo\n'), ((1375, 1381), 'mininet.topo.Topo', 'Topo', ([], {}), '()\n', (1379, 1381), False, 'from mininet.topo import Topo\n')]
from datetime import datetime as dt from enum import Enum from math import ceil ISO8601_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ' class LiftStatus(Enum): STOPPED = 0 IN_ACTION = 1 class ActorStatus(Enum): IDLE = 0 EXPECT = 1 IN_LIFT = 2 class Lift(): def __init__(self, id, speed, max_weight, floor_height=1.0, *args, **kwargs): self._id = id self._speed = speed self._max_weight = max_weight self._position = 0.01 self._passengers = [] self._status = LiftStatus.STOPPED self._floor_height = floor_height super().__init__(*args, **kwargs) @property def id(self): return self._id @property def speed(self): return self._speed @property def max_weight(self): return self._max_weight @property def position(self): return self._position @position.setter def position(self, pos): if pos >= 0.0: self._position = pos @property def passengers(self): return self._passengers @passengers.setter def passengers(self, pas): if sum([x.weight for x in pas]) <= self._max_weight: self._passengers = pas @property def status(self): return self._status @property def floor(self): return ceil(self.position / self._floor_height) def near_act_floor(self, actors): """Ближайший этаж на котором нужно выполнить какое-то действие""" drop, take = self._near_drop_floor(), self._near_take_floor(actors) if None not in (drop, take): return drop if abs(self.floor - drop) < abs(self.floor - take) else take return drop or take def drop_off(self): """Высаживаем пассажиров, которые должны выйти на этом этаже""" drop_off = self._out_passengers() for p in drop_off: self._passengers.remove(p) p.leave_lift() return drop_off def take_actors(self, actors): """Забирает actor'ов c текущего этажа, если им нужен лифт""" new_passengers = [x for x in actors if x.floor == self.floor and x.status == ActorStatus.EXPECT] # теперь нужно проверить ограничение с грузоподъемностью лифта new_passengers.sort(key=lambda x: x.weight) possible_weight = self._max_weight - sum([x.weight for x in self._passengers]) extra_inx = weight = 0 for p in new_passengers: extra_inx += 1 if possible_weight > weight + p.weight: break weight += p.weight new_passengers = new_passengers[0:extra_inx] for x in new_passengers: x.enter_lift() self._passengers += new_passengers return new_passengers def stop(self): self._status = LiftStatus.STOPPED def move_to_act_floor(self, actors): """Перемещает лифт на один шаг к ближайшему этажу с посадкой/высадкой""" near = self.near_act_floor(actors) if near is not None: if near < self.floor: self.move_down() else: self.move_up() def move_up(self): self._status = LiftStatus.IN_ACTION self._position += self._speed def move_down(self): self._status = LiftStatus.IN_ACTION self._position -= self._speed if self._position < 0: self._position = 0 def is_empty(self): return not self._passengers def _out_passengers(self): """Пассажиры, выходящие на текущем этаже""" return [x for x in self._passengers if x.need_floor == self.floor] def _near_drop_floor(self): """Ближайший этаж, на котором нужно высадить пассажира""" cur_floor = self.floor dist = [(abs(cur_floor - x.need_floor), x.need_floor) for x in self._passengers] return min(dist, key=lambda x: x[0])[1] if dist else None def _near_take_floor(self, actors): """Ближайший этаж, на котором следует забрать пассажира, при условии что его вес не приведет к перегрузке лифта """ cur_floor = self.floor possible_weight = self._max_weight - sum([x.weight for x in self._passengers]) dist = [(abs(cur_floor - x.floor), x.floor) for x in actors if x.weight <= possible_weight and x.status == ActorStatus.EXPECT] return min(dist, key=lambda x: x[0])[1] if dist else None class Actor: def __init__(self, uid, weight): self._uid = uid self._weight = weight self._floor = 1 self._need_floor = None self._status = ActorStatus.IDLE self._timestamp = dt.utcnow() @property def uid(self): return self._uid @property def weight(self): return self._weight @property def floor(self): return self._floor @floor.setter def floor(self, value): if value >= 1: self._floor = value @property def need_floor(self): return self._need_floor @property def status(self): return self._status @property def timestamp(self): return self._timestamp def idle(self): """Переход в режим бездействия""" if self._status == ActorStatus.EXPECT: self._status = ActorStatus.IDLE self._need_floor = None def wait_lift(self, floor): """Ожидать лифт на текущем этаже""" if self._status != ActorStatus.IN_LIFT and floor != self._floor: self._need_floor = floor self._status = ActorStatus.EXPECT def leave_lift(self): """Покидает лифт и выходит на этаж""" if self._status == ActorStatus.IN_LIFT: self._status = ActorStatus.IDLE self._need_floor = None return True return False def enter_lift(self): """Заходит в лифт, если это возможно""" if self._status == ActorStatus.EXPECT: self._status = ActorStatus.IN_LIFT return True return False
[ "datetime.datetime.utcnow", "math.ceil" ]
[((1336, 1376), 'math.ceil', 'ceil', (['(self.position / self._floor_height)'], {}), '(self.position / self._floor_height)\n', (1340, 1376), False, 'from math import ceil\n'), ((4717, 4728), 'datetime.datetime.utcnow', 'dt.utcnow', ([], {}), '()\n', (4726, 4728), True, 'from datetime import datetime as dt\n')]
""" Mock Library for RPi.GPIO """ import time import logging import os import yaml logger = logging.getLogger(__name__) log_level = os.getenv('LOG_LEVEL') if log_level is not None: if log_level == "Info": logger.setLevel(logging.INFO) if log_level == "Debug": logger.setLevel(logging.DEBUG) if log_level == "Warning": logger.setLevel(logging.WARNING) if log_level == "Error": logger.setLevel(logging.ERROR) if log_level == "Critical": logger.setLevel(logging.CRITICAL) else: logger.setLevel(logging.ERROR) stream_formatter = logging.Formatter('%(asctime)s:%(levelname)s: %(message)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(stream_formatter) logger.addHandler(stream_handler) BCM = 11 BOARD = 10 BOTH = 33 FALLING = 32 HARD_PWM = 43 HIGH = 1 I2C = 42 IN = 1 LOW = 0 OUT = 0 PUD_DOWN = 21 PUD_OFF = 20 PUD_UP = 22 RISING = 31 RPI_INFO = {'MANUFACTURER': 'Sony', 'P1_REVISION': 3, 'PROCESSOR': 'BCM2837', 'RAM': '1G', 'REVISION': 'a020d3', 'TYPE': 'Pi 3 Model B+'} RPI_REVISION = 3 SERIAL = 40 SPI = 41 UNKNOWN = -1 VERSION = '0.7.0' _mode = 0 channel_config = {} #flags setModeDone = False class Channel: def __init__(self,channel, direction, initial=0,pull_up_down=PUD_OFF): self.chanel = channel self.direction = direction self.initial = initial self.pull_up_down = pull_up_down #GPIO LIBRARY Functions def setmode(mode): """ Set up numbering mode to use for channels. BOARD - Use Raspberry Pi board numbers BCM - Use Broadcom GPIO 00..nn numbers """ # GPIO = GPIO() time.sleep(1) if(mode == BCM): setModeDone = True _mode = mode elif (mode == BOARD): setModeDone = True else: setModeDone = False def getmode(): """ Get numbering mode used for channel numbers. Returns BOARD, BCM or None """ return _mode def setwarnings(flag): """ Enable or disable warning messages """ logger.info("Set Warings as {}".format(flag)) def setup(channel, direction, initial=0,pull_up_down=PUD_OFF): """ Set up a GPIO channel or list of channels with a direction and (optional) pull/up down control channel - either board pin number or BCM number depending on which mode is set. direction - IN or OUT [pull_up_down] - PUD_OFF (default), PUD_UP or PUD_DOWN [initial] - Initial value for an output channel """ logger.info("setup channel : {} as {} with intial :{} and pull_up_dowm {}".format(channel,direction,initial,pull_up_down)) global channel_config channel_config[channel] = Channel(channel, direction, initial, pull_up_down) def output(channel, value): """ Output to a GPIO channel or list of channels channel - either board pin number or BCM number depending on which mode is set. value - 0/1 or False/True or LOW/HIGH """ logger.info("output channel : {} with value : {}".format(channel, value)) def input(channel): """ Input from a GPIO channel. Returns HIGH=1=True or LOW=0=False channel - either board pin number or BCM number depending on which mode is set. """ logger.info("reading from chanel {}".format(channel)) def wait_for_edge(channel,edge,bouncetime,timeout): """ Wait for an edge. Returns the channel number or None on timeout. channel - either board pin number or BCM number depending on which mode is set. edge - RISING, FALLING or BOTH [bouncetime] - time allowed between calls to allow for switchbounce [timeout] - timeout in ms """ logger.info("waiting for edge : {} on channel : {} with bounce time : {} and Timeout :{}".format(edge,channel,bouncetime,timeout)) def add_event_detect(channel,edge,callback,bouncetime): """ Enable edge detection events for a particular GPIO channel. channel - either board pin number or BCM number depending on which mode is set. edge - RISING, FALLING or BOTH [callback] - A callback function for the event (optional) [bouncetime] - Switch bounce timeout in ms for callback """ logger.info("Event detect added for edge : {} on channel : {} with bouce time : {} and callback {}".format(edge,channel,bouncetime,callback)) def event_detected(channel): """ Returns True if an edge has occurred on a given GPIO. You need to enable edge detection using add_event_detect() first. channel - either board pin number or BCM number depending on which mode is set. """ logger.info("Waiting for even detection on channel :{}".format(channel)) def add_event_callback(channel,callback): """ Add a callback for an event already defined using add_event_detect() channel - either board pin number or BCM number depending on which mode is set. callback - a callback function """ logger.info("Event Calback : {} added for channel : {}".format(callback,channel)) def remove_event_detect(channel): """ Remove edge detection for a particular GPIO channel channel - either board pin number or BCM number depending on which mode is set. """ logger.info("Event Detect Removed for channel : {}".format(channel)) def gpio_function(channel): """ Return the current GPIO function (IN, OUT, PWM, SERIAL, I2C, SPI) channel - either board pin number or BCM number depending on which mode is set. """ logger.info("GPIO function of Channel : {} is {}".format(channel,channel_config[channel].direction)) class PWM: # initialise PWM channel def __init__(self, channel, frequency): """ x.__init__(...) initializes x; see help(type(x)) for signature """ self.chanel = channel self.frequency = frequency self.dutycycle = 0 global channel_config channel_config[channel] = Channel(channel,PWM,) logger.info("Initialized PWM for Channel : {} at frequency : {}".format(channel,frequency)) # where dc is the duty cycle (0.0 <= dc <= 100.0) def start(self, dutycycle): """ Start software PWM dutycycle - the duty cycle (0.0 to 100.0) """ self.dutycycle = dutycycle logger.info("start pwm on channel : {} with Duty cycle : {}".format(self.chanel,dutycycle)) # where freq is the new frequency in Hz def ChangeFrequency(self, frequency): """ Change the frequency frequency - frequency in Hz (freq > 1.0) """ logger.info("Freqency Changed for channel : {} from : {} -> to : {}".format(self.chanel,self.frequency,frequency)) self.frequency = frequency # where 0.0 <= dc <= 100.0 def ChangeDutyCycle(self, dutycycle): """ Change the duty cycle dutycycle - between 0.0 and 100.0 """ self.dutycycle = dutycycle logger.info("Dutycycle Changed for channel : {} from : {} -> to : {}".format(self.chanel,self.dutycycle,dutycycle)) # stop PWM generation def stop(self): logger.info("Stop pwm on channel : {} with Duty cycle : {}".format(self.chanel,self.dutycycle)) def cleanup(channel=None): """ Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection [channel] - individual channel or list/tuple of channels to clean up. Default - clean every channel that has been used. """ if channel is not None: logger.info("Cleaning Up Channel : {}".format(channel)) else: logger.info("Cleaning Up all channels")
[ "logging.StreamHandler", "time.sleep", "logging.Formatter", "os.getenv", "logging.getLogger" ]
[((94, 121), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (111, 121), False, 'import logging\n'), ((135, 157), 'os.getenv', 'os.getenv', (['"""LOG_LEVEL"""'], {}), "('LOG_LEVEL')\n", (144, 157), False, 'import os\n'), ((594, 653), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s:%(levelname)s: %(message)s"""'], {}), "('%(asctime)s:%(levelname)s: %(message)s')\n", (611, 653), False, 'import logging\n'), ((671, 694), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (692, 694), False, 'import logging\n'), ((1640, 1653), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1650, 1653), False, 'import time\n')]
# -*- coding: utf-8 -*- # This file is a part of DDT (https://github.com/datadriventests/ddt) # Copyright 2012-2015 <NAME> and DDT contributors # For the exact contribution history, see the git revision log. # DDT is licensed under the MIT License, included in # https://github.com/datadriventests/ddt/blob/master/LICENSE.md import inspect import json import os import re import codecs from functools import wraps try: import yaml except ImportError: # pragma: no cover _have_yaml = False else: _have_yaml = True __version__ = '1.3.1' # These attributes will not conflict with any real python attribute # They are added to the decorated test method and processed later # by the `ddt` class decorator. DATA_ATTR = '%values' # store the data the test must run with FILE_ATTR = '%file_path' # store the path to JSON file YAML_LOADER_ATTR = '%yaml_loader' # store custom yaml loader for serialization UNPACK_ATTR = '%unpack' # remember that we have to unpack values index_len = 5 # default max length of case index try: trivial_types = (type(None), bool, int, float, basestring) except NameError: trivial_types = (type(None), bool, int, float, str) def is_trivial(value): if isinstance(value, trivial_types): return True elif isinstance(value, (list, tuple)): return all(map(is_trivial, value)) return False def unpack(func): """ Method decorator to add unpack feature. """ setattr(func, UNPACK_ATTR, True) return func def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ global index_len index_len = len(str(len(values))) return idata(values) def idata(iterable): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, DATA_ATTR, iterable) return func return wrapper def file_data(value, yaml_loader=None): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. ``value`` should be a path relative to the directory of the file containing the decorated ``unittest.TestCase``. The file should contain JSON encoded data, that can either be a list or a dict. In case of a list, each value in the list will correspond to one test case, and the value will be concatenated to the test method name. In case of a dict, keys will be used as suffixes to the name of the test case, and values will be fed as test data. ``yaml_loader`` can be used to customize yaml deserialization. The default is ``None``, which results in using the ``yaml.safe_load`` method. """ def wrapper(func): setattr(func, FILE_ATTR, value) if yaml_loader: setattr(func, YAML_LOADER_ATTR, yaml_loader) return func return wrapper def mk_test_name(name, value, index=0): """ Generate a new name for a test case. It will take the original test name and append an ordinal index and a string representation of the value, and convert the result into a valid python identifier by replacing extraneous characters with ``_``. We avoid doing str(value) if dealing with non-trivial values. The problem is possible different names with different runs, e.g. different order of dictionary keys (see PYTHONHASHSEED) or dealing with mock objects. Trivial scalar values are passed as is. A "trivial" value is a plain scalar, or a tuple or list consisting only of trivial values. """ # Add zeros before index to keep order index = "{0:0{1}}".format(index + 1, index_len) if not is_trivial(value): return "{0}_{1}".format(name, index) try: value = str(value) except UnicodeEncodeError: # fallback for python2 value = value.encode('ascii', 'backslashreplace') test_name = "{0}_{1}_{2}".format(name, index, value) return re.sub(r'\W|^(?=\d)', '_', test_name) def feed_data(func, new_name, test_data_docstring, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) wrapper.__name__ = new_name wrapper.__wrapped__ = func # set docstring if exists if test_data_docstring is not None: wrapper.__doc__ = test_data_docstring else: # Try to call format on the docstring if func.__doc__: try: wrapper.__doc__ = func.__doc__.format(*args, **kwargs) except (IndexError, KeyError): # Maybe the user has added some of the formating strings # unintentionally in the docstring. Do not raise an exception # as it could be that user is not aware of the # formating feature. pass return wrapper def add_test(cls, test_name, test_docstring, func, *args, **kwargs): """ Add a test case to this class. The test will be based on an existing function but will give it a new name. """ setattr(cls, test_name, feed_data(func, test_name, test_docstring, *args, **kwargs)) def process_file_data(cls, name, func, file_attr): """ Process the parameter in the `file_data` decorator. """ cls_path = os.path.abspath(inspect.getsourcefile(cls)) data_file_path = os.path.join(os.path.dirname(cls_path), file_attr) def create_error_func(message): # pylint: disable-msg=W0613 def func(*args): raise ValueError(message % file_attr) return func # If file does not exist, provide an error function instead if not os.path.exists(data_file_path): test_name = mk_test_name(name, "error") test_docstring = """Error!""" add_test(cls, test_name, test_docstring, create_error_func("%s does not exist"), None) return _is_yaml_file = data_file_path.endswith((".yml", ".yaml")) # Don't have YAML but want to use YAML file. if _is_yaml_file and not _have_yaml: test_name = mk_test_name(name, "error") test_docstring = """Error!""" add_test( cls, test_name, test_docstring, create_error_func("%s is a YAML file, please install PyYAML"), None ) return with codecs.open(data_file_path, 'r', 'utf-8') as f: # Load the data from YAML or JSON if _is_yaml_file: if hasattr(func, YAML_LOADER_ATTR): yaml_loader = getattr(func, YAML_LOADER_ATTR) data = yaml.load(f, Loader=yaml_loader) else: data = yaml.safe_load(f) else: data = json.load(f) _add_tests_from_data(cls, name, func, data) def _add_tests_from_data(cls, name, func, data): """ Add tests from data loaded from the data file into the class """ for i, elem in enumerate(data): if isinstance(data, dict): key, value = elem, data[elem] test_name = mk_test_name(name, key, i) elif isinstance(data, list): value = elem test_name = mk_test_name(name, value, i) if isinstance(value, dict): add_test(cls, test_name, test_name, func, **value) else: add_test(cls, test_name, test_name, func, value) def _is_primitive(obj): """Finds out if the obj is a "primitive". It is somewhat hacky but it works. """ return not hasattr(obj, '__dict__') def _get_test_data_docstring(func, value): """Returns a docstring based on the following resolution strategy: 1. Passed value is not a "primitive" and has a docstring, then use it. 2. In all other cases return None, i.e the test name is used. """ if not _is_primitive(value) and value.__doc__: return value.__doc__ else: return None def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. The names of the test methods follow the pattern ``original_test_name_{ordinal}_{data}``. ``ordinal`` is the position of the data argument, starting with 1. For data we use a string representation of the data value converted into a valid python identifier. If ``data.__name__`` exists, we use that instead. For each method decorated with ``@file_data('test_data.json')``, the decorator will try to load the test_data.json file located relative to the python file containing the method that is decorated. It will, for each ``test_name`` key create as many methods in the list of values from the ``data`` key. """ for name, func in list(cls.__dict__.items()): if hasattr(func, DATA_ATTR): for i, v in enumerate(getattr(func, DATA_ATTR)): test_name = mk_test_name(name, getattr(v, "__name__", v), i) test_data_docstring = _get_test_data_docstring(func, v) if hasattr(func, UNPACK_ATTR): if isinstance(v, tuple) or isinstance(v, list): add_test( cls, test_name, test_data_docstring, func, *v ) else: # unpack dictionary add_test( cls, test_name, test_data_docstring, func, **v ) else: add_test(cls, test_name, test_data_docstring, func, v) delattr(cls, name) elif hasattr(func, FILE_ATTR): file_attr = getattr(func, FILE_ATTR) process_file_data(cls, name, func, file_attr) delattr(cls, name) return cls
[ "yaml.load", "json.load", "codecs.open", "os.path.dirname", "os.path.exists", "yaml.safe_load", "functools.wraps", "re.sub", "inspect.getsourcefile" ]
[((4151, 4189), 're.sub', 're.sub', (['"""\\\\W|^(?=\\\\d)"""', '"""_"""', 'test_name'], {}), "('\\\\W|^(?=\\\\d)', '_', test_name)\n", (4157, 4189), False, 'import re\n'), ((4355, 4366), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (4360, 4366), False, 'from functools import wraps\n'), ((5580, 5606), 'inspect.getsourcefile', 'inspect.getsourcefile', (['cls'], {}), '(cls)\n', (5601, 5606), False, 'import inspect\n'), ((5642, 5667), 'os.path.dirname', 'os.path.dirname', (['cls_path'], {}), '(cls_path)\n', (5657, 5667), False, 'import os\n'), ((5917, 5947), 'os.path.exists', 'os.path.exists', (['data_file_path'], {}), '(data_file_path)\n', (5931, 5947), False, 'import os\n'), ((6616, 6657), 'codecs.open', 'codecs.open', (['data_file_path', '"""r"""', '"""utf-8"""'], {}), "(data_file_path, 'r', 'utf-8')\n", (6627, 6657), False, 'import codecs\n'), ((6990, 7002), 'json.load', 'json.load', (['f'], {}), '(f)\n', (6999, 7002), False, 'import json\n'), ((6865, 6897), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml_loader'}), '(f, Loader=yaml_loader)\n', (6874, 6897), False, 'import yaml\n'), ((6939, 6956), 'yaml.safe_load', 'yaml.safe_load', (['f'], {}), '(f)\n', (6953, 6956), False, 'import yaml\n')]
import logging import os import cv2 import numpy as np import inferencing_pb2 import media_pb2 import extension_pb2 import extension_pb2_grpc # import timeit as t from enum import Enum from shared_memory import SharedMemoryManager from exception_handler import PrintGetExceptionDetails from model_wrapper import YoloV4Model # Get debug flag from env variable (Returns None if not set) # Set this environment variables in the IoTEdge Deployment manifest to activate debugging. DEBUG = os.getenv('DEBUG') class TransferType(Enum): BYTES = 1 # Embedded Content REFERENCE = 2 # Shared Memory HANDLE = 3 # Reserved class State: def __init__(self, mediaStreamDescriptor): try: # media descriptor holding input data format self._mediaStreamDescriptor = mediaStreamDescriptor # Get how data will be transferred if self._mediaStreamDescriptor.WhichOneof("data_transfer_properties") is None: self._contentTransferType = TransferType.BYTES elif self._mediaStreamDescriptor.HasField("shared_memory_buffer_transfer_properties"): self._contentTransferType = TransferType.REFERENCE elif self._mediaStreamDescriptor.HasField("shared_memory_segments_transfer_properties"): self._contentTransferType = TransferType.HANDLE # Setup if shared mem used if self._contentTransferType == TransferType.REFERENCE: # Create shared memory accessor specific to the client self._sharedMemoryManager = SharedMemoryManager( name=self._mediaStreamDescriptor.shared_memory_buffer_transfer_properties.handle_name, size=self._mediaStreamDescriptor.shared_memory_buffer_transfer_properties.length_bytes) else: self._sharedMemoryManager = None except: PrintGetExceptionDetails() raise class InferenceEngine(extension_pb2_grpc.MediaGraphExtensionServicer): def __init__(self): # create ONNX model wrapper # Thread safe shared resource among all clients self._YoloV4 = YoloV4Model() # Debug method for dumping received images with analysis results def CreateDebugOutput(self, requestSeqNum, cvImage, boxes, scores, indices, confidenceThreshold=0.1): try: marked = False for idx in indices: confidenceScore = scores[tuple(idx)].tolist() if confidenceScore >= confidenceThreshold: objectLabel = self._tYoloV3._labelList[idx[1].tolist()] idxTuple = (idx[0], idx[2]) ymin, xmin, ymax, xmax = boxes[idxTuple].tolist() cv2.rectangle(cvImage, (int(xmin), int(ymin)), (int(xmax), int(ymax)), (255, 0, 0), 2) cv2.putText(cvImage, objectLabel + " - " + str(confidenceScore), (int(xmin), int(ymin - 7)), cv2.FONT_HERSHEY_COMPLEX, 0.3, (255, 0, 0), 1) marked = True # Set output file name if marked: outputFileName = os.path.join(DEBUG_OUTPUT_FOLDER, str(requestSeqNum) + '_marked.jpg') else: outputFileName = os.path.join(DEBUG_OUTPUT_FOLDER, str(requestSeqNum) + '.jpg') # output with bounding boxes cv2.imwrite(outputFileName, cvImage) except: PrintGetExceptionDetails() raise def GetMediaStreamMessageResponse(self, bboxes, originalImageSize): try: msg = extension_pb2.MediaStreamMessage() ih, iw = originalImageSize for i, bbox in enumerate(bboxes): confidenceScore = bbox[4].tolist() objectLabel = self._YoloV4._labelList[int(bbox[5])] xmin, ymin, xmax, ymax = np.array(bbox[:4], dtype=np.int32) inference = msg.media_sample.inferences.add() inference.type = inferencing_pb2.Inference.InferenceType.ENTITY inference.entity.CopyFrom( inferencing_pb2.Entity( tag = inferencing_pb2.Tag( value = objectLabel, confidence = confidenceScore ), box = inferencing_pb2.Rectangle( l = xmin / iw, t = ymin / ih, w = (xmax - xmin) / iw, h = (ymax - ymin) / ih, ) ) ) return msg except: PrintGetExceptionDetails() raise def GetCvImageFromRawBytes(self, clientState, mediaSample): try: # Get reference to raw bytes if clientState._contentTransferType == TransferType.BYTES: rawBytes = memoryview(mediaSample.content_bytes.bytes).toreadonly() elif clientState._contentTransferType == TransferType.REFERENCE: # Data sent over shared memory buffer addressOffset = mediaSample.content_reference.address_offset lengthBytes = mediaSample.content_reference.length_bytes # Get memory reference to (in readonly mode) data sent over shared memory rawBytes = clientState._sharedMemoryManager.ReadBytes(addressOffset, lengthBytes) # Get encoding details of the media sent by client encoding = clientState._mediaStreamDescriptor.media_descriptor.video_frame_sample_format.encoding # Handle JPG, PNG, BMP content cvImage = None if encoding == clientState._mediaStreamDescriptor.media_descriptor.video_frame_sample_format.Encoding.JPG or \ encoding == clientState._mediaStreamDescriptor.media_descriptor.video_frame_sample_format.Encoding.PNG or \ encoding == clientState._mediaStreamDescriptor.media_descriptor.video_frame_sample_format.Encoding.BMP: # np.frombuffer is zero copy command cvImage = cv2.imdecode(np.frombuffer(rawBytes, dtype=np.uint8), -1) # Handle RAW content (Just place holder for the user to handle each variation...) elif encoding == clientState._mediaStreamDescriptor.media_descriptor.video_frame_sample_format.Encoding.RAW: pixelFormat = clientState._mediaStreamDescriptor.media_descriptor.video_frame_sample_format.pixel_format if pixelFormat == media_pb2.VideoFrameSampleFormat.PixelFormat.RGBA: cvImage = cv2.cvtColor(np.frombuffer(rawBytes, dtype=np.uint8), cv2.COLOR_RGBA2RGB) elif pixelFormat == media_pb2.VideoFrameSampleFormat.PixelFormat.YUV420P: cvImage = None return cvImage except: PrintGetExceptionDetails() raise def ProcessMediaStream(self, requestIterator, context): # Below logic can be extended into multi-process (per CPU cores, i.e. in case using CPU inferencing) # For simplicity below, we use single process to handle gRPC clients # Auto increment counter. Increases per client requests responseSeqNum = 1 # First message from the client is (must be) MediaStreamDescriptor mediaStreamMessageRequest = next(requestIterator) # Extract message IDs requestSeqNum = mediaStreamMessageRequest.sequence_number requestAckSeqNum = mediaStreamMessageRequest.ack_sequence_number # State object per client clientState = State(mediaStreamMessageRequest.media_stream_descriptor) if DEBUG is not None: logging.info('[Received] SeqNum: {0:07d} | AckNum: {1}\nMediaStreamDescriptor:\n{2}'.format(requestSeqNum, requestAckSeqNum, clientState._mediaStreamDescriptor)) # First message response ... mediaStreamMessage = extension_pb2.MediaStreamMessage( sequence_number = responseSeqNum, ack_sequence_number = requestSeqNum, media_stream_descriptor = extension_pb2.MediaStreamDescriptor( media_descriptor = media_pb2.MediaDescriptor( timescale = clientState._mediaStreamDescriptor.media_descriptor.timescale ) ) ) yield mediaStreamMessage # Process rest of the MediaStream messagge sequence for mediaStreamMessageRequest in requestIterator: try: # Increment response counter, will be sent to client responseSeqNum += 1 # Read request id, sent by client requestSeqNum = mediaStreamMessageRequest.sequence_number if DEBUG is not None: logging.info('[Received] SeqNum: {0:07d}'.format(requestSeqNum)) # Get media content bytes. (bytes sent over shared memory buffer, segment or inline to message) cvImage = self.GetCvImageFromRawBytes(clientState, mediaStreamMessageRequest.media_sample) if cvImage is None: logging.info('Cant decode received bytes.') continue # start = t.default_timer() # run inference boxes, originalImageSize = self._YoloV4.Score(cvImage) # end = t.default_timer() # infTime = round((end - start) * 1000, 5) # logging.info('inf time: {0}'.format(infTime)) # if DEBUG is not None: # self.CreateDebugOutput(requestSeqNum, cvImage, boxes, scores, indices) # Check client connection state if context.is_active(): # return inference result as MediaStreamMessage mediaStreamMessage = self.GetMediaStreamMessageResponse(boxes, originalImageSize) mediaStreamMessage.sequence_number = responseSeqNum mediaStreamMessage.ack_sequence_number = requestSeqNum mediaStreamMessage.media_sample.timestamp = mediaStreamMessageRequest.media_sample.timestamp # yield response yield mediaStreamMessage else: break except: PrintGetExceptionDetails()
[ "cv2.imwrite", "numpy.frombuffer", "shared_memory.SharedMemoryManager", "extension_pb2.MediaStreamMessage", "media_pb2.MediaDescriptor", "model_wrapper.YoloV4Model", "logging.info", "inferencing_pb2.Tag", "numpy.array", "inferencing_pb2.Rectangle", "os.getenv", "exception_handler.PrintGetExceptionDetails" ]
[((489, 507), 'os.getenv', 'os.getenv', (['"""DEBUG"""'], {}), "('DEBUG')\n", (498, 507), False, 'import os\n'), ((2192, 2205), 'model_wrapper.YoloV4Model', 'YoloV4Model', ([], {}), '()\n', (2203, 2205), False, 'from model_wrapper import YoloV4Model\n'), ((3403, 3439), 'cv2.imwrite', 'cv2.imwrite', (['outputFileName', 'cvImage'], {}), '(outputFileName, cvImage)\n', (3414, 3439), False, 'import cv2\n'), ((3617, 3651), 'extension_pb2.MediaStreamMessage', 'extension_pb2.MediaStreamMessage', ([], {}), '()\n', (3649, 3651), False, 'import extension_pb2\n'), ((1604, 1813), 'shared_memory.SharedMemoryManager', 'SharedMemoryManager', ([], {'name': 'self._mediaStreamDescriptor.shared_memory_buffer_transfer_properties.handle_name', 'size': 'self._mediaStreamDescriptor.shared_memory_buffer_transfer_properties.length_bytes'}), '(name=self._mediaStreamDescriptor.\n shared_memory_buffer_transfer_properties.handle_name, size=self.\n _mediaStreamDescriptor.shared_memory_buffer_transfer_properties.\n length_bytes)\n', (1623, 1813), False, 'from shared_memory import SharedMemoryManager\n'), ((1936, 1962), 'exception_handler.PrintGetExceptionDetails', 'PrintGetExceptionDetails', ([], {}), '()\n', (1960, 1962), False, 'from exception_handler import PrintGetExceptionDetails\n'), ((3468, 3494), 'exception_handler.PrintGetExceptionDetails', 'PrintGetExceptionDetails', ([], {}), '()\n', (3492, 3494), False, 'from exception_handler import PrintGetExceptionDetails\n'), ((3898, 3932), 'numpy.array', 'np.array', (['bbox[:4]'], {'dtype': 'np.int32'}), '(bbox[:4], dtype=np.int32)\n', (3906, 3932), True, 'import numpy as np\n'), ((4980, 5006), 'exception_handler.PrintGetExceptionDetails', 'PrintGetExceptionDetails', ([], {}), '()\n', (5004, 5006), False, 'from exception_handler import PrintGetExceptionDetails\n'), ((7228, 7254), 'exception_handler.PrintGetExceptionDetails', 'PrintGetExceptionDetails', ([], {}), '()\n', (7252, 7254), False, 'from exception_handler import PrintGetExceptionDetails\n'), ((6475, 6514), 'numpy.frombuffer', 'np.frombuffer', (['rawBytes'], {'dtype': 'np.uint8'}), '(rawBytes, dtype=np.uint8)\n', (6488, 6514), True, 'import numpy as np\n'), ((9722, 9765), 'logging.info', 'logging.info', (['"""Cant decode received bytes."""'], {}), "('Cant decode received bytes.')\n", (9734, 9765), False, 'import logging\n'), ((10929, 10955), 'exception_handler.PrintGetExceptionDetails', 'PrintGetExceptionDetails', ([], {}), '()\n', (10953, 10955), False, 'from exception_handler import PrintGetExceptionDetails\n'), ((8647, 8750), 'media_pb2.MediaDescriptor', 'media_pb2.MediaDescriptor', ([], {'timescale': 'clientState._mediaStreamDescriptor.media_descriptor.timescale'}), '(timescale=clientState._mediaStreamDescriptor.\n media_descriptor.timescale)\n', (8672, 8750), False, 'import media_pb2\n'), ((4198, 4264), 'inferencing_pb2.Tag', 'inferencing_pb2.Tag', ([], {'value': 'objectLabel', 'confidence': 'confidenceScore'}), '(value=objectLabel, confidence=confidenceScore)\n', (4217, 4264), False, 'import inferencing_pb2\n'), ((4478, 4578), 'inferencing_pb2.Rectangle', 'inferencing_pb2.Rectangle', ([], {'l': '(xmin / iw)', 't': '(ymin / ih)', 'w': '((xmax - xmin) / iw)', 'h': '((ymax - ymin) / ih)'}), '(l=xmin / iw, t=ymin / ih, w=(xmax - xmin) / iw, h\n =(ymax - ymin) / ih)\n', (4503, 4578), False, 'import inferencing_pb2\n'), ((6985, 7024), 'numpy.frombuffer', 'np.frombuffer', (['rawBytes'], {'dtype': 'np.uint8'}), '(rawBytes, dtype=np.uint8)\n', (6998, 7024), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf-8 # Copy from https://github.com/Urinx/WeixinBot/blob/master/wxbot_project_py2.7/config/constant.py import time class Constant(object): """ @brief All used constants are listed here """ WECHAT_CONFIG_FILE = 'config/wechat.conf' WECHAT_COOKIE_FILE = 'config/cookie.bin' LOGGING_LOGGER_NAME = 'WeChat' QRCODE_BLACK = '\033[40m \033[0m' QRCODE_WHITE = '\033[47m \033[0m' HTTP_HEADER_USERAGENT = [('User-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36')] HTTP_HEADER_CONTENTTYPE = ['ContentType', 'application/json; charset=UTF-8'] HTTP_HEADER_CONNECTION = ['Connection', 'keep-alive'] HTTP_HEADER_REFERER = ['Referer', 'https://wx.qq.com/'] HTTP_HEADER_RANGE = ['Range', 'bytes=0-'] REGEX_EMOJI = r'<span class="emoji emoji(\w+)"></span>' SERVER_LOG_FORMAT = '%(asctime)s - %(pathname)s:%(lineno)d - %(name)s - %(levelname)s - %(message)s' SERVER_UPLOAD_ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) SERVER_PAGE_UPLOAD = 'upload.html' SERVER_PAGE_INDEX = 'index.html' RUN_RESULT_SUCCESS = '成功 %ds\n' RUN_RESULT_FAIL = '失败\n[*] 退出程序\n' MAIN_RESTART = '[*] wait for restart' LOG_MSG_FILE = 'WeChat-Msgs-%Y-%m-%d.json' LOG_MSG_GROUP_LIST_FILE = 'group_list.json' LOG_MSG_QUIT = '\n[*] Force quit.\n' LOG_MSG_FAIL = '失败\n' LOG_MSG_SUCCESS = '成功\n' LOG_MSG_START = '[*] 微信网页版 ... 开动\n' LOG_MSG_RECOVER = '[*] 从配置文件中恢复 ... ' LOG_MSG_RECOVER_CONTACT = '[*] 从文件中恢复联系人数据 ... ' LOG_MSG_TRY_INIT = '[*] 尝试初始化 ... ' LOG_MSG_ASSOCIATION_LOGIN = '[*] 通过关联登录 ... ' LOG_MSG_GET_UUID = '[*] 正在获取 uuid ... ' LOG_MSG_GET_QRCODE = '[*] 正在获取二维码 ... 成功\n' LOG_MSG_SCAN_QRCODE = '[*] 请使用微信扫描二维码以登录 ... \n' LOG_MSG_CONFIRM_LOGIN = '[*] 请在手机上点击确认以登录 ... \n' LOG_MSG_WAIT_LOGIN_ERR1 = '[登陆超时] \n' LOG_MSG_WAIT_LOGIN_ERR2 = '[登陆异常] \n' LOG_MSG_LOGIN = '[*] 正在登录 ... ' LOG_MSG_INIT = '[*] 微信初始化 ... ' LOG_MSG_STATUS_NOTIFY = '[*] 开启状态通知 ... ' LOG_MSG_GET_CONTACT = '[*] 获取联系人 ... ' LOG_MSG_CONTACT_COUNT = '[*] 应有 %s 个联系人,读取到联系人 %d 个\n' LOG_MSG_OTHER_CONTACT_COUNT = '[*] 共有 %d 个群 | %d 个直接联系人 | %d 个特殊账号 | %d 公众号或服务号\n' LOG_MSG_GET_GROUP_MEMBER = '[*] 拉取群聊成员 ... ' LOG_MSG_SNAPSHOT = '[*] 保存配置 ... ' LOG_MSG_LOGOUT = '[*] 你在手机上登出了微信\n' LOG_MSG_LOGIN_OTHERWHERE = '[*] 你在其他地方登录了 WEB 版微信\n' LOG_MSG_QUIT_ON_PHONE = '[*] 你在手机上主动退出了\n' LOG_MSG_RUNTIME = '[*] Total run: %s\n' LOG_MSG_KILL_PROCESS = 'kill %d' LOG_MSG_NEW_MSG = '>>> %d 条新消息\n' LOG_MSG_LOCATION = '[位置] %s' LOG_MSG_PICTURE = '[图片] %s' LOG_MSG_VOICE = '[语音] %s' LOG_MSG_RECALL = '撤回了一条消息' LOG_MSG_ADD_FRIEND = '%s 请求添加你为好友' LOG_MSG_UNKNOWN_MSG = '[*] 该消息类型为: %d,内容: %s' LOG_MSG_VIDEO = '[小视频] %s' LOG_MSG_NOTIFY_PHONE = '[*] 提示手机网页版微信登录状态\n' LOG_MSG_EMOTION = '[表情] %s' LOG_MSG_NAME_CARD = ( '[名片]\n' '=========================\n' '= 昵称: %s\n' '= 微信号: %s\n' '= 地区: %s %s\n' '= 性别: %s\n' '=========================' ) LOG_MSG_SEX_OPTION = ['未知', '男', '女'] LOG_MSG_APP_LINK = ( '[%s]\n' '=========================\n' '= 标题: %s\n' '= 描述: %s\n' '= 链接: %s\n' '= 来自: %s\n' '=========================' ) LOG_MSG_APP_LINK_TYPE = {5: '链接', 3: '音乐', 7: '微博'} LOG_MSG_APP_IMG = ( '[图片]\n' '=========================\n' '= 文件: %s\n' '= 来自: %s\n' '=========================' ) LOG_MSG_SYSTEM = '系统消息' LOG_MSG_UNKNOWN_NAME = '未知_' LOG_MSG_UNKNOWN_GROUP_NAME = '未知群_' TABLE_GROUP_MSG_LOG = 'WeChatRoomMessage' TABLE_GROUP_MSG_LOG_COL = """ MsgID text, RoomOwnerID text, RoomName text, UserCount text, FromUserName text, ToUserName text, AttrStatus text, DisplayName text, Name text, MsgType text, FaceMsg text, TextMsg text, ImageMsg text, VideoMsg text, SoundMsg text, LinkMsg text, NameCardMsg text, LocationMsg text, RecallMsgID text, SysMsg text, MsgTime text, MsgTimestamp text """ @staticmethod def TABLE_GROUP_LIST(): return 'WeChatRoom_' + time.strftime('%Y%m%d', time.localtime()) TABLE_GROUP_LIST_COL = """ RoomName text, RoomID text, RoomOwnerID text, UserCount text, RoomIcon text """ @staticmethod def TABLE_GROUP_USER_LIST(): return 'WeChatRoomMember_' + time.strftime('%Y%m%d', time.localtime()) TABLE_GROUP_USER_LIST_COL = """ RoomID text, MemberID text, MemberNickName text, MemberDisplayName text, MemberAttrStatus text """ TABLE_RECORD_ENTER_GROUP = 'WeChatEnterGroupRecord' TABLE_RECORD_ENTER_GROUP_COL = """ MsgID text, RoomName text, FromUserName text, ToUserName text, Name text, EnterTime text """ TABLE_RECORD_RENAME_GROUP = 'WeChatRenameGroupRecord' TABLE_RECORD_RENAME_GROUP_COL = """ MsgID text, FromName text, ToName text, ModifyPeople text, ModifyTime text """ API_APPID = 'wx782c26e4c19acffb' API_WXAPPID = 'wx299208e619de7026' # Weibo # 'wxeb7ec651dd0aefa9' # Weixin API_LANG = 'en_US' API_USER_AGENT = ( 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/65.0.3325.181 Safari/537.36' ) API_SPECIAL_USER = [ 'newsapp', 'filehelper', 'weibo', 'qqmail', 'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle', 'lbsapp', 'shakeapp', 'medianote', 'qqfriend', 'readerapp', 'blogapp', 'facebookapp', 'masssendapp', 'meishiapp', 'feedsapp', 'voip', 'blogappweixin', 'brandsessionholder', 'weixin', 'weixinreminder', 'officialaccounts', 'wxitil', 'notification_messages', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c', 'userexperience_alarm', ] EMOTICON = [ '[Smile]', '[Grimace]', '[Drool]', '[Scowl]', '[CoolGuy]', '[Sob]', '[Shy]', '[Silent]', '[Sleep]', '[Cry]', '[Awkward]', '[Angry]', '[Tongue]', '[Grin]', '[Surprise]', '[Frown]', '[Ruthless]', '[Blush]', '[Scream]', '[Puke]', '[Chuckle]', '[Joyful]', '[Slight]', '[Smug]', '[Hungry]', '[Drowsy]', '[Panic]', '[Sweat]', '[Laugh]', '[Commando]', '[Determined]', '[Scold]', '[Shocked]', '[Shhh]', '[Dizzy]', '[Tormented]', '[Toasted]', '[Skull]', '[Hammer]', '[Wave]', '[Relief]', '[DigNose]', '[Clap]', '[Shame]', '[Trick]',' [Bah!L]','[Bah!R]', '[Yawn]', '[Lookdown]', '[Wronged]', '[Puling]', '[Sly]', '[Kiss]', '[Uh-oh]', '[Whimper]', '[Cleaver]', '[Melon]', '[Beer]', '[Basketball]', '[PingPong]', '[Coffee]', '[Rice]', '[Pig]', '[Rose]', '[Wilt]', '[Lip]', '[Heart]', '[BrokenHeart]', '[Cake]', '[Lightning]', '[Bomb]', '[Dagger]', '[Soccer]', '[Ladybug]', '[Poop]', '[Moon]', '[Sun]', '[Gift]', '[Hug]', '[Strong]', '[Weak]', '[Shake]', '[Victory]', '[Admire]', '[Beckon]', '[Fist]', '[Pinky]', '[Love]', '[No]', '[OK]', '[InLove]', '[Blowkiss]', '[Waddle]', '[Tremble]', '[Aaagh!]', '[Twirl]', '[Kotow]', '[Lookback]', '[Jump]', '[Give-in]', u'\U0001f604', u'\U0001f637', u'\U0001f639', u'\U0001f61d', u'\U0001f632', u'\U0001f633', u'\U0001f631', u'\U0001f64d', u'\U0001f609', u'\U0001f60c', u'\U0001f612', u'\U0001f47f', u'\U0001f47b', u'\U0001f49d', u'\U0001f64f', u'\U0001f4aa', u'\U0001f4b5', u'\U0001f382', u'\U0001f388', u'\U0001f4e6', ] BOT_ZHIHU_URL_LATEST = 'http://news-at.zhihu.com/api/4/news/latest' BOT_ZHIHU_URL_DAILY = 'http://daily.zhihu.com/story/' BOT_TULING_API_KEY = '55e7f30895a0a10535984bae5ad294d1' BOT_TULING_API_URL = 'http://www.tuling123.com/openapi/api?key=%s&info=%s&userid=%s' BOT_TULING_BOT_REPLY = u'麻烦说的清楚一点,我听不懂你在说什么'
[ "time.localtime" ]
[((4484, 4500), 'time.localtime', 'time.localtime', ([], {}), '()\n', (4498, 4500), False, 'import time\n'), ((4775, 4791), 'time.localtime', 'time.localtime', ([], {}), '()\n', (4789, 4791), False, 'import time\n')]
"""Implementation of treadmill-admin CLI plugin.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import io import click from treadmill import cli from treadmill import restclient from treadmill import yamlwrapper as yaml def init(): """Return top level command handler.""" ctx = {} @click.group() @click.option('--cell', required=True, envvar='TREADMILL_CELL', callback=cli.handle_context_opt, expose_value=False) @click.option('--api', required=False, help='API url to use.', envvar='TREADMILL_ADMINAPI') @click.option('--outfmt', type=click.Choice(['json', 'yaml']), default='json') def top(api, outfmt): """Invoke Treadmill HTTP REST API.""" cli.OUTPUT_FORMAT = outfmt ctx['api'] = [api] @top.command() @click.argument('path') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def get(path): """REST GET request.""" response = restclient.get(ctx['api'], path) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) @top.command() @click.argument('path') @click.argument('payload', type=click.Path(exists=True, readable=True)) @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def post(path, payload): """REST POST request.""" with io.open(payload, 'rb') as fd: request = yaml.load(stream=fd) response = restclient.post(ctx['api'], path, payload=request) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) @top.command() @click.argument('path') @click.argument('payload', type=click.Path(exists=True, readable=True)) @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def put(path, payload): """REST PUT request.""" with io.open(payload, 'rb') as fd: request = yaml.load(stream=fd) response = restclient.put(ctx['api'], path, payload=request) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) @top.command() @click.argument('path') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def delete(path): """REST DELETE request.""" response = restclient.delete(ctx['api'], path) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) del get del post del put del delete return top
[ "treadmill.restclient.delete", "treadmill.restclient.put", "click.argument", "treadmill.restclient.post", "click.option", "click.Choice", "treadmill.yamlwrapper.load", "click.Path", "treadmill.cli.make_formatter", "io.open", "click.group", "treadmill.cli.handle_exceptions", "treadmill.restclient.get" ]
[((406, 419), 'click.group', 'click.group', ([], {}), '()\n', (417, 419), False, 'import click\n'), ((425, 545), 'click.option', 'click.option', (['"""--cell"""'], {'required': '(True)', 'envvar': '"""TREADMILL_CELL"""', 'callback': 'cli.handle_context_opt', 'expose_value': '(False)'}), "('--cell', required=True, envvar='TREADMILL_CELL', callback=cli\n .handle_context_opt, expose_value=False)\n", (437, 545), False, 'import click\n'), ((600, 695), 'click.option', 'click.option', (['"""--api"""'], {'required': '(False)', 'help': '"""API url to use."""', 'envvar': '"""TREADMILL_ADMINAPI"""'}), "('--api', required=False, help='API url to use.', envvar=\n 'TREADMILL_ADMINAPI')\n", (612, 695), False, 'import click\n'), ((969, 991), 'click.argument', 'click.argument', (['"""path"""'], {}), "('path')\n", (983, 991), False, 'import click\n'), ((997, 1050), 'treadmill.cli.handle_exceptions', 'cli.handle_exceptions', (['restclient.CLI_REST_EXCEPTIONS'], {}), '(restclient.CLI_REST_EXCEPTIONS)\n', (1018, 1050), False, 'from treadmill import cli\n'), ((1269, 1291), 'click.argument', 'click.argument', (['"""path"""'], {}), "('path')\n", (1283, 1291), False, 'import click\n'), ((1373, 1426), 'treadmill.cli.handle_exceptions', 'cli.handle_exceptions', (['restclient.CLI_REST_EXCEPTIONS'], {}), '(restclient.CLI_REST_EXCEPTIONS)\n', (1394, 1426), False, 'from treadmill import cli\n'), ((1760, 1782), 'click.argument', 'click.argument', (['"""path"""'], {}), "('path')\n", (1774, 1782), False, 'import click\n'), ((1864, 1917), 'treadmill.cli.handle_exceptions', 'cli.handle_exceptions', (['restclient.CLI_REST_EXCEPTIONS'], {}), '(restclient.CLI_REST_EXCEPTIONS)\n', (1885, 1917), False, 'from treadmill import cli\n'), ((2248, 2270), 'click.argument', 'click.argument', (['"""path"""'], {}), "('path')\n", (2262, 2270), False, 'import click\n'), ((2276, 2329), 'treadmill.cli.handle_exceptions', 'cli.handle_exceptions', (['restclient.CLI_REST_EXCEPTIONS'], {}), '(restclient.CLI_REST_EXCEPTIONS)\n', (2297, 2329), False, 'from treadmill import cli\n'), ((1121, 1153), 'treadmill.restclient.get', 'restclient.get', (["ctx['api']", 'path'], {}), "(ctx['api'], path)\n", (1135, 1153), False, 'from treadmill import restclient\n'), ((1175, 1199), 'treadmill.cli.make_formatter', 'cli.make_formatter', (['None'], {}), '(None)\n', (1193, 1199), False, 'from treadmill import cli\n'), ((1594, 1644), 'treadmill.restclient.post', 'restclient.post', (["ctx['api']", 'path'], {'payload': 'request'}), "(ctx['api'], path, payload=request)\n", (1609, 1644), False, 'from treadmill import restclient\n'), ((1666, 1690), 'treadmill.cli.make_formatter', 'cli.make_formatter', (['None'], {}), '(None)\n', (1684, 1690), False, 'from treadmill import cli\n'), ((2083, 2132), 'treadmill.restclient.put', 'restclient.put', (["ctx['api']", 'path'], {'payload': 'request'}), "(ctx['api'], path, payload=request)\n", (2097, 2132), False, 'from treadmill import restclient\n'), ((2154, 2178), 'treadmill.cli.make_formatter', 'cli.make_formatter', (['None'], {}), '(None)\n', (2172, 2178), False, 'from treadmill import cli\n'), ((2406, 2441), 'treadmill.restclient.delete', 'restclient.delete', (["ctx['api']", 'path'], {}), "(ctx['api'], path)\n", (2423, 2441), False, 'from treadmill import restclient\n'), ((2463, 2487), 'treadmill.cli.make_formatter', 'cli.make_formatter', (['None'], {}), '(None)\n', (2481, 2487), False, 'from treadmill import cli\n'), ((744, 774), 'click.Choice', 'click.Choice', (["['json', 'yaml']"], {}), "(['json', 'yaml'])\n", (756, 774), False, 'import click\n'), ((1502, 1524), 'io.open', 'io.open', (['payload', '"""rb"""'], {}), "(payload, 'rb')\n", (1509, 1524), False, 'import io\n'), ((1554, 1574), 'treadmill.yamlwrapper.load', 'yaml.load', ([], {'stream': 'fd'}), '(stream=fd)\n', (1563, 1574), True, 'from treadmill import yamlwrapper as yaml\n'), ((1328, 1366), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'readable': '(True)'}), '(exists=True, readable=True)\n', (1338, 1366), False, 'import click\n'), ((1991, 2013), 'io.open', 'io.open', (['payload', '"""rb"""'], {}), "(payload, 'rb')\n", (1998, 2013), False, 'import io\n'), ((2043, 2063), 'treadmill.yamlwrapper.load', 'yaml.load', ([], {'stream': 'fd'}), '(stream=fd)\n', (2052, 2063), True, 'from treadmill import yamlwrapper as yaml\n'), ((1819, 1857), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'readable': '(True)'}), '(exists=True, readable=True)\n', (1829, 1857), False, 'import click\n')]
import pika import sys import os import time from pathlib import Path class LogConfirmer(object): FILENAME = "log.txt" def __init__(self): self.cache_dict = {} self.already = set() try: os.remove(self.FILENAME) Path(self.FILENAME).touch() except OSError: pass def add(self, tid, node, body): if tid not in self.already: self.cache_dict.setdefault(tid, {}).setdefault(node, []).append(body) self.checkAndSave(tid) def checkAndSave(self, tid): vl = list(map(len, self.cache_dict[tid].values())) cl = [int(i >= 5) for i in vl] if sum(cl) > 0: pickOne = cl.index(1) self.__save__(tid, pickOne) def __save__(self, tid, pickOne): batchlog = list(self.cache_dict[tid].values())[pickOne] if len(batchlog) < 5: raise Exception if len(batchlog) > 5: batchlog = batchlog[0:5] timed_batchlog = ["{}, {}".format(time.time(), i) for i in batchlog] for i in timed_batchlog: with open(self.FILENAME, "a") as f: f.write(i + "\n") self.cache_dict.pop(tid, None) self.already.add(tid) previous_tid = "" batchlog = [] lc = LogConfirmer() def callback(ch, method, properties, body): global previous_tid global batchlog global lc body = body.decode("utf-8") # print(">>>>>>", body) log_line = body.split("|") if len(log_line) <= 2: # print(body) return _, tid, node = list(map(str.strip, log_line[0:3])) lc.add(tid, node, body) # i = "{}, {}\n".format(time.time(), body) # with open("log.txt", "a") as f: # f.write(i) def main(): connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='shimlog') channel.basic_consume(queue='shimlog', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming() if __name__ == '__main__': try: main() except KeyboardInterrupt: print('Interrupted') try: sys.exit(0) except SystemExit: os._exit(0)
[ "os.remove", "pika.ConnectionParameters", "time.time", "pathlib.Path", "os._exit", "sys.exit" ]
[((1805, 1848), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': '"""localhost"""'}), "(host='localhost')\n", (1830, 1848), False, 'import pika\n'), ((233, 257), 'os.remove', 'os.remove', (['self.FILENAME'], {}), '(self.FILENAME)\n', (242, 257), False, 'import os\n'), ((1029, 1040), 'time.time', 'time.time', ([], {}), '()\n', (1038, 1040), False, 'import time\n'), ((2244, 2255), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2252, 2255), False, 'import sys\n'), ((270, 289), 'pathlib.Path', 'Path', (['self.FILENAME'], {}), '(self.FILENAME)\n', (274, 289), False, 'from pathlib import Path\n'), ((2295, 2306), 'os._exit', 'os._exit', (['(0)'], {}), '(0)\n', (2303, 2306), False, 'import os\n')]
import numpy as np import os # lib from Qiskit Aqua # from qiskit.aqua import Operator, QuantumInstance # from qiskit.aqua.algorithms import VQE, ExactEigensolver # from qiskit.aqua.components.optimizers import COBYLA from qiskit.aqua.operators import Z2Symmetries from qiskit.circuit.instruction import Instruction # lib from Qiskit Aqua Chemistry from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from torchquantum.plugins.qiskit_processor import QiskitProcessor from torchquantum.plugins import qiskit2tq processor = QiskitProcessor( use_real_qc=False, backend_name=None, noise_model_name=None, coupling_map_name=None, basis_gates_name=None, n_shots=8192, initial_layout=None, seed_transpiler=42, seed_simulator=42, optimization_level=None, max_jobs=5, remove_ops=False, remove_ops_thres=1e-4, ) # import pdb # pdb.set_trace() def load_qubitop_for_molecule(molecule_data): atom_list = [a[0] + ' ' + " ".join([str(elem) for elem in a[1]]) for a in molecule_data['geometry']] atom = "; ".join(atom_list) #atom = 'Li .0 .0 .0; H .0 .0 3.9' basis = molecule_data['basis'] transform = molecule_data['transform'] electrons = molecule_data['electrons'] active = molecule_data['active_orbitals'] driver = PySCFDriver(atom=atom, unit=UnitsType.ANGSTROM, basis=basis, charge=0, spin=0) molecule = driver.run() num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 #print("# of electrons: {}".format(num_particles)) #print("# of spin orbitals: {}".format(num_spin_orbitals)) freeze_list = [x for x in range(int(active/2), int(num_particles/2))] remove_list = [-x for x in range(active,molecule.num_orbitals-int(num_particles/2)+int(active/2))] #print(freeze_list) #print(remove_list) if transform == 'BK': map_type = 'bravyi_kitaev' elif transform == 'JW': map_type = 'jordan_wigner' else: map_type = 'parity' remove_list = [x % molecule.num_orbitals for x in remove_list] freeze_list = [x % molecule.num_orbitals for x in freeze_list] remove_list = [x - len(freeze_list) for x in remove_list] remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list] freeze_list += [x + molecule.num_orbitals for x in freeze_list] fermiOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) energy_shift = 0 if len(freeze_list) > 0: fermiOp, energy_shift = fermiOp.fermion_mode_freezing(freeze_list) num_spin_orbitals -= len(freeze_list) num_particles -= len(freeze_list) if len(remove_list) > 0: fermiOp = fermiOp.fermion_mode_elimination(remove_list) num_spin_orbitals -= len(remove_list) qubitOp = fermiOp.mapping(map_type=map_type, threshold=0.00000001) if len(freeze_list) > 0 or len(remove_list) >0: qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) #print(qubitOp.print_operators()) num_spin_orbitals= qubitOp.num_qubits return molecule, qubitOp, map_type, num_particles, num_spin_orbitals def generate_uccsd(molecule_data): molecule, qubitOp, map_type, num_particles, num_spin_orbitals = load_qubitop_for_molecule(molecule_data) nuclear_repulsion_energy = molecule.nuclear_repulsion_energy print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) qubit_reduction = False HF_state = HartreeFock(num_spin_orbitals, num_particles, map_type, qubit_reduction) uccsd_ansatz = UCCSD(reps=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, initial_state=HF_state, qubit_mapping=map_type, two_qubit_reduction=qubit_reduction) circ = uccsd_ansatz.construct_circuit([0.4242] * uccsd_ansatz.num_parameters) circ.measure_all() circ_transpiled = processor.transpile(circ) q_layer = qiskit2tq(circ_transpiled) for name, param in q_layer.named_parameters(): if not (param % (np.pi / 2)).detach().cpu().numpy().any(): param.requires_grad = False #randlist = np.random.rand(uccsd_ansatz.num_parameters) # ansatz parameters #uccsd_ansatz_circuit = uccsd_ansatz.construct_circuit(randlist) return q_layer def molecule_data2str(md): return md['name'] + ' ' + md['basis'] + ' ' + md['transform']+ ' ' + str(md['active_orbitals']) def write_ansatz(molecule_data): #filename = ... ansatz = generate_uccsd(molecule_data) randlist = np.random.rand(uccsd_ansatz.num_parameters) # ansatz parameters uccsd_ansatz_circuit = uccsd_ansatz.construct_circuit(randlist) print(uccsd_ansatz_circuit) def write_observable(molecule_data, root): #filename = ... _, qubitOp, _, _ , _ = load_qubitop_for_molecule(molecule_data) molecule_str = molecule_data2str(molecule_data) numq = qubitOp.num_qubits molecule_str += ' q' + str(numq) + '\n' op_str = qubitOp.print_details() filename = f"{molecule_data['name'].lower()}_" \ f"{molecule_data['transform'].lower()}" with open(os.path.join(root, filename, f"{filename}.txt"), 'w') as wfid: wfid.write(f"{molecule_data['name'].lower()} " f"{molecule_data['transform'].lower()} {numq}\n") for line in op_str.splitlines(): molecule_str = '' #print(ord(line[6])) #ZXXIII (6.505213034913027e-19+0j) linedata = line.split(chr(9)) if not complex(linedata[1]).imag == 0: print(f"WARNING: imaginary is not zero!!") molecule_str += str(complex(linedata[1]).real) + ' ' for (i, c) in enumerate(linedata[0]): molecule_str += c+str(i)+' ' wfid.write(f"{molecule_str}\n") # molecule_str # print(molecule_str) # Molecule parameters for H2 h2_molecule = { 'name' : 'H2', 'basis' : 'sto-3g', 'transform' : 'BK', 'electrons' : 2, 'geometry' : [('H', (0., 0., 0.)), ('H', (0., 0., 0.72))], 'active_orbitals' : 2 } # Molecule parameters for H2O h2o_molecule = { 'name' : 'H2O', 'basis' : 'sto-3g', 'transform' : 'BK', 'electrons' : 8, 'geometry' : [('O', (0.,0.,0.)), ('H', (0.757,0.586,0.)), ('H', (-0.757,0.586,0.))], 'active_orbitals' : 4 } # Molecule parameters for LiH lih_molecule = { 'name' : 'LiH', 'basis' : 'sto-3g', 'transform' : 'BK', 'electrons' : 4, 'geometry' : [('Li', (0., 0., 0.)), ('H', (0., 0., 1.45))], 'active_orbitals' : 4 } # Molecule parameters for CH4 ch4_molecule = { 'name' : 'CH4', 'basis' : 'sto-3g', 'transform' : 'BK', 'electrons' : 10, 'geometry' : [('C', (0, 0, 0)), ('H', (0.5541, 0.7996, 0.4965)), ('H', (0.6833, -0.8134, -0.2536)), ('H', (-0.7782, -0.3735, 0.6692)), ('H', (-0.4593, 0.3874, -0.9121))], 'active_orbitals' : 4 } # generate_uccsd(h2_molecule) #generate_uccsd(h2o_molecule) #generate_uccsd(lih_molecule) #generate_uccsd(ch4_molecule) molecule_name_dict = { 'h2': h2_molecule, 'h2o': h2o_molecule, 'lih': lih_molecule, 'ch4': ch4_molecule } if __name__ == '__main__': import pdb pdb.set_trace() generate_uccsd(molecule_name_dict['ch4']) # for transform in ['BK', 'JW']: # for name, info in molecule_name_dict.items(): # root = './examples/data/vqe/' # info['transform'] = transform # os.makedirs(os.path.join(root, f"{name}_{transform.lower()}"), # exist_ok=True) # # write_observable(info, root)
[ "qiskit.chemistry.components.variational_forms.UCCSD", "qiskit.chemistry.FermionicOperator", "qiskit.chemistry.components.initial_states.HartreeFock", "torchquantum.plugins.qiskit2tq", "qiskit.chemistry.drivers.PySCFDriver", "pdb.set_trace", "numpy.random.rand", "qiskit.aqua.operators.Z2Symmetries.two_qubit_reduction", "os.path.join", "torchquantum.plugins.qiskit_processor.QiskitProcessor" ]
[((710, 1004), 'torchquantum.plugins.qiskit_processor.QiskitProcessor', 'QiskitProcessor', ([], {'use_real_qc': '(False)', 'backend_name': 'None', 'noise_model_name': 'None', 'coupling_map_name': 'None', 'basis_gates_name': 'None', 'n_shots': '(8192)', 'initial_layout': 'None', 'seed_transpiler': '(42)', 'seed_simulator': '(42)', 'optimization_level': 'None', 'max_jobs': '(5)', 'remove_ops': '(False)', 'remove_ops_thres': '(0.0001)'}), '(use_real_qc=False, backend_name=None, noise_model_name=None,\n coupling_map_name=None, basis_gates_name=None, n_shots=8192,\n initial_layout=None, seed_transpiler=42, seed_simulator=42,\n optimization_level=None, max_jobs=5, remove_ops=False, remove_ops_thres\n =0.0001)\n', (725, 1004), False, 'from torchquantum.plugins.qiskit_processor import QiskitProcessor\n'), ((1477, 1555), 'qiskit.chemistry.drivers.PySCFDriver', 'PySCFDriver', ([], {'atom': 'atom', 'unit': 'UnitsType.ANGSTROM', 'basis': 'basis', 'charge': '(0)', 'spin': '(0)'}), '(atom=atom, unit=UnitsType.ANGSTROM, basis=basis, charge=0, spin=0)\n', (1488, 1555), False, 'from qiskit.chemistry.drivers import PySCFDriver, UnitsType\n'), ((2565, 2651), 'qiskit.chemistry.FermionicOperator', 'FermionicOperator', ([], {'h1': 'molecule.one_body_integrals', 'h2': 'molecule.two_body_integrals'}), '(h1=molecule.one_body_integrals, h2=molecule.\n two_body_integrals)\n', (2582, 2651), False, 'from qiskit.chemistry import FermionicOperator\n'), ((3709, 3781), 'qiskit.chemistry.components.initial_states.HartreeFock', 'HartreeFock', (['num_spin_orbitals', 'num_particles', 'map_type', 'qubit_reduction'], {}), '(num_spin_orbitals, num_particles, map_type, qubit_reduction)\n', (3720, 3781), False, 'from qiskit.chemistry.components.initial_states import HartreeFock\n'), ((3801, 3969), 'qiskit.chemistry.components.variational_forms.UCCSD', 'UCCSD', ([], {'reps': '(1)', 'num_orbitals': 'num_spin_orbitals', 'num_particles': 'num_particles', 'initial_state': 'HF_state', 'qubit_mapping': 'map_type', 'two_qubit_reduction': 'qubit_reduction'}), '(reps=1, num_orbitals=num_spin_orbitals, num_particles=num_particles,\n initial_state=HF_state, qubit_mapping=map_type, two_qubit_reduction=\n qubit_reduction)\n', (3806, 3969), False, 'from qiskit.chemistry.components.variational_forms import UCCSD\n'), ((4229, 4255), 'torchquantum.plugins.qiskit2tq', 'qiskit2tq', (['circ_transpiled'], {}), '(circ_transpiled)\n', (4238, 4255), False, 'from torchquantum.plugins import qiskit2tq\n'), ((4823, 4866), 'numpy.random.rand', 'np.random.rand', (['uccsd_ansatz.num_parameters'], {}), '(uccsd_ansatz.num_parameters)\n', (4837, 4866), True, 'import numpy as np\n'), ((7424, 7439), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (7437, 7439), False, 'import pdb\n'), ((3128, 3184), 'qiskit.aqua.operators.Z2Symmetries.two_qubit_reduction', 'Z2Symmetries.two_qubit_reduction', (['qubitOp', 'num_particles'], {}), '(qubitOp, num_particles)\n', (3160, 3184), False, 'from qiskit.aqua.operators import Z2Symmetries\n'), ((5404, 5451), 'os.path.join', 'os.path.join', (['root', 'filename', 'f"""{filename}.txt"""'], {}), "(root, filename, f'{filename}.txt')\n", (5416, 5451), False, 'import os\n')]
# Author: <NAME> import unittest import redis import threading import time import copy from redis_rw_lock import RWLock class Writer(threading.Thread): def __init__(self, buffer_, rw_lock, init_sleep_time, sleep_time, to_write): """ @param buffer_: common buffer_ shared by the readers and writers @type buffer_: list @type rw_lock: L{RWLock} @param init_sleep_time: sleep time before doing any action @type init_sleep_time: C{float} @param sleep_time: sleep time while in critical section @type sleep_time: C{float} @param to_write: data that will be appended to the buffer """ threading.Thread.__init__(self) self.__buffer = buffer_ self.__rw_lock = rw_lock self.__init_sleep_time = init_sleep_time self.__sleep_time = sleep_time self.__to_write = to_write self.entry_time = None """Time of entry to the critical section""" self.exit_time = None """Time of exit from the critical section""" def run(self): time.sleep(self.__init_sleep_time) self.__rw_lock.acquire() self.entry_time = time.time() time.sleep(self.__sleep_time) self.__buffer.append(self.__to_write) self.exit_time = time.time() self.__rw_lock.release() class Reader(threading.Thread): def __init__(self, buffer_, rw_lock, init_sleep_time, sleep_time): """ @param buffer_: common buffer shared by the readers and writers @type buffer_: list @type rw_lock: L{RWLock} @param init_sleep_time: sleep time before doing any action @type init_sleep_time: C{float} @param sleep_time: sleep time while in critical section @type sleep_time: C{float} """ threading.Thread.__init__(self) self.__buffer = buffer_ self.__rw_lock = rw_lock self.__init_sleep_time = init_sleep_time self.__sleep_time = sleep_time self.buffer_read = None """a copy of a the buffer read while in critical section""" self.entry_time = None """Time of entry to the critical section""" self.exit_time = None """Time of exit from the critical section""" def run(self): time.sleep(self.__init_sleep_time) self.__rw_lock.acquire() self.entry_time = time.time() time.sleep(self.__sleep_time) self.buffer_read = copy.deepcopy(self.__buffer) self.exit_time = time.time() self.__rw_lock.release() class RWLockTestCase(unittest.TestCase): def test_readers_nonexclusive_access(self): (buffer_, threads) = self.__init_variables() threads.append(Reader(buffer_, self.__generate_reader_lock(), 0, 1)) threads.append(Writer(buffer_, self.__generate_writer_lock(), 0.4, 1, 1)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 1, 1)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 1.2, 0.2)) self.__start_and_join_threads(threads) # The third reader should enter after the second one but it should # exit before the second one exits # (i.e. the readers should be in the critical section # at the same time) self.assertEqual([], threads[0].buffer_read) self.assertEqual([1], threads[2].buffer_read) self.assertEqual([1], threads[3].buffer_read) self.assertTrue(threads[1].exit_time <= threads[2].entry_time) self.assertTrue(threads[2].entry_time <= threads[3].entry_time) self.assertTrue(threads[3].exit_time < threads[2].exit_time) def test_writers_exclusive_access(self): (buffer_, threads) = self.__init_variables() threads.append(Writer(buffer_, self.__generate_writer_lock(), 0, 0.4, 1)) threads.append(Writer(buffer_, self.__generate_writer_lock(), 0.1, 0, 2)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 0.2, 0)) self.__start_and_join_threads(threads) # The second writer should wait for the first one to exit self.assertEqual([1, 2], threads[2].buffer_read) self.assertTrue(threads[0].exit_time <= threads[1].entry_time) self.assertTrue(threads[1].exit_time <= threads[2].exit_time) def test_writer_priority(self): (buffer_, threads) = self.__init_variables() threads.append(Writer(buffer_, self.__generate_writer_lock(), 0, 0, 1)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 0.1, 0.4)) threads.append(Writer(buffer_, self.__generate_writer_lock(), 0.2, 0, 2)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 0.3, 0)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 0.3, 0)) self.__start_and_join_threads(threads) # The second writer should go before the second and the third reader self.assertEqual([1], threads[1].buffer_read) self.assertEqual([1, 2], threads[3].buffer_read) self.assertEqual([1, 2], threads[4].buffer_read) self.assertTrue(threads[0].exit_time < threads[1].entry_time) self.assertTrue(threads[1].exit_time <= threads[2].entry_time) self.assertTrue(threads[2].exit_time <= threads[3].entry_time) self.assertTrue(threads[2].exit_time <= threads[4].entry_time) def test_many_writers_priority(self): (buffer_, threads) = self.__init_variables() threads.append(Writer(buffer_, self.__generate_writer_lock(), 0, 0, 1)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 0.1, 0.6)) threads.append(Writer(buffer_, self.__generate_writer_lock(), 0.2, 0.1, 2)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 0.3, 0)) threads.append(Reader(buffer_, self.__generate_reader_lock(), 0.4, 0)) threads.append(Writer(buffer_, self.__generate_writer_lock(), 0.5, 0.1, 3)) self.__start_and_join_threads(threads) # The two last writers should go first -- after the first reader and # before the second and the third reader self.assertEqual([1], threads[1].buffer_read) self.assertEqual([1, 2, 3], threads[3].buffer_read) self.assertEqual([1, 2, 3], threads[4].buffer_read) self.assertTrue(threads[0].exit_time < threads[1].entry_time) self.assertTrue(threads[1].exit_time <= threads[2].entry_time) self.assertTrue(threads[1].exit_time <= threads[5].entry_time) self.assertTrue(threads[2].exit_time <= threads[3].entry_time) self.assertTrue(threads[2].exit_time <= threads[4].entry_time) self.assertTrue(threads[5].exit_time <= threads[3].entry_time) self.assertTrue(threads[5].exit_time <= threads[4].entry_time) @staticmethod def __init_variables(): buffer_ = [] threads = [] return (buffer_, threads) @staticmethod def __generate_reader_lock(name='RWLock'): redis_conn = redis.StrictRedis() return RWLock(redis_conn, name, mode=RWLock.READ) @staticmethod def __generate_writer_lock(name='RWLock'): redis_conn = redis.StrictRedis() return RWLock(redis_conn, name, mode=RWLock.WRITE) @staticmethod def __start_and_join_threads(threads): for t in threads: t.start() for t in threads: t.join()
[ "copy.deepcopy", "threading.Thread.__init__", "redis_rw_lock.RWLock", "time.time", "time.sleep", "redis.StrictRedis" ]
[((675, 706), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (700, 706), False, 'import threading\n'), ((1089, 1123), 'time.sleep', 'time.sleep', (['self.__init_sleep_time'], {}), '(self.__init_sleep_time)\n', (1099, 1123), False, 'import time\n'), ((1183, 1194), 'time.time', 'time.time', ([], {}), '()\n', (1192, 1194), False, 'import time\n'), ((1203, 1232), 'time.sleep', 'time.sleep', (['self.__sleep_time'], {}), '(self.__sleep_time)\n', (1213, 1232), False, 'import time\n'), ((1304, 1315), 'time.time', 'time.time', ([], {}), '()\n', (1313, 1315), False, 'import time\n'), ((1825, 1856), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (1850, 1856), False, 'import threading\n'), ((2304, 2338), 'time.sleep', 'time.sleep', (['self.__init_sleep_time'], {}), '(self.__init_sleep_time)\n', (2314, 2338), False, 'import time\n'), ((2398, 2409), 'time.time', 'time.time', ([], {}), '()\n', (2407, 2409), False, 'import time\n'), ((2418, 2447), 'time.sleep', 'time.sleep', (['self.__sleep_time'], {}), '(self.__sleep_time)\n', (2428, 2447), False, 'import time\n'), ((2475, 2503), 'copy.deepcopy', 'copy.deepcopy', (['self.__buffer'], {}), '(self.__buffer)\n', (2488, 2503), False, 'import copy\n'), ((2529, 2540), 'time.time', 'time.time', ([], {}), '()\n', (2538, 2540), False, 'import time\n'), ((7034, 7053), 'redis.StrictRedis', 'redis.StrictRedis', ([], {}), '()\n', (7051, 7053), False, 'import redis\n'), ((7069, 7111), 'redis_rw_lock.RWLock', 'RWLock', (['redis_conn', 'name'], {'mode': 'RWLock.READ'}), '(redis_conn, name, mode=RWLock.READ)\n', (7075, 7111), False, 'from redis_rw_lock import RWLock\n'), ((7199, 7218), 'redis.StrictRedis', 'redis.StrictRedis', ([], {}), '()\n', (7216, 7218), False, 'import redis\n'), ((7234, 7277), 'redis_rw_lock.RWLock', 'RWLock', (['redis_conn', 'name'], {'mode': 'RWLock.WRITE'}), '(redis_conn, name, mode=RWLock.WRITE)\n', (7240, 7277), False, 'from redis_rw_lock import RWLock\n')]
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, <NAME>. All rights reserved. # Distributed under the terms of the new BSD License. # ----------------------------------------------------------------------------- """ An ArrayList is a strongly typed list whose type can be anything that can be interpreted as a numpy data type. Example ------- >>> L = ArrayList( [[0], [1,2], [3,4,5], [6,7,8,9]] ) >>> print L [ [0] [1 2] [3 4 5] [6 7 8 9] ] >>> print L.data [0 1 2 3 4 5 6 7 8 9] You can add several items at once by specifying common or individual size: a single scalar means all items are the same size while a list of sizes is used to specify individual item sizes. Example ------- >>> L = ArrayList( np.arange(10), [3,3,4]) >>> print L [ [0 1 2] [3 4 5] [6 7 8 9] ] >>> print L.data [0 1 2 3 4 5 6 7 8 9] """ import numpy as np class ArrayList(object): """ An ArrayList is a strongly typed list whose type can be anything that can be interpreted as a numpy data type. """ def __init__(self, data=None, itemsize=None, dtype=float, sizeable=True, writeable=True): """ Create a new buffer using given data and sizes or dtype Parameters ---------- data : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. itemsize: int or 1-D array If `itemsize is an integer, N, the array will be divided into elements of size N. If such partition is not possible, an error is raised. If `itemsize` is 1-D array, the array will be divided into elements whose succesive sizes will be picked from itemsize. If the sum of itemsize values is different from array size, an error is raised. dtype: np.dtype Any object that can be interpreted as a numpy data type. sizeable : boolean Indicate whether item can be appended/inserted/deleted writeable : boolean Indicate whether content can be changed """ self._sizeable = sizeable self._writeable = writeable if data is not None: if isinstance(data, (list, tuple)): if isinstance(data[0], (list, tuple)): itemsize = [len(l) for l in data] data = [item for sublist in data for item in sublist] self._data = np.array(data, copy=False) self._size = self._data.size # Default is one group with all data inside _itemsize = np.ones(1) * self._data.size # Check item sizes and get items count if itemsize is not None: if isinstance(itemsize, int): if (self._size % itemsize) != 0: raise ValueError("Cannot partition data as requested") self._count = self._size // itemsize _itemsize = np.ones( self._count, dtype=int) * (self._size // self._count) else: _itemsize = np.array(itemsize, copy=False) self._count = len(itemsize) if _itemsize.sum() != self._size: raise ValueError("Cannot partition data as requested") else: self._count = 1 # Store items self._items = np.zeros((self._count, 2), int) C = _itemsize.cumsum() self._items[1:, 0] += C[:-1] self._items[0:, 1] += C else: self._data = np.zeros(1, dtype=dtype) self._items = np.zeros((1, 2), dtype=int) self._size = 0 self._count = 0 @property def data(self): """ The array's elements, in memory. """ return self._data[:self._size] @property def size(self): """ Number of base elements, in memory. """ return self._size @property def itemsize(self): """ Individual item sizes """ return self._items[:self._count, 1] - self._items[:self._count, 0] @property def dtype(self): """ Describes the format of the elements in the buffer. """ return self._data.dtype def reserve(self, capacity): """ Set current capacity of the underlying array""" if capacity >= self._data.size: capacity = int(2 ** np.ceil(np.log2(capacity))) self._data = np.resize(self._data, capacity) def __len__(self): """ x.__len__() <==> len(x) """ return self._count def __str__(self): s = '[ ' for item in self: s += str(item) + ' ' s += ']' return s def __getitem__(self, key): """ x.__getitem__(y) <==> x[y] """ if isinstance(key, int): if key < 0: key += len(self) if key < 0 or key >= len(self): raise IndexError("Tuple index out of range") dstart = self._items[key][0] dstop = self._items[key][1] return self._data[dstart:dstop] elif isinstance(key, slice): istart, istop, step = key.indices(len(self)) if istart > istop: istart, istop = istop, istart dstart = self._items[istart][0] if istart == istop: dstop = dstart else: dstop = self._items[istop - 1][1] return self._data[dstart:dstop] elif isinstance(key, str): return self._data[key][:self._size] elif key is Ellipsis: return self.data else: raise TypeError("List indices must be integers") def __setitem__(self, key, data): """ x.__setitem__(i, y) <==> x[i]=y """ if not self._writeable: raise AttributeError("List is not writeable") if isinstance(key, (int, slice)): if isinstance(key, int): if key < 0: key += len(self) if key < 0 or key > len(self): raise IndexError("List assignment index out of range") dstart = self._items[key][0] dstop = self._items[key][1] istart = key elif isinstance(key, slice): istart, istop, step = key.indices(len(self)) if istart == istop: return if istart > istop: istart, istop = istop, istart if istart > len(self) or istop > len(self): raise IndexError("Can only assign iterable") dstart = self._items[istart][0] if istart == istop: dstop = dstart else: dstop = self._items[istop - 1][1] if hasattr(data, "__len__"): if len(data) == dstop - dstart: # or len(data) == 1: self._data[dstart:dstop] = data else: self.__delitem__(key) self.insert(istart, data) else: # we assume len(data) = 1 if dstop - dstart == 1: self._data[dstart:dstop] = data else: self.__delitem__(key) self.insert(istart, data) elif key is Ellipsis: self.data[...] = data elif isinstance(key, str): self._data[key][:self._size] = data else: raise TypeError("List assignment indices must be integers") def __delitem__(self, key): """ x.__delitem__(y) <==> del x[y] """ if not self._sizeable: raise AttributeError("List is not sizeable") # Deleting a single item if isinstance(key, int): if key < 0: key += len(self) if key < 0 or key > len(self): raise IndexError("List deletion index out of range") istart, istop = key, key + 1 dstart, dstop = self._items[key] # Deleting several items elif isinstance(key, slice): istart, istop, step = key.indices(len(self)) if istart > istop: istart, istop = istop, istart if istart == istop: return dstart = self._items[istart][0] dstop = self._items[istop - 1][1] elif key is Ellipsis: istart = 0 istop = len(self) dstart = 0 dstop = self.size # Error else: raise TypeError("List deletion indices must be integers") # Remove data size = self._size - (dstop - dstart) self._data[ dstart:dstart + self._size - dstop] = self._data[dstop:self._size] self._size -= dstop - dstart # Remove corresponding items size = self._count - istop self._items[istart:istart + size] = self._items[istop:istop + size] # Update other items size = dstop - dstart self._items[istart:istop + size + 1] -= size, size self._count -= istop - istart def insert(self, index, data, itemsize=None): """ Insert data before index Parameters ---------- index : int Index before which data will be inserted. data : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. itemsize: int or 1-D array If `itemsize is an integer, N, the array will be divided into elements of size N. If such partition is not possible, an error is raised. If `itemsize` is 1-D array, the array will be divided into elements whose succesive sizes will be picked from itemsize. If the sum of itemsize values is different from array size, an error is raised. """ if not self._sizeable: raise AttributeError("List is not sizeable") if isinstance(data, (list, tuple)) and isinstance(data[0], (list, tuple)): # noqa itemsize = [len(l) for l in data] data = [item for sublist in data for item in sublist] data = np.array(data, copy=False).ravel() size = data.size # Check item size and get item number if itemsize is not None: if isinstance(itemsize, int): if (size % itemsize) != 0: raise ValueError("Cannot partition data as requested") _count = size // itemsize _itemsize = np.ones(_count, dtype=int) * (size // _count) else: _itemsize = np.array(itemsize, copy=False) _count = len(itemsize) if _itemsize.sum() != size: raise ValueError("Cannot partition data as requested") else: _count = 1 # Check if data array is big enough and resize it if necessary if self._size + size >= self._data.size: capacity = int(2 ** np.ceil(np.log2(self._size + size))) self._data = np.resize(self._data, capacity) # Check if item array is big enough and resize it if necessary if self._count + _count >= len(self._items): capacity = int(2 ** np.ceil(np.log2(self._count + _count))) self._items = np.resize(self._items, (capacity, 2)) # Check index if index < 0: index += len(self) if index < 0 or index > len(self): raise IndexError("List insertion index out of range") # Inserting if index < self._count: istart = index dstart = self._items[istart][0] dstop = self._items[istart][1] # Move data Z = self._data[dstart:self._size] self._data[dstart + size:self._size + size] = Z # Update moved items items = self._items[istart:self._count] + size self._items[istart + _count:self._count + _count] = items # Appending else: dstart = self._size istart = self._count # Only one item (faster) if _count == 1: # Store data self._data[dstart:dstart + size] = data self._size += size # Store data location (= item) self._items[istart][0] = dstart self._items[istart][1] = dstart + size self._count += 1 # Several items else: # Store data dstop = dstart + size self._data[dstart:dstop] = data self._size += size # Store items items = np.ones((_count, 2), int) * dstart C = _itemsize.cumsum() items[1:, 0] += C[:-1] items[0:, 1] += C istop = istart + _count self._items[istart:istop] = items self._count += _count def append(self, data, itemsize=None): """ Append data to the end. Parameters ---------- data : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. itemsize: int or 1-D array If `itemsize is an integer, N, the array will be divided into elements of size N. If such partition is not possible, an error is raised. If `itemsize` is 1-D array, the array will be divided into elements whose succesive sizes will be picked from itemsize. If the sum of itemsize values is different from array size, an error is raised. """ self.insert(len(self), data, itemsize)
[ "numpy.resize", "numpy.log2", "numpy.zeros", "numpy.ones", "numpy.array" ]
[((2573, 2599), 'numpy.array', 'np.array', (['data'], {'copy': '(False)'}), '(data, copy=False)\n', (2581, 2599), True, 'import numpy as np\n'), ((3563, 3594), 'numpy.zeros', 'np.zeros', (['(self._count, 2)', 'int'], {}), '((self._count, 2), int)\n', (3571, 3594), True, 'import numpy as np\n'), ((3747, 3771), 'numpy.zeros', 'np.zeros', (['(1)'], {'dtype': 'dtype'}), '(1, dtype=dtype)\n', (3755, 3771), True, 'import numpy as np\n'), ((3798, 3825), 'numpy.zeros', 'np.zeros', (['(1, 2)'], {'dtype': 'int'}), '((1, 2), dtype=int)\n', (3806, 3825), True, 'import numpy as np\n'), ((4625, 4656), 'numpy.resize', 'np.resize', (['self._data', 'capacity'], {}), '(self._data, capacity)\n', (4634, 4656), True, 'import numpy as np\n'), ((11432, 11463), 'numpy.resize', 'np.resize', (['self._data', 'capacity'], {}), '(self._data, capacity)\n', (11441, 11463), True, 'import numpy as np\n'), ((11687, 11724), 'numpy.resize', 'np.resize', (['self._items', '(capacity, 2)'], {}), '(self._items, (capacity, 2))\n', (11696, 11724), True, 'import numpy as np\n'), ((2722, 2732), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (2729, 2732), True, 'import numpy as np\n'), ((10529, 10555), 'numpy.array', 'np.array', (['data'], {'copy': '(False)'}), '(data, copy=False)\n', (10537, 10555), True, 'import numpy as np\n'), ((10991, 11021), 'numpy.array', 'np.array', (['itemsize'], {'copy': '(False)'}), '(itemsize, copy=False)\n', (10999, 11021), True, 'import numpy as np\n'), ((13022, 13047), 'numpy.ones', 'np.ones', (['(_count, 2)', 'int'], {}), '((_count, 2), int)\n', (13029, 13047), True, 'import numpy as np\n'), ((3248, 3278), 'numpy.array', 'np.array', (['itemsize'], {'copy': '(False)'}), '(itemsize, copy=False)\n', (3256, 3278), True, 'import numpy as np\n'), ((10899, 10925), 'numpy.ones', 'np.ones', (['_count'], {'dtype': 'int'}), '(_count, dtype=int)\n', (10906, 10925), True, 'import numpy as np\n'), ((3107, 3138), 'numpy.ones', 'np.ones', (['self._count'], {'dtype': 'int'}), '(self._count, dtype=int)\n', (3114, 3138), True, 'import numpy as np\n'), ((4580, 4597), 'numpy.log2', 'np.log2', (['capacity'], {}), '(capacity)\n', (4587, 4597), True, 'import numpy as np\n'), ((11378, 11404), 'numpy.log2', 'np.log2', (['(self._size + size)'], {}), '(self._size + size)\n', (11385, 11404), True, 'import numpy as np\n'), ((11629, 11658), 'numpy.log2', 'np.log2', (['(self._count + _count)'], {}), '(self._count + _count)\n', (11636, 11658), True, 'import numpy as np\n')]
import datetime import re import sys from cybox.objects.account_object import Account from cybox.objects.address_object import Address from cybox.objects.archive_file_object import ArchiveFile from cybox.objects.domain_name_object import DomainName from cybox.objects.email_message_object import EmailMessage from cybox.objects.file_object import File from cybox.objects.http_session_object import HostField, HTTPSession from cybox.objects.mutex_object import Mutex from cybox.objects.network_connection_object import NetworkConnection from cybox.objects.network_packet_object import NetworkPacket from cybox.objects.network_socket_object import NetworkSocket from cybox.objects.process_object import Process from cybox.objects.unix_user_account_object import UnixUserAccount from cybox.objects.uri_object import URI from cybox.objects.win_computer_account_object import WinComputerAccount from cybox.objects.win_executable_file_object import WinExecutableFile from cybox.objects.win_process_object import WinProcess from cybox.objects.win_registry_key_object import WinRegistryKey from cybox.objects.win_service_object import WinService from six import text_type import stix2 from stix2.patterns import (_BooleanExpression, _ComparisonExpression, _CompoundObservationExpression, _Constant) import stixmarx from stix2elevator.common import ADDRESS_FAMILY_ENUMERATION, SOCKET_OPTIONS from stix2elevator.convert_cybox import split_into_requests_and_responses from stix2elevator.ids import (add_object_id_value, exists_object_id_key, get_id_value, get_object_id_value) from stix2elevator.options import error, info, warn from stix2elevator.utils import identifying_info, map_vocabs_to_label from stix2elevator.vocab_mappings import WINDOWS_PEBINARY if sys.version_info > (3,): long = int KEEP_OBSERVABLE_DATA_USED_IN_PATTERNS = False KEEP_INDICATORS_USED_IN_COMPOSITE_INDICATOR_EXPRESSION = True class ComparisonExpressionForElevator(_ComparisonExpression): # overrides, so IdrefPlaceHolder can be handled def __init__(self, operator, lhs, rhs, negated=False): self.operator = operator if operator == "=" and isinstance(rhs, stix2.ListConstant): warn("apply_condition assumed to be 'ANY' in %s", 721, identifying_info(get_dynamic_variable("current_observable"))) self.operator = "IN" if isinstance(lhs, stix2.ObjectPath): self.lhs = lhs else: self.lhs = stix2.ObjectPath.make_object_path(lhs) # rhs might be a reference to another object, which has its own observable pattern if isinstance(rhs, _Constant) or isinstance(rhs, IdrefPlaceHolder): self.rhs = rhs else: self.rhs = make_constant(rhs) self.negated = negated self.root_type = self.lhs.object_type_name def contains_placeholder(self): return isinstance(self.rhs, IdrefPlaceHolder) def collapse_reference(self, prefix): new_lhs = prefix.merge(self.lhs) new_lhs.collapsed = True return ComparisonExpressionForElevator(self.operator, new_lhs, self.rhs) def replace_placeholder_with_idref_pattern(self, idref): if isinstance(self.rhs, IdrefPlaceHolder): change_made, pattern = self.rhs.replace_placeholder_with_idref_pattern(idref) if change_made: if hasattr(self.lhs, "collapsed") and self.lhs.collapsed: return True, ComparisonExpressionForElevator(pattern.operator, self.lhs, pattern.rhs) else: return True, pattern.collapse_reference(self.lhs) return False, self def partition_according_to_object_path(self): return self def contains_unconverted_term(self): return False class BooleanExpressionForElevator(_BooleanExpression): def add_operand(self, operand): self.operands.append(operand) def contains_placeholder(self): for args in self.operands: if args.contains_placeholder(): return True return False def replace_placeholder_with_idref_pattern(self, idref): new_operands = [] change_made = False for args in self.operands: change_made_this_time, new_operand = args.replace_placeholder_with_idref_pattern(idref) if change_made_this_time: if not hasattr(self, "root_type"): self.root_type = new_operand.root_type elif self.root_type and hasattr(new_operand, "root_type") and (self.root_type != new_operand.root_type): self.root_type = None change_made = change_made or change_made_this_time new_operands.append(new_operand) self.operands = new_operands return change_made, self def collapse_reference(self, prefix): new_operands = [] for operand in self.operands: new_operands.append(operand.collapse_reference(prefix)) return BooleanExpressionForElevator(self.operator, new_operands) def partition_according_to_object_path(self): subexpressions = [] results = [] for term in self.operands: term_was_appended = False for sub in subexpressions: if not hasattr(term, "root_type") and not hasattr(sub[0], "root_type"): sub.append(term) term_was_appended = True break elif hasattr(term, "root_type") and hasattr(sub[0], "root_type") and term.root_type == sub[0].root_type: sub.append(term) term_was_appended = True break if not term_was_appended: subexpressions.append([term]) for x in subexpressions: if len(x) == 1: results.append(x[0]) else: results.append(create_boolean_expression(self.operator, x)) if len(results) == 1: return results[0] else: return ObservableExpressionForElevator(self.operator, results) def contains_unconverted_term(self): for args in self.operands: if args.contains_unconverted_term(): return True return False class IdrefPlaceHolder(object): def __init__(self, idref): self.idref = idref def __str__(self): return "PLACEHOLDER:" + self.idref def contains_placeholder(self): return True def replace_placeholder_with_idref_pattern(self, idref): if idref == self.idref: return True, get_pattern_from_cache(idref) elif exists_object_id_key(self.idref) and idref == get_object_id_value(self.idref): return True, get_pattern_from_cache(idref) else: return False, self def partition_according_to_object_path(self): error("Placeholder %s should be resolved", 203, self.idref) return self def contains_unconverted_term(self): return False class UnconvertedTerm(object): def __init__(self, term_info): self.term_info = term_info def __str__(self): return "unconverted_term:%s" % self.term_info def contains_placeholder(self): return False def replace_placeholder_with_idref_pattern(self, idref): return False, self def partition_according_to_object_path(self): return self def contains_unconverted_term(self): return True class ObservableExpressionForElevator(_CompoundObservationExpression): def __str__(self): sub_exprs = [] if len(self.operands) == 1: return "[%s]" % self.operands[0] for o in self.operands: sub_exprs.append("[%s]" % o) return (" " + self.operator + " ").join(sub_exprs) def contains_placeholder(self): for args in self.operands: if args.contains_placeholder(): error("Observable Expressions should not contain placeholders", 202) def contains_unconverted_term(self): for args in self.operands: if args.contains_unconverted_term(): return True return False def partition_according_to_object_path(self): return self class ParentheticalExpressionForElevator(stix2.ParentheticalExpression): def contains_placeholder(self): return self.expression.contains_placeholder() def contains_unconverted_term(self): return self.expression.contains_unconverted_term() def replace_placeholder_with_idref_pattern(self, idref): change_made, new_expression = self.expression.replace_placeholder_with_idref_pattern(idref) self.expression = new_expression if hasattr(new_expression, "root_type"): self.root_type = new_expression.root_type return change_made, self def collapse_reference(self, prefix): new_expression = self.expression.collapse_reference(prefix) return ParentheticalExpressionForElevator(new_expression) def partition_according_to_object_path(self): self.expression = self.expression.partition_according_to_object_path() return self def create_boolean_expression(operator, operands): if len(operands) == 1: return operands[0] exp = BooleanExpressionForElevator(operator, []) for arg in operands: if not isinstance(arg, IdrefPlaceHolder) and not isinstance(arg, UnconvertedTerm) and hasattr(arg, "root_type"): if not hasattr(exp, "root_type"): exp.root_type = arg.root_type elif exp.root_type and (exp.root_type != arg.root_type): exp.root_type = None exp.add_operand(arg) return ParentheticalExpressionForElevator(exp) ################### _PATTERN_CACHE = {} def clear_pattern_cache(): global _PATTERN_CACHE _PATTERN_CACHE = {} def add_to_pattern_cache(key, pattern): global _PATTERN_CACHE if pattern: _PATTERN_CACHE[key] = pattern def id_in_pattern_cache(id_): return id_ in _PATTERN_CACHE def get_pattern_from_cache(id_): return _PATTERN_CACHE[id_] def get_ids_from_pattern_cache(): return _PATTERN_CACHE.keys() def get_items_from_pattern_cache(): return _PATTERN_CACHE.items() def pattern_cache_is_empty(): return _PATTERN_CACHE == {} ########### _OBSERVABLE_MAPPINGS = {} def add_to_observable_mappings(obs): global _OBSERVABLE_MAPPINGS if obs: _OBSERVABLE_MAPPINGS[obs.id_] = obs _OBSERVABLE_MAPPINGS[obs.object_.id_] = obs def id_in_observable_mappings(id_): return id_ in _OBSERVABLE_MAPPINGS def get_obs_from_mapping(id_): return _OBSERVABLE_MAPPINGS[id_] def clear_observable_mappings(): global _OBSERVABLE_MAPPINGS _OBSERVABLE_MAPPINGS = {} # simulate dynamic variable environment _DYNAMIC_SCOPING_ENV = {} def intialize_dynamic_variable(var): global _DYNAMIC_SCOPING_ENV if var in _DYNAMIC_SCOPING_ENV: raise Exception else: _DYNAMIC_SCOPING_ENV[var] = [] def set_dynamic_variable(var, value): global _DYNAMIC_SCOPING_ENV if var not in _DYNAMIC_SCOPING_ENV: intialize_dynamic_variable(var) _DYNAMIC_SCOPING_ENV[var].append(value) def get_dynamic_variable(var): if var not in _DYNAMIC_SCOPING_ENV: raise Exception else: return _DYNAMIC_SCOPING_ENV[var][-1] def pop_dynamic_variable(var): if var not in _DYNAMIC_SCOPING_ENV or not _DYNAMIC_SCOPING_ENV[var]: raise Exception else: _DYNAMIC_SCOPING_ENV[var].pop _CLASS_NAME_MAPPING = {"File": "file", "URI": "uri", "EmailMessage": "email-message", "WinRegistryKey": "windows-registry-key", "Process": "process", "DomainName": "domain-name", "Mutex": "mutex", "WinExecutableFile": "file:extensions.'windows-pebinary-ext'", "ArchiveFile": "file:extensions.'archive-ext'", "NetworkConnection": "network-traffic"} _ADDRESS_NAME_MAPPING = {Address.CAT_IPV4: "ipv4-addr", Address.CAT_IPV6: "ipv6-addr", Address.CAT_MAC: "mac-addr", Address.CAT_EMAIL: "email-addr"} # address, network_connection def convert_cybox_class_name_to_object_path_root_name(instance): class_name = instance.__class__.__name__ if class_name in _CLASS_NAME_MAPPING: return _CLASS_NAME_MAPPING[class_name] elif class_name == "Address" and instance.category in _ADDRESS_NAME_MAPPING: return _ADDRESS_NAME_MAPPING[class_name] else: error("Cannot convert CybOX 2.x class name %s to an object_path_root_name", 813, class_name) return None def need_not(condition): return condition == "DoesNotContain" def is_equal_condition(cond): return cond == "Equals" or cond is None def add_parens_if_needed(expr): if expr.find("AND") != -1 or expr.find("OR") != -1: return "(" + expr + ")" else: return expr _CONDITION_OPERATOR_MAP = { 'Equals': "=", "DoesNotEqual": "!=", "Contains": "=", "DoesNotContain": "!=", "GreaterThan": ">", 'GreaterThanOrEqual': ">=", "LessThan": "<", "LessThanOrEqual": "<=" # StartsWith - handled in create_term_with_regex # EndsWith - handled in create_term_with_regex # InclusiveBetween - handled in create_term_with_range # ExclusiveBetween - handled in create_term_with_range # FitsPattern # BitwiseAnd # BitwiseOr } def convert_condition(condition): if condition is None: warn("No condition given for %s - assume '='", 714, identifying_info(get_dynamic_variable("current_observable"))) return "=" for cond, op in _CONDITION_OPERATOR_MAP.items(): if cond.lower() == condition.lower(): if cond != condition: warn("'%s' allowed in %s - should be '%s'", 630, condition, identifying_info(get_dynamic_variable("current_observable")), cond) return op warn("Unknown condition given in %s - marked as 'INVALID_CONDITION'", 628, identifying_info(get_dynamic_variable("current_observable"))) return "INVALID-CONDITION" def process_boolean_negation(op, negated): if not negated: return op elif op == "AND": return "OR" elif op == "OR": return "AND" else: raise (ValueError("not a legal Boolean op: %s" % op)) def process_comparison_negation(op, negated): if not negated: return op elif op == "=": return "!=" elif op == "!=": return "=" elif op == "<": return ">=" elif op == "<=": return ">" elif op == ">": return "<=" elif op == ">=": return "<" else: raise (ValueError("not a legal Comparison op: %s" % op)) def create_term_with_regex(lhs, condition, rhs, negated): # TODO: escape characters if condition == "StartsWith": rhs.value = "^%s" % rhs.value elif condition == "EndsWith": rhs.value = "$%s" % rhs.value return ComparisonExpressionForElevator("MATCHES", lhs, rhs, negated) def create_term_with_range(lhs, condition, rhs, negated=False): # TODO: handle negated if not isinstance(rhs, stix2.ListConstant) or len(rhs.value) != 2: error("%s was used, but two values were not provided.", 609, condition) return "'range term underspecified'" else: if condition == "InclusiveBetween": # return "(" + lhs + " GE " + text_type(rhs[0]) + " AND " + lhs + " LE " + text_type(rhs[1]) + ")" lower_bound = ComparisonExpressionForElevator(process_comparison_negation(">=", negated), lhs, rhs.value[0]) upper_bound = ComparisonExpressionForElevator(process_comparison_negation("<=", negated), lhs, rhs.value[1]) else: # "ExclusiveBetween" # return "(" + lhs + " GT " + text_type(rhs[0]) + " AND " + lhs + " LT " + text_type(rhs[1]) + ")" lower_bound = ComparisonExpressionForElevator(process_comparison_negation(">", negated), lhs, rhs.value[0]) upper_bound = ComparisonExpressionForElevator(process_comparison_negation("<", negated), lhs, rhs.value[1]) return create_boolean_expression(process_boolean_negation("AND", negated), [lower_bound, upper_bound]) def multi_valued_property(object_path): return object_path and object_path.find("*") != -1 def negate_if_needed(condition, negated): if negated: return "NOT " + condition else: return condition def create_term(lhs, condition, rhs, negated=False): if condition == "StartsWith" or condition == "EndsWith": return create_term_with_regex(lhs, condition, rhs, negated) elif condition == "InclusiveBetween" or condition == "ExclusiveBetween": return create_term_with_range(lhs, condition, rhs, negated) else: if condition == "Contains" and not multi_valued_property(lhs): warn("Used MATCHES operator for %s", 715, condition) return create_term_with_regex(lhs, condition, rhs, negated) elif condition == "DoesNotContain": warn("Used MATCHES operator for %s", 715, condition) return create_term_with_regex(lhs, condition, rhs, not negated) # return lhs + " " + negate_if_needed(convert_condition(condition), negated) + " '" + convert_to_text_type(rhs) + "'" return ComparisonExpressionForElevator(convert_condition(condition), lhs, rhs, negated) def make_constant(obj): # TODO: handle other Markable objects? if isinstance(obj, bool): return stix2.BooleanConstant(obj) elif isinstance(obj, int) or isinstance(obj, long): return stix2.IntegerConstant(obj) elif isinstance(obj, float): return stix2.FloatConstant(obj) elif isinstance(obj, str) or isinstance(obj, stixmarx.api.types.MarkableText): return stix2.StringConstant(obj.strip()) elif isinstance(obj, list): return stix2.ListConstant([make_constant(x) for x in obj]) elif isinstance(obj, datetime.datetime) or isinstance(obj, stixmarx.api.types.MarkableDateTime): return stix2.TimestampConstant(obj.strftime("%Y-%m-%dT%H:%M:%S.%fZ")) else: raise ValueError("Can't make a constant from %s" % obj) def add_comparison_expression(prop, object_path): if prop is not None and prop.value is not None: if hasattr(prop, "condition"): cond = prop.condition else: warn("No condition given - assume '='", 714) cond = None return create_term(object_path, cond, make_constant(prop.value)) if prop is not None and prop.value is None: warn("No term was yielded for %s", 622, object_path) return None def convert_custom_properties(cps, object_type_name): expressions = [] for cp in cps.property_: if not re.match("[a-z0-9_]+", cp.name): warn("The custom property name %s does not adhere to the specification rules", 617, cp.name) if " " in cp.name: warn("The custom property name %s contains whitespace, replacing it with underscores", 624, cp.name) expressions.append( create_term(object_type_name + ":x_" + cp.name.replace(" ", "_"), cp.condition, make_constant(cp.value))) return create_boolean_expression("AND", expressions) _ACCOUNT_PROPERTIES = [ ["full_name", "user-account:display_name"], ["last_login", "user-account:account_last_login"], ["username", "user-account:account_login"], ["creation_time", "user-account:account_created"] ] def convert_account_to_pattern(account): expressions = [] if hasattr(account, "disabled") and account.disabled: expressions.append(create_term("user-account:is_disabled", "Equals", stix2.BooleanConstant(account.disabled))) for prop_spec in _ACCOUNT_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(account, prop_1x) and getattr(account, prop_1x): term = add_comparison_expression(getattr(account, prop_1x), object_path) if term: expressions.append(term) if isinstance(account, UnixUserAccount): win_process_expression = convert_unix_user_to_pattern(account) if win_process_expression: expressions.append(win_process_expression) else: warn("No UnixUserAccount properties found in %s", 615, text_type(account)) elif isinstance(account, WinComputerAccount): expressions.append(create_term("user-account:account_type", "Equals", stix2.StringConstant("windows-domain" if account.domain else "windows-local"))) if expressions: return create_boolean_expression("AND", expressions) _UNIX_ACCOUNT_PROPERTIES = [ ["group_id", "user-account:extensions.'unix-account-ext'.gid"], ["login_shell", "user-account:extensions.'unix-account-ext'.shell"], ["home_directory", "user-account:extensions.'unix-account-ext'.home_dir"], ] def convert_unix_user_to_pattern(account): expressions = [] expressions.append(create_term("user-account:account_type", "Equals", stix2.StringConstant("unix"))) if hasattr(account, "user_id") and account.user_id: expressions.append(create_term("user-account:user_id", account.user_id.condition, stix2.StringConstant(text_type(account.user_id.value)))) for prop_spec in _UNIX_ACCOUNT_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(account, prop_1x) and getattr(account, prop_1x): term = add_comparison_expression(getattr(account, prop_1x), object_path) if term: expressions.append(term) if expressions: return create_boolean_expression("AND", expressions) def convert_address_to_pattern(add): cond = add.address_value.condition if add.category == add.CAT_IPV4: return create_term("ipv4-addr:value", cond, make_constant(add.address_value.value.strip())) elif add.category == add.CAT_IPV6: return create_term("ipv6-addr:value", cond, make_constant(add.address_value.value.strip())) elif add.category == add.CAT_MAC: return create_term("mac-addr:value", cond, make_constant(add.address_value.value.strip())) elif add.category == add.CAT_EMAIL: return create_term("email-addr:value", cond, make_constant(add.address_value.value.strip())) else: warn("The address type %s is not part of Cybox 3.0", 421, add.category) def convert_uri_to_pattern(uri): return create_term("url:value", uri.value.condition, make_constant(uri.value.value.strip())) # NOTICE: The format of these PROPERTIES is different than the others in this file!!!!!! _EMAIL_HEADER_PROPERTIES = [["email-message:subject", ["subject"]], ["email-message:from_ref.value", ["from_", "address_value"]], ["email-message:sender_ref.value", ["sender", "address_value"]], ["email-message:date", ["date"]], ["email-message:content_type", ["content_type"]], ["email-message:to_refs[*].value", ["to*", "address_value"]], ["email-message:cc_refs[*].value", ["cc*", "address_value"]], ["email-message:bcc_refs[*].value", ["bcc*", "address_value"]]] _EMAIL_ADDITIONAL_HEADERS_PROPERTIES = \ [["email-message:additional_header_fields.Reply-To", ["reply-to*", "address_value"]], ["email-message:additional_header_fields.Message-ID", ["message_id"]], ["email-message:additional_header_fields.In-Reply-To", ["in_reply_to"]], ["email-message:additional_header_fields.Errors-To", ["errors_to"]], ["email-message:additional_header_fields.MIME-Version", ["mime_version"]], ["email-message:additional_header_fields.Precedence", ["precedence"]], ["email-message:additional_header_fields.User-Agent", ["user_agent"]], ["email-message:additional_header_fields.Boundary", ["boundary"]], ["email-message:additional_header_fields.X-Originating-IP", ["x_originating_ip", "address_value"]], ["email-message:additional_header_fields.X-Priority", ["x_priority"]], ["email-message:additional_header_fields.X-Mailer", ["x_mailer"]]] def cannonicalize_prop_name(name): if name.find("*") == -1: return name else: return name[:-1] def create_terms_from_prop_list(prop_list, obj, object_path): if len(prop_list) == 1: prop_1x = prop_list[0] if hasattr(obj, cannonicalize_prop_name(prop_1x)): if multi_valued_property(prop_1x): prop_exprs = [] for c in getattr(obj, cannonicalize_prop_name(prop_1x)): term = add_comparison_expression(c, object_path) if term: prop_exprs.append(term) # return " OR ".join(prop_exprs) if prop_exprs: return create_boolean_expression("OR", prop_exprs) else: return add_comparison_expression(getattr(obj, cannonicalize_prop_name(prop_1x)), object_path) else: prop_1x, rest_of_prop_list = prop_list[0], prop_list[1:] if hasattr(obj, cannonicalize_prop_name(prop_1x)): if multi_valued_property(prop_1x): prop_exprs = [] values = getattr(obj, cannonicalize_prop_name(prop_1x)) if values: for c in values: term = create_terms_from_prop_list(rest_of_prop_list, c, object_path) if term: prop_exprs.append(term) # return " OR ".join(prop_exprs) if prop_exprs: return create_boolean_expression("OR", prop_exprs) else: return create_terms_from_prop_list(rest_of_prop_list, getattr(obj, cannonicalize_prop_name(prop_1x)), object_path) def convert_email_header_to_pattern(head, properties): header_expressions = [] for prop_spec in properties: object_path = prop_spec[0] prop_1x_list = prop_spec[1] if hasattr(head, cannonicalize_prop_name(prop_1x_list[0])): term = create_terms_from_prop_list(prop_1x_list, head, object_path) if term: header_expressions.append(term) if head.received_lines: warn("Email received lines not handled yet", 806) if header_expressions: return create_boolean_expression("AND", header_expressions) def convert_attachment_to_ref(attachment): return IdrefPlaceHolder(attachment.object_reference) def convert_email_message_to_pattern(mess): expressions = [] if mess.header is not None: expressions.append(convert_email_header_to_pattern(mess.header, _EMAIL_HEADER_PROPERTIES)) add_headers = convert_email_header_to_pattern(mess.header, _EMAIL_ADDITIONAL_HEADERS_PROPERTIES) if add_headers: expressions.append(add_headers) if mess.attachments is not None: for attachment in mess.attachments: expressions.append(ComparisonExpressionForElevator("=", "email-message:body_multipart[*].body_raw_ref", convert_attachment_to_ref(attachment))) if mess.raw_body is not None: if not mess.raw_body.value: warn("%s contains no value", 621, "Email raw body") else: warn("Email raw body not handled yet", 806) if mess.links is not None: warn("Email links not handled yet", 806) if expressions: return create_boolean_expression("AND", expressions) _PE_FILE_HEADER_PROPERTIES = \ [["machine", "file:extensions.'windows-pebinary-ext'.file_header:machine_hex"], ["time_date_stamp", "file:extensions.'windows-pebinary-ext'.file_header.time_date_stamp"], ["number_of_sections", "file:extensions.'windows-pebinary-ext'.file_header.number_of_sections"], ["pointer_to_symbol_table", "file:extensions.'windows-pebinary-ext'.file_header.pointer_to_symbol_table"], ["number_of_symbols", "file:extensions.'windows-pebinary-ext'.file_header.number_of_symbols"], ["size_of_optional_header", "file:extensions.'windows-pebinary-ext'.file_header.size_of_optional_header"], ["characteristics", "file:extensions.'windows-pebinary-ext'.file_header.characteristics_hex"]] _PE_SECTION_HEADER_PROPERTIES = [["name", "file:extensions.'windows-pebinary-ext'.section[*].name"], ["virtual_size", "file:extensions.'windows-pebinary-ext'.section[*].size"]] _ARCHIVE_FILE_PROPERTIES = [["comment", "file:extensions.'archive-ext'.comment"], ["version", "file:extensions.'archive-ext'.version"]] def convert_windows_executable_file_to_pattern(f): expressions = [] if f.headers: file_header = f.headers.file_header if file_header: file_header_expressions = [] for prop_spec in _PE_FILE_HEADER_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(file_header, prop_1x) and getattr(file_header, prop_1x): term = add_comparison_expression(getattr(file_header, prop_1x), object_path) if term: file_header_expressions.append(term) if file_header.hashes is not None: hash_expression = convert_hashes_to_pattern(file_header.hashes) if hash_expression: file_header_expressions.append(hash_expression) if file_header_expressions: expressions.append(create_boolean_expression("AND", file_header_expressions)) if f.headers.optional_header: warn("file:extensions:'windows-pebinary-ext':optional_header is not implemented yet", 807) if f.type_: expressions.append(create_term("file:extensions.'windows-pebinary-ext'.pe_type", f.type_.condition, stix2.StringConstant(map_vocabs_to_label(f.type_.value, WINDOWS_PEBINARY)))) sections = f.sections if sections: sections_expressions = [] # should order matter in patterns??? for s in sections: section_expressions = [] if s.section_header: for prop_spec in _PE_SECTION_HEADER_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(s.section_header, prop_1x) and getattr(s.section_header, prop_1x): term = add_comparison_expression(getattr(s.section_header, prop_1x), object_path) if term: section_expressions.append(term) if s.entropy: if s.entropy.min: warn("Entropy.min is not supported in STIX 2.0", 424) if s.entropy.min: warn("Entropy.max is not supported in STIX 2.0", 424) if s.entropy.value: section_expressions.append(create_term("file:extensions.'windows-pebinary-ext'.section[*].entropy", s.entropy.value.condition, stix2.FloatConstant(s.entropy.value.value))) if s.data_hashes: section_expressions.append(convert_hashes_to_pattern(s.data_hashes)) if s.header_hashes: section_expressions.append(convert_hashes_to_pattern(s.header_hashes)) if section_expressions: sections_expressions.append(create_boolean_expression("AND", section_expressions)) if sections_expressions: expressions.append(create_boolean_expression("AND", sections_expressions)) if f.exports: warn("The exports property of WinExecutableFileObj is not part of STIX 2.0", 418) expressions.append(UnconvertedTerm("WinExecutableFileObj.exports")) if f.imports: warn("The imports property of WinExecutableFileObj is not part of STIX 2.0", 419) expressions.append(UnconvertedTerm("WinExecutableFileObj.imports")) if expressions: return create_boolean_expression("AND", expressions) def convert_archive_file_to_pattern(f): and_expressions = [] for prop_spec in _ARCHIVE_FILE_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(f, prop_1x): term = add_comparison_expression(getattr(f, prop_1x), object_path) if term: and_expressions.append(term) if and_expressions: return create_boolean_expression("AND", and_expressions) def convert_hashes_to_pattern(hashes): hash_expressions = [] for h in hashes: if getattr(h, "simple_hash_value"): hash_value = h.simple_hash_value else: hash_value = h.fuzzy_hash_value if text_type(h.type_).startswith("SHA"): hash_type = "'" + "SHA" + "-" + text_type(h.type_)[3:] + "'" elif text_type(h.type_) == "SSDEEP": hash_type = text_type(h.type_).lower() else: hash_type = text_type(h.type_) try: hc = stix2.HashConstant(hash_value.value, text_type(h.type_)) except ValueError as err: # don't cause exception if hash value isn't correct warn(err.message, 626) hc = make_constant(hash_value.value) hash_expressions.append(create_term("file:hashes" + "." + hash_type, hash_value.condition, hc)) if hash_expressions: return create_boolean_expression("OR", hash_expressions) def convert_file_name_and_file_extension(file_name, file_extension): if (file_extension and file_extension.value and is_equal_condition(file_name.condition) and is_equal_condition(file_extension.condition) and file_name.value.endswith(file_extension.value)): return create_term("file:name", file_name.condition, make_constant(file_name.value)) elif (file_name.condition == "StartsWith" and file_extension and file_extension.value and is_equal_condition(file_extension.condition)): return ComparisonExpressionForElevator("MATCHES", "file:name", make_constant( "^" + file_name.value + "*." + file_extension.value + "$")) elif (file_name.condition == "Contains" and file_extension and file_extension.value and is_equal_condition(file_extension.condition)): return ComparisonExpressionForElevator("MATCHES", "file:name", make_constant( file_name.value + "*." + file_extension.value + "$")) else: warn("Unable to create a pattern for file:file_name from a File object", 620) def convert_file_name_and_path_to_pattern(f): file_name_path_expressions = [] if f.file_name and f.file_extension and f.file_extension.value: file_name_path_expressions.append(convert_file_name_and_file_extension(f.file_name, f.file_extension)) elif f.file_name: file_name_path_expressions.append(create_term("file:name", f.file_name.condition, make_constant(f.file_name.value))) if f.file_path and f.file_path.value: index = f.file_path.value.rfind("/") if index == -1: index = f.file_path.value.rfind("\\") if index == -1: warn("Ambiguous file path '%s' was not processed", 816, f.file_path.value) else: if not (f.file_path.value.endswith("/") or f.file_path.value.endswith("\\")): file_name_path_expressions.append(create_term("file:name", f.file_path.condition, make_constant(f.file_path.value[index + 1:]))) path_string_constant = make_constant(((f.device_path.value if f.device_path else "") + f.file_path.value[0: index])) file_name_path_expressions.append(create_term("file:parent_directory_ref.path", f.file_path.condition, path_string_constant)) else: path_string_constant = make_constant(((f.device_path.value if f.device_path else "") + f.file_path.value[0: index])) file_name_path_expressions.append(create_term("directory:path", f.file_path.condition, path_string_constant)) if f.full_path: warn("1.x full file paths are not processed, yet", 802) if file_name_path_expressions: return create_boolean_expression("AND", file_name_path_expressions) _FILE_PROPERTIES = [["size_in_bytes", "file:size"], ["magic_number", "file:magic_number_hex"], ["created_time", "file:created"], ["modified_time", "file:modified"], ["accessed_time", "file:accessed"], ["encyption_algorithm", "file:encyption_algorithm"], ["decryption_key", "file:decryption_key"]] def convert_file_to_pattern(f): expressions = [] if f.hashes is not None: hash_expression = convert_hashes_to_pattern(f.hashes) if hash_expression: expressions.append(hash_expression) file_name_and_path_expression = convert_file_name_and_path_to_pattern(f) if file_name_and_path_expression: expressions.append(file_name_and_path_expression) properties_expressions = [] for prop_spec in _FILE_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(f, prop_1x) and getattr(f, prop_1x): term = add_comparison_expression(getattr(f, prop_1x), object_path) if term: properties_expressions.append(term) if properties_expressions: expressions.extend(properties_expressions) if isinstance(f, WinExecutableFile): windows_executable_file_expression = convert_windows_executable_file_to_pattern(f) if windows_executable_file_expression: expressions.append(windows_executable_file_expression) else: warn("No WinExecutableFile properties found in %s", 613, text_type(f)) if isinstance(f, ArchiveFile): archive_file_expressions = convert_archive_file_to_pattern(f) if archive_file_expressions: expressions.append(archive_file_expressions) else: warn("No ArchiveFile properties found in %s", 614, text_type(f)) if expressions: return create_boolean_expression("AND", expressions) _REGISTRY_KEY_VALUES_PROPERTIES = [["data", "windows-registry-key:values[*].data"], ["name", "windows-registry-key:values[*].name"], ["datatype", "windows-registry-key:values[*].data_type"]] def convert_registry_key_to_pattern(reg_key): expressions = [] if reg_key.key: key_value_term = "" if reg_key.hive: if reg_key.hive.condition is None or is_equal_condition(reg_key.hive.condition): key_value_term += reg_key.hive.value + "\\" else: warn("Condition %s on a hive property not handled", 812, reg_key.hive.condition) if reg_key.key.value.startswith(reg_key.hive.value): warn("Hive property, %s, is already a prefix of the key property, %s", 623, reg_key.hive.value, reg_key.key.value) key_value_term = reg_key.key.value else: key_value_term += reg_key.key.value else: key_value_term = reg_key.key.value expressions.append(create_term("windows-registry-key:key", reg_key.key.condition, make_constant(key_value_term))) if reg_key.values: values_expressions = [] for v in reg_key.values: value_expressions = [] for prop_spec in _REGISTRY_KEY_VALUES_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(v, prop_1x) and getattr(v, prop_1x): term = add_comparison_expression(getattr(v, prop_1x), object_path) if term: value_expressions.append(term) if value_expressions: values_expressions.append(create_boolean_expression("OR", value_expressions)) expressions.extend(values_expressions) if expressions: return create_boolean_expression("AND", expressions) def convert_image_info_to_pattern(image_info): expressions = [] if image_info.command_line: expressions.append(add_comparison_expression(image_info.command_line, "process:command_line")) if image_info.current_directory: expressions.append(add_comparison_expression(image_info.current_directory, "process:cwd")) if expressions: return create_boolean_expression("AND", expressions) _PROCESS_PROPERTIES = [ ["is_hidden", "process:is_hidden"], ["pid", "process:pid"], ["name", "process:name"], ["parent_pid", "process:parent_ref.pid"], ["username", "process:creator_user_ref.user_id"], ["creation_time", "process:created"] ] def convert_process_to_pattern(process): expressions = [] for prop_spec in _PROCESS_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(process, prop_1x) and getattr(process, prop_1x): term = add_comparison_expression(getattr(process, prop_1x), object_path) if term: expressions.append(term) if process.image_info: process_info = convert_image_info_to_pattern(process.image_info) if process_info: expressions.append(process_info) if hasattr(process, "argument_list") and process.argument_list: argument_expressions = [] for a in process.argument_list: argument_expressions.append(create_term("process:arguments[*]", a.condition, stix2.StringConstant(a.value))) if argument_expressions: expressions.append(create_boolean_expression("AND", argument_expressions)) if hasattr(process, "environment_variable_list") and process.environment_variable_list: ev_expressions = [] for ev in process.environment_variable_list: # TODO: handle variable names with '-' ev_expressions.append(create_term("process:environment_variables[*]." + str(ev.name), ev.value.condition, stix2.StringConstant(str(ev.value)))) if ev_expressions: expressions.append(create_boolean_expression("AND", ev_expressions)) if hasattr(process, "child_pid_list") and process.child_pid_list: child_pids_expressions = [] for cp in process.child_pid_list: child_pids_expressions.append(create_term("process:child_refs[*].pid", cp.condition, stix2.IntegerConstant(cp.value))) if child_pids_expressions: expressions.append(create_boolean_expression("AND", child_pids_expressions)) if hasattr(process, "network_connection_list") and process.network_connection_list: network_connection_expressions = [] for nc in process.network_connection_list: new_pattern = convert_network_connection_to_pattern(nc) network_connection_expressions.append( new_pattern.collapse_reference(stix2.ObjectPath.make_object_path("process:opened_connection_refs[*]"))) if network_connection_expressions: expressions.append(create_boolean_expression("AND", network_connection_expressions)) if isinstance(process, WinProcess): win_process_expression = convert_windows_process_to_pattern(process) if win_process_expression: expressions.append(win_process_expression) else: warn("No WinProcess properties found in %s", 615, text_type(process)) if isinstance(process, WinService): service_expression = convert_windows_service_to_pattern(process) if service_expression: expressions.append(service_expression) else: warn("No WinService properties found in %s", 616, text_type(process)) if expressions: return create_boolean_expression("AND", expressions) _WINDOWS_PROCESS_PROPERTIES = [ ["aslr_enabled", "process:extensions.'windows-process-ext'.aslr_enabled"], ["dep_enabled", "process:extensions.'windows-process-ext'.dep_enabled"], ["priority", "process:extensions.'windows-process-ext'.priority"], ["security_id", "process:extensions.'windows-process-ext'.owner_sid"], ["window_title", "process:extensions.'windows-process-ext'.window_title"] ] def convert_windows_process_to_pattern(process): expressions = [] for prop_spec in _WINDOWS_PROCESS_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(process, prop_1x) and getattr(process, prop_1x): term = add_comparison_expression(getattr(process, prop_1x), object_path) if term: expressions.append(term) if process.handle_list: for h in process.handle_list: warn("Windows Handles are not a part of STIX 2.0", 420) if process.startup_info: warn("process:startup_info not handled yet", 803) if expressions: return create_boolean_expression("AND", expressions) _WINDOWS_SERVICE_PROPERTIES = \ [["service_name", "process:extensions.'windows-service-ext'.service_name"], ["display_name", "process:extensions.'windows-service-ext'.display_name"], ["startup_command_line", "process:extensions.'windows-service-ext'.startup_command_line"], ["start_type", "process:extensions.'windows-service-ext'.start_type"], ["service_type", "process:extensions.'windows-service-ext'.service_type"], ["service_status", "process:extensions.'windows-service-ext'.service_status"]] def convert_windows_service_to_pattern(service): expressions = [] for prop_spec in _WINDOWS_SERVICE_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(service, prop_1x) and getattr(service, prop_1x): term = add_comparison_expression(getattr(service, prop_1x), object_path) if term: expressions.append(term) if hasattr(service, "description_list") and service.description_list: description_expressions = [] for d in service.description_list: description_expressions.append(create_term("process:extensions.'windows-service-ext'.descriptions[*]", d.condition, make_constant(d.value))) if description_expressions: expressions.append(create_boolean_expression("OR", description_expressions)) if hasattr(service, "service_dll") and service.service_dll: warn("WinServiceObject.service_dll is not handled, yet.", 804) expressions.append(UnconvertedTerm("WinServiceObject.service_dll")) if expressions: return create_boolean_expression("AND", expressions) def convert_related_object_to_pattern(ro): if ro.id_: new_pattern = convert_object_to_pattern(ro, ro.id_) if new_pattern: add_to_pattern_cache(ro.id_, new_pattern) return new_pattern elif ro.idref: if id_in_pattern_cache(ro.idref): return get_pattern_from_cache(ro.idref) else: if id_in_observable_mappings(ro.idref): return convert_observable_to_pattern(get_obs_from_mapping(ro.idref)) return IdrefPlaceHolder(ro.idref) def convert_domain_name_to_pattern(domain_name, related_objects): pattern = [ create_term("domain-name:value", domain_name.value.condition, make_constant(domain_name.value.value))] if related_objects: for ro in related_objects: if ro.relationship == "Resolved_To": new_pattern = convert_related_object_to_pattern(ro) if new_pattern: if isinstance(new_pattern, IdrefPlaceHolder): pattern.append(ComparisonExpressionForElevator("=", "domain-name:resolves_to_refs[*]", new_pattern)) else: pattern.append(new_pattern.collapse_reference( stix2.ObjectPath.make_object_path("domain-name:resolves_to_refs[*]"))) else: warn("The %s relationship involving %s is not supported in STIX 2.0", 427, ro.relationship, identifying_info(ro)) return create_boolean_expression("AND", pattern) def convert_mutex_to_pattern(mutex): if mutex.name: return create_term("mutex:name", mutex.name.condition, make_constant(mutex.name.value)) else: return None def convert_network_connection_to_pattern(conn): expressions = [] if conn.layer3_protocol is not None: expressions.append(create_term("network-traffic:protocols[*]", conn.layer3_protocol.condition, make_constant(conn.layer3_protocol.value.lower()))) if conn.layer4_protocol is not None: expressions.append(create_term("network-traffic:protocols[*]", conn.layer4_protocol.condition, make_constant(conn.layer4_protocol.value.lower()))) if conn.layer7_protocol is not None: expressions.append(create_term("network-traffic:protocols[*]", conn.layer7_protocol.condition, make_constant(conn.layer7_protocol.value.lower()))) if conn.source_socket_address is not None: if conn.source_socket_address.port is not None: if conn.source_socket_address.port.port_value is not None: expressions.append(create_term("network-traffic:src_port", conn.source_socket_address.port.port_value.condition, stix2.IntegerConstant(int(conn.source_socket_address.port.port_value)))) if conn.source_socket_address.port.layer4_protocol is not None: expressions.append( create_term("network-traffic:protocols[*]", conn.source_socket_address.port.layer4_protocol.condition, make_constant(conn.source_socket_address.port.layer4_protocol.value.lower()))) if conn.source_socket_address.ip_address is not None: expressions.append( create_term("network-traffic:src_ref.value", conn.source_socket_address.ip_address.address_value.condition, make_constant(conn.source_socket_address.ip_address.address_value.value))) elif conn.source_socket_address.hostname is not None: if conn.source_socket_address.hostname.is_domain_name and conn.source_socket_address.hostname.hostname_value is not None: expressions.append( create_term("network-traffic:src_ref.value", conn.source_socket_address.hostname.condition, make_constant(conn.source_socket_address.hostname.hostname_value))) elif (conn.source_socket_address.hostname.naming_system is not None and any(x.value == "DNS" for x in conn.source_socket_address.hostname.naming_system)): expressions.append( create_term("network-traffic:src_ref.value", conn.source_socket_address.hostname.condition, make_constant(conn.source_socket_address.hostname.hostname_value))) if conn.destination_socket_address is not None: if conn.destination_socket_address.port is not None: if conn.destination_socket_address.port.port_value is not None: expressions.append( create_term("network-traffic:dst_port", conn.destination_socket_address.port.port_value.condition, stix2.IntegerConstant(int(conn.destination_socket_address.port.port_value)))) if conn.destination_socket_address.port.layer4_protocol is not None: expressions.append( create_term("network-traffic:protocols[*]", conn.destination_socket_address.port.layer4_protocol.condition, make_constant( conn.destination_socket_address.port.layer4_protocol.value.lower()))) if conn.destination_socket_address.ip_address is not None: expressions.append( create_term("network-traffic:dst_ref.value", conn.destination_socket_address.ip_address.address_value.condition, make_constant(conn.destination_socket_address.ip_address.address_value.value))) elif conn.destination_socket_address.hostname is not None: hostname = conn.destination_socket_address.hostname if hostname.is_domain_name and hostname.hostname_value is not None: expressions.append( create_term("network-traffic:dst_ref.value", conn.destination_socket_address.hostname.condition, make_constant(conn.destination_socket_address.hostname.hostname_value))) elif (conn.destination_socket_address.hostname.naming_system is not None and any(x.value == "DNS" for x in conn.destination_socket_address.hostname.naming_system)): expressions.append( create_term("network-traffic:dst_ref.value", conn.destination_socket_address.hostname.condition, make_constant(conn.destination_socket_address.hostname.hostname_value))) if conn.layer7_connections is not None: if conn.layer7_connections.http_session is not None: extension_expressions = convert_http_session_to_pattern(conn.layer7_connections.http_session) if extension_expressions: expressions.append(extension_expressions) return create_boolean_expression("AND", expressions) def convert_http_client_request_to_pattern(http_request): expressions = [] if http_request.http_request_line is not None: if http_request.http_request_line.http_method is not None: term = add_comparison_expression(http_request.http_request_line.http_method, "network-traffic:extensions.'http-request-ext'.request_method") if term: expressions.append(term) if http_request.http_request_line.version is not None: term = add_comparison_expression(http_request.http_request_line.version, "network-traffic:extensions.'http-request-ext'.request_version") if term: expressions.append(term) if http_request.http_request_header is not None: if http_request.http_request_header.parsed_header is not None: header = http_request.http_request_header.parsed_header for prop_spec in _NETWORK_CONNECTION_PROPERTIES: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(header, prop_1x) and getattr(header, prop_1x): value = getattr(header, prop_1x) # handle non-String properties if isinstance(value, Address): value = getattr(value, "address_value") elif isinstance(value, HostField): value = getattr(value, "domain_name").value elif isinstance(value, URI): value = value.value term = add_comparison_expression(value, object_path) if term: expressions.append(term) return create_boolean_expression("AND", expressions) def convert_http_network_connection_extension(http): if http.http_client_request is not None: return convert_http_client_request_to_pattern(http.http_client_request) _NETWORK_CONNECTION_PROPERTIES = [ ["accept", "network-traffic:extensions.'http-request-ext'.request_header.Accept"], ["accept_charset", "network-traffic:extensions.'http-request-ext'.request_header.'Accept-Charset'"], ["accept_language", "network-traffic:extensions.'http-request-ext'.request_header.'Accept-Language'"], ["accept_datetime", "network-traffic:extensions.'http-request-ext'.request_header.'Accept-Datetime'"], ["accept_encoding", "network-traffic:extensions.'http-request-ext'.request_header.'Accept-Encoding'"], ["authorization", "network-traffic:extensions.'http-request-ext'.request_header.Authorization"], ["cache_control", "network-traffic:extensions.'http-request-ext'.request_header.'Cache-Control'"], ["connection", "network-traffic:extensions.'http-request-ext'.request_header.Connection"], ["cookie", "network-traffic:extensions.'http-request-ext'.request_header.Cookie"], ["content_length", "network-traffic:extensions.'http-request-ext'.request_header.'Content-Length'"], ["content_md5", "network-traffic:extensions.'http-request-ext'.request_header.'Content-MD5'"], ["content_type", "network-traffic:extensions.'http-request-ext'.request_header.'Content-Type'"], ["date", "network-traffic:extensions.'http-request-ext'.request_header.Date"], ["expect", "network-traffic:extensions.'http-request-ext'.request_header.Expect"], ["from_", "network-traffic:extensions.'http-request-ext'.request_header.From"], ["host", "network-traffic:extensions.'http-request-ext'.request_header.Host"], ["if_match", "network-traffic:extensions.'http-request-ext'.request_header.'If-Match'"], ["if_modified_since", "network-traffic:extensions.'http-request-ext'.request_header.'If-Modified-Since'"], ["if_none_match", "network-traffic:extensions.'http-request-ext'.request_header.'If-None-Match'"], ["if_range", "network-traffic:extensions.'http-request-ext'.request_header.'If-Range'"], ["if_unmodified_since", "network-traffic:extensions.'http-request-ext'.request_header.'If-Unmodified-Since'"], ["max_forwards", "network-traffic:extensions.'http-request-ext'.request_header.'Max-Forwards'"], ["pragma", "network-traffic:extensions.'http-request-ext'.request_header.Pragma"], ["proxy_authorization", "network-traffic:extensions.'http-request-ext'.request_header.'Proxy-Authorization'"], ["range", "network-traffic:extensions.'http-request-ext'.request_header.Range"], ["referer", "network-traffic:extensions.'http-request-ext'.request_header.Referer"], ["te", "network-traffic:extensions.'http-request-ext'.request_header.TE"], ["user_agent", "network-traffic:extensions.'http-request-ext'.request_header.'User-Agent'"], ["via", "network-traffic:extensions.'http-request-ext'.request_header.Via"], ["warning", "network-traffic:extensions.'http-request-ext'.request_header.Warning"], ["dnt", "network-traffic:extensions.'http-request-ext'.request_header.DNT"], ["x_requested_with", "network-traffic:extensions.'http-request-ext'.request_header.'X-Requested-With'"], ["x_forwarded_for", "network-traffic:extensions.'http-request-ext'.request_header.'X-Forwarded-For'"], ["x_att_deviceid", "network-traffic:extensions.'http-request-ext'.request_header.'X-ATT-DeviceId'"], ["x_wap_profile", "network-traffic:extensions.'http-request-ext'.request_header.'X-Wap-Profile'"], ] def convert_network_packet_to_pattern(packet): if packet.internet_layer: internet_layer = packet.internet_layer if internet_layer.ipv4 or internet_layer.ipv6: warn("Internet_Layer/IP_Packet content not supported in STIX 2.0", 424) else: if internet_layer.icmpv4: icmp_header = internet_layer.icmpv4.icmpv4_header elif internet_layer.icmpv6: icmp_header = internet_layer.icmpv6.icmpv6_header else: return None expressions = [] if icmp_header.type_: expressions.append(create_term("network-traffic:extensions.'icmp-ext'.icmp_type_hex", icmp_header.type_.condition, stix2.HexConstant(str(icmp_header.type_)))) if icmp_header.code: expressions.append(create_term("network-traffic:extensions.'icmp-ext'.icmp_type_code", icmp_header.code.condition, stix2.HexConstant(str(icmp_header.code)))) return create_boolean_expression("AND", expressions) def convert_http_session_to_pattern(session): if session.http_request_response: requests, responses = split_into_requests_and_responses(session.http_request_response) if len(responses) != 0: warn("HTTPServerResponse type is not supported in STIX 2.0", 429) if len(requests) >= 1: expression = convert_http_client_request_to_pattern(requests[0]) if len(requests) > 1: warn("Only HTTP_Request_Response used for http-request-ext, using first value", 512) return expression def convert_socket_options_to_pattern(options): expressions = [] for prop_name in SOCKET_OPTIONS: prop = getattr(options, prop_name) if prop: expressions.append(create_term("network-traffic:extensions.'socket_ext'.options." + prop_name.upper(), "Equals", prop)) return create_boolean_expression("AND", expressions) _SOCKET_MAP = { "is_blocking": "network-traffic:extensions.'socket_ext'.is_blocking", "is_listening": "network-traffic:extensions.'socket_ext'.is_listening", "type_": "network-traffic:extensions.'socket_ext'.socket_type", "domain": "network-traffic:extensions.'socket_ext'.socket_type", "socket_descriptor": "network-traffic:extensions.'socket_ext'.socket_descriptor" } def convert_network_socket_to_pattern(socket): expressions = [] for prop_spec in _SOCKET_MAP: prop_1x = prop_spec[0] object_path = prop_spec[1] if hasattr(socket, prop_1x) and getattr(socket, prop_1x): term = add_comparison_expression(getattr(socket, prop_1x), object_path) if term: expressions.append(term) if socket.address_family: if socket.address_family in ADDRESS_FAMILY_ENUMERATION: expressions.append(add_comparison_expression(socket.address_family, "network-traffic:extensions.'socket_ext'.address_family")) else: warn("%s in is not a member of the %s enumeration", 627, socket.address_family, "address family") if socket.options: expressions.append(convert_socket_options_to_pattern(socket.options)) if socket.local_address: warn("Network_Socket.local_address content not supported in STIX 2.0", 424) if socket.remote_address: warn("Network_Socket.remote_address content not supported in STIX 2.0", 424) if socket.protocol: expressions.append(add_comparison_expression(socket.protocol, "network-traffic:protocols[*]")) return create_boolean_expression("AND", expressions) #################################################################################################################### def convert_observable_composition_to_pattern(obs_comp): expressions = [] for obs in obs_comp.observables: term = convert_observable_to_pattern(obs) if term: expressions.append(term) if expressions: return create_boolean_expression(obs_comp.operator, expressions) else: return "" def convert_object_to_pattern(obj, obs_id): related_objects = obj.related_objects prop = obj.properties expression = None if prop: if isinstance(prop, Address): expression = convert_address_to_pattern(prop) elif isinstance(prop, URI): expression = convert_uri_to_pattern(prop) elif isinstance(prop, EmailMessage): expression = convert_email_message_to_pattern(prop) elif isinstance(prop, File): expression = convert_file_to_pattern(prop) elif isinstance(prop, WinRegistryKey): expression = convert_registry_key_to_pattern(prop) elif isinstance(prop, Process): expression = convert_process_to_pattern(prop) elif isinstance(prop, DomainName): expression = convert_domain_name_to_pattern(prop, related_objects) elif isinstance(prop, Mutex): expression = convert_mutex_to_pattern(prop) elif isinstance(prop, NetworkConnection): expression = convert_network_connection_to_pattern(prop) elif isinstance(prop, Account): expression = convert_account_to_pattern(prop) elif isinstance(prop, HTTPSession): expression = convert_http_session_to_pattern(prop) elif isinstance(prop, NetworkPacket): expression = convert_network_packet_to_pattern(prop) elif isinstance(prop, NetworkSocket): expression = convert_network_socket_to_pattern(prop) else: warn("%s found in %s cannot be converted to a pattern, yet.", 808, text_type(obj.properties), obs_id) expression = UnconvertedTerm(obs_id) if prop.custom_properties is not None: object_path_root = convert_cybox_class_name_to_object_path_root_name(prop) if object_path_root: if expression: expression = create_boolean_expression("AND", [expression, convert_custom_properties(prop.custom_properties, object_path_root)]) else: expression = convert_custom_properties(prop.custom_properties, object_path_root) if not expression: warn("No pattern term was created from %s", 422, obs_id) expression = UnconvertedTerm(obs_id) elif obj.id_: add_object_id_value(obj.id_, obs_id) return expression def match_1x_id_with_20_id(id_1x, id_20): id_1x_split = id_1x.split("-", 1) id_20_split = id_20.split("--") return id_1x_split[1] == id_20_split[1] def find_definition(idref, sdos): for obs in sdos: if match_1x_id_with_20_id(idref, obs["id"]): info("Found definition for %s", 204, idref) return obs # warn (idref + " cannot be resolved") return None def negate_expression(obs): return hasattr(obs, "negate") and obs.negate def convert_observable_to_pattern(obs): try: set_dynamic_variable("current_observable", obs) if negate_expression(obs): warn("Negation of %s is not handled yet", 810, obs.id_) return convert_observable_to_pattern_without_negate(obs) finally: pop_dynamic_variable("current_observable") def convert_observable_to_pattern_without_negate(obs): if obs.observable_composition is not None: pattern = convert_observable_composition_to_pattern(obs.observable_composition) if pattern and obs.id_: add_to_pattern_cache(obs.id_, pattern) return pattern elif obs.object_ is not None: pattern = convert_object_to_pattern(obs.object_, obs.id_) if pattern: add_to_pattern_cache(obs.id_, pattern) if obs.object_.related_objects: related_patterns = [] for o in obs.object_.related_objects: # save pattern for later use if o.id_ and not id_in_pattern_cache(o.id_): new_pattern = convert_object_to_pattern(o, o.id_) if new_pattern: related_patterns.append(new_pattern) add_to_pattern_cache(o.id_, new_pattern) if pattern: related_patterns.append(pattern) return create_boolean_expression("AND", related_patterns) else: return pattern elif obs.idref is not None: if id_in_pattern_cache(obs.idref): return get_pattern_from_cache(obs.idref) else: # resolve now if possible, and remove from observed_data if id_in_observable_mappings(obs.idref): return convert_observable_to_pattern(get_obs_from_mapping(obs.idref)) return IdrefPlaceHolder(obs.idref) # patterns can contain idrefs which might need to be resolved because the order in which the ids and idrefs appear def interatively_resolve_placeholder_refs(): if pattern_cache_is_empty(): return done = False while not done: # collect all of the fully resolved idrefs fully_resolved_idrefs = [] for idref, expr in get_items_from_pattern_cache(): if expr and not expr.contains_placeholder(): # no PLACEHOLDER idrefs found in the expr, means this idref is fully resolved fully_resolved_idrefs.append(idref) # replace only fully resolved idrefs change_made = False for fr_idref in fully_resolved_idrefs: for idref, expr in get_items_from_pattern_cache(): if expr: change_made, expr = expr.replace_placeholder_with_idref_pattern(fr_idref) # a change will be made, which could introduce a new placeholder id into the expr if change_made: add_to_pattern_cache(idref, expr) # PATTERN_CACHE[idref] = expr done = not change_made def is_placeholder(thing): return thing.index("PLACEHOLDER") != -1 def fix_pattern(pattern): if not pattern_cache_is_empty(): # info(text_type(PATTERN_CACHE)) # info("pattern is: " + pattern) if pattern and pattern.contains_placeholder: for idref in get_ids_from_pattern_cache(): pattern.replace_placeholder_with_idref_pattern(idref) return pattern def convert_indicator_to_pattern(ind): try: set_dynamic_variable("current_indicator", ind) if ind.negate: warn("Negation of %s is not handled yet", 810, ind.id_) return convert_indicator_to_pattern_without_negate(ind) finally: pop_dynamic_variable("current_indicator") def convert_indicator_to_pattern_without_negate(ind): if ind.composite_indicator_expression is not None: pattern = convert_indicator_composition_to_pattern(ind.composite_indicator_expression) if pattern and ind.id_: add_to_pattern_cache(ind.id_, pattern) return pattern elif ind.observable is not None: pattern = convert_observable_to_pattern(ind.observable) if pattern: add_to_pattern_cache(ind.id_, pattern) return pattern elif ind.idref is not None: if id_in_pattern_cache(ind.idref): return get_pattern_from_cache(ind.idref) else: # resolve now if possible, and remove from observed_data if id_in_observable_mappings(ind.idref): return convert_observable_to_pattern(get_obs_from_mapping(ind.idref)) return IdrefPlaceHolder(ind.idref) def convert_indicator_composition_to_pattern(ind_comp): expressions = [] for ind in ind_comp.indicators: term = convert_indicator_to_pattern(ind) if term: expressions.append(term) else: warn("No term was yielded for %s", 422, ind.id_ or ind.idref) if expressions: return create_boolean_expression(ind_comp.operator, expressions) else: return "" def remove_pattern_objects(bundle_instance): all_new_ids_with_patterns = [] for old_id in get_ids_from_pattern_cache(): new_id = get_id_value(old_id) if new_id and len(new_id) == 1: all_new_ids_with_patterns.append(new_id[0]) if not KEEP_OBSERVABLE_DATA_USED_IN_PATTERNS: remaining_objects = [] for obj in bundle_instance["objects"]: if obj["type"] != "observed-data" or obj["id"] not in all_new_ids_with_patterns: remaining_objects.append(obj) else: warn("%s is used as a pattern, therefore it is not included as an observed_data instance", 423, obj["id"]) bundle_instance["objects"] = remaining_objects if not KEEP_OBSERVABLE_DATA_USED_IN_PATTERNS: for obj in bundle_instance["objects"]: if obj["type"] == "report": remaining_object_refs = [] if "object_refs" in obj: for ident in obj["object_refs"]: if not ident.startswith("observed-data") or ident not in all_new_ids_with_patterns: remaining_object_refs.append(ident) obj["object_refs"] = remaining_object_refs # TODO: only remove indicators that were involved ONLY as sub-indicators within composite indicator expressions # if not KEEP_INDICATORS_USED_IN_COMPOSITE_INDICATOR_EXPRESSION and "indicators" in bundle_instance: # remaining_indicators = [] # for ind in bundle_instance["indicators"]: # if ind["id"] not in all_new_ids_with_patterns: # remaining_indicators.append(ind) # bundle_instance["indicators"] = remaining_indicators
[ "stix2elevator.options.error", "stix2elevator.ids.get_object_id_value", "stix2.ObjectPath.make_object_path", "stix2.FloatConstant", "stix2elevator.ids.add_object_id_value", "stix2elevator.ids.get_id_value", "stix2elevator.options.warn", "stix2elevator.utils.map_vocabs_to_label", "re.match", "stix2elevator.ids.exists_object_id_key", "stix2.StringConstant", "six.text_type", "stix2elevator.convert_cybox.split_into_requests_and_responses", "stix2elevator.options.info", "stix2.BooleanConstant", "stix2elevator.utils.identifying_info", "stix2.IntegerConstant" ]
[((6988, 7047), 'stix2elevator.options.error', 'error', (['"""Placeholder %s should be resolved"""', '(203)', 'self.idref'], {}), "('Placeholder %s should be resolved', 203, self.idref)\n", (6993, 7047), False, 'from stix2elevator.options import error, info, warn\n'), ((15663, 15734), 'stix2elevator.options.error', 'error', (['"""%s was used, but two values were not provided."""', '(609)', 'condition'], {}), "('%s was used, but two values were not provided.', 609, condition)\n", (15668, 15734), False, 'from stix2elevator.options import error, info, warn\n'), ((17981, 18007), 'stix2.BooleanConstant', 'stix2.BooleanConstant', (['obj'], {}), '(obj)\n', (18002, 18007), False, 'import stix2\n'), ((19064, 19116), 'stix2elevator.options.warn', 'warn', (['"""No term was yielded for %s"""', '(622)', 'object_path'], {}), "('No term was yielded for %s', 622, object_path)\n", (19068, 19116), False, 'from stix2elevator.options import error, info, warn\n'), ((27254, 27303), 'stix2elevator.options.warn', 'warn', (['"""Email received lines not handled yet"""', '(806)'], {}), "('Email received lines not handled yet', 806)\n", (27258, 27303), False, 'from stix2elevator.options import error, info, warn\n'), ((28415, 28455), 'stix2elevator.options.warn', 'warn', (['"""Email links not handled yet"""', '(806)'], {}), "('Email links not handled yet', 806)\n", (28419, 28455), False, 'from stix2elevator.options import error, info, warn\n'), ((32823, 32908), 'stix2elevator.options.warn', 'warn', (['"""The exports property of WinExecutableFileObj is not part of STIX 2.0"""', '(418)'], {}), "('The exports property of WinExecutableFileObj is not part of STIX 2.0',\n 418)\n", (32827, 32908), False, 'from stix2elevator.options import error, info, warn\n'), ((33007, 33092), 'stix2elevator.options.warn', 'warn', (['"""The imports property of WinExecutableFileObj is not part of STIX 2.0"""', '(419)'], {}), "('The imports property of WinExecutableFileObj is not part of STIX 2.0',\n 419)\n", (33011, 33092), False, 'from stix2elevator.options import error, info, warn\n'), ((38100, 38155), 'stix2elevator.options.warn', 'warn', (['"""1.x full file paths are not processed, yet"""', '(802)'], {}), "('1.x full file paths are not processed, yet', 802)\n", (38104, 38155), False, 'from stix2elevator.options import error, info, warn\n'), ((47327, 47376), 'stix2elevator.options.warn', 'warn', (['"""process:startup_info not handled yet"""', '(803)'], {}), "('process:startup_info not handled yet', 803)\n", (47331, 47376), False, 'from stix2elevator.options import error, info, warn\n'), ((49005, 49067), 'stix2elevator.options.warn', 'warn', (['"""WinServiceObject.service_dll is not handled, yet."""', '(804)'], {}), "('WinServiceObject.service_dll is not handled, yet.', 804)\n", (49009, 49067), False, 'from stix2elevator.options import error, info, warn\n'), ((63555, 63619), 'stix2elevator.convert_cybox.split_into_requests_and_responses', 'split_into_requests_and_responses', (['session.http_request_response'], {}), '(session.http_request_response)\n', (63588, 63619), False, 'from stix2elevator.convert_cybox import split_into_requests_and_responses\n'), ((65772, 65847), 'stix2elevator.options.warn', 'warn', (['"""Network_Socket.local_address content not supported in STIX 2.0"""', '(424)'], {}), "('Network_Socket.local_address content not supported in STIX 2.0', 424)\n", (65776, 65847), False, 'from stix2elevator.options import error, info, warn\n'), ((65886, 65962), 'stix2elevator.options.warn', 'warn', (['"""Network_Socket.remote_address content not supported in STIX 2.0"""', '(424)'], {}), "('Network_Socket.remote_address content not supported in STIX 2.0', 424)\n", (65890, 65962), False, 'from stix2elevator.options import error, info, warn\n'), ((69006, 69062), 'stix2elevator.options.warn', 'warn', (['"""No pattern term was created from %s"""', '(422)', 'obs_id'], {}), "('No pattern term was created from %s', 422, obs_id)\n", (69010, 69062), False, 'from stix2elevator.options import error, info, warn\n'), ((74920, 74940), 'stix2elevator.ids.get_id_value', 'get_id_value', (['old_id'], {}), '(old_id)\n', (74932, 74940), False, 'from stix2elevator.ids import add_object_id_value, exists_object_id_key, get_id_value, get_object_id_value\n'), ((2526, 2564), 'stix2.ObjectPath.make_object_path', 'stix2.ObjectPath.make_object_path', (['lhs'], {}), '(lhs)\n', (2559, 2564), False, 'import stix2\n'), ((12871, 12967), 'stix2elevator.options.error', 'error', (['"""Cannot convert CybOX 2.x class name %s to an object_path_root_name"""', '(813)', 'class_name'], {}), "('Cannot convert CybOX 2.x class name %s to an object_path_root_name',\n 813, class_name)\n", (12876, 12967), False, 'from stix2elevator.options import error, info, warn\n'), ((18079, 18105), 'stix2.IntegerConstant', 'stix2.IntegerConstant', (['obj'], {}), '(obj)\n', (18100, 18105), False, 'import stix2\n'), ((18866, 18910), 'stix2elevator.options.warn', 'warn', (['"""No condition given - assume \'=\'"""', '(714)'], {}), '("No condition given - assume \'=\'", 714)\n', (18870, 18910), False, 'from stix2elevator.options import error, info, warn\n'), ((19254, 19285), 're.match', 're.match', (['"""[a-z0-9_]+"""', 'cp.name'], {}), "('[a-z0-9_]+', cp.name)\n", (19262, 19285), False, 'import re\n'), ((19299, 19395), 'stix2elevator.options.warn', 'warn', (['"""The custom property name %s does not adhere to the specification rules"""', '(617)', 'cp.name'], {}), "('The custom property name %s does not adhere to the specification rules',\n 617, cp.name)\n", (19303, 19395), False, 'from stix2elevator.options import error, info, warn\n'), ((21755, 21783), 'stix2.StringConstant', 'stix2.StringConstant', (['"""unix"""'], {}), "('unix')\n", (21775, 21783), False, 'import stix2\n'), ((28254, 28305), 'stix2elevator.options.warn', 'warn', (['"""%s contains no value"""', '(621)', '"""Email raw body"""'], {}), "('%s contains no value', 621, 'Email raw body')\n", (28258, 28305), False, 'from stix2elevator.options import error, info, warn\n'), ((28332, 28375), 'stix2elevator.options.warn', 'warn', (['"""Email raw body not handled yet"""', '(806)'], {}), "('Email raw body not handled yet', 806)\n", (28336, 28375), False, 'from stix2elevator.options import error, info, warn\n'), ((30678, 30778), 'stix2elevator.options.warn', 'warn', (['"""file:extensions:\'windows-pebinary-ext\':optional_header is not implemented yet"""', '(807)'], {}), '(\n "file:extensions:\'windows-pebinary-ext\':optional_header is not implemented yet"\n , 807)\n', (30682, 30778), False, 'from stix2elevator.options import error, info, warn\n'), ((36716, 36790), 'stix2elevator.options.warn', 'warn', (['"""Ambiguous file path \'%s\' was not processed"""', '(816)', 'f.file_path.value'], {}), '("Ambiguous file path \'%s\' was not processed", 816, f.file_path.value)\n', (36720, 36790), False, 'from stix2elevator.options import error, info, warn\n'), ((47234, 47289), 'stix2elevator.options.warn', 'warn', (['"""Windows Handles are not a part of STIX 2.0"""', '(420)'], {}), "('Windows Handles are not a part of STIX 2.0', 420)\n", (47238, 47289), False, 'from stix2elevator.options import error, info, warn\n'), ((62399, 62470), 'stix2elevator.options.warn', 'warn', (['"""Internet_Layer/IP_Packet content not supported in STIX 2.0"""', '(424)'], {}), "('Internet_Layer/IP_Packet content not supported in STIX 2.0', 424)\n", (62403, 62470), False, 'from stix2elevator.options import error, info, warn\n'), ((63664, 63729), 'stix2elevator.options.warn', 'warn', (['"""HTTPServerResponse type is not supported in STIX 2.0"""', '(429)'], {}), "('HTTPServerResponse type is not supported in STIX 2.0', 429)\n", (63668, 63729), False, 'from stix2elevator.options import error, info, warn\n'), ((65536, 65638), 'stix2elevator.options.warn', 'warn', (['"""%s in is not a member of the %s enumeration"""', '(627)', 'socket.address_family', '"""address family"""'], {}), "('%s in is not a member of the %s enumeration', 627, socket.\n address_family, 'address family')\n", (65540, 65638), False, 'from stix2elevator.options import error, info, warn\n'), ((69134, 69170), 'stix2elevator.ids.add_object_id_value', 'add_object_id_value', (['obj.id_', 'obs_id'], {}), '(obj.id_, obs_id)\n', (69153, 69170), False, 'from stix2elevator.ids import add_object_id_value, exists_object_id_key, get_id_value, get_object_id_value\n'), ((69477, 69520), 'stix2elevator.options.info', 'info', (['"""Found definition for %s"""', '(204)', 'idref'], {}), "('Found definition for %s', 204, idref)\n", (69481, 69520), False, 'from stix2elevator.options import error, info, warn\n'), ((69836, 69891), 'stix2elevator.options.warn', 'warn', (['"""Negation of %s is not handled yet"""', '(810)', 'obs.id_'], {}), "('Negation of %s is not handled yet', 810, obs.id_)\n", (69840, 69891), False, 'from stix2elevator.options import error, info, warn\n'), ((73258, 73313), 'stix2elevator.options.warn', 'warn', (['"""Negation of %s is not handled yet"""', '(810)', 'ind.id_'], {}), "('Negation of %s is not handled yet', 810, ind.id_)\n", (73262, 73313), False, 'from stix2elevator.options import error, info, warn\n'), ((74590, 74651), 'stix2elevator.options.warn', 'warn', (['"""No term was yielded for %s"""', '(422)', '(ind.id_ or ind.idref)'], {}), "('No term was yielded for %s', 422, ind.id_ or ind.idref)\n", (74594, 74651), False, 'from stix2elevator.options import error, info, warn\n'), ((6750, 6782), 'stix2elevator.ids.exists_object_id_key', 'exists_object_id_key', (['self.idref'], {}), '(self.idref)\n', (6770, 6782), False, 'from stix2elevator.ids import add_object_id_value, exists_object_id_key, get_id_value, get_object_id_value\n'), ((8056, 8124), 'stix2elevator.options.error', 'error', (['"""Observable Expressions should not contain placeholders"""', '(202)'], {}), "('Observable Expressions should not contain placeholders', 202)\n", (8061, 8124), False, 'from stix2elevator.options import error, info, warn\n'), ((17334, 17386), 'stix2elevator.options.warn', 'warn', (['"""Used MATCHES operator for %s"""', '(715)', 'condition'], {}), "('Used MATCHES operator for %s', 715, condition)\n", (17338, 17386), False, 'from stix2elevator.options import error, info, warn\n'), ((18154, 18178), 'stix2.FloatConstant', 'stix2.FloatConstant', (['obj'], {}), '(obj)\n', (18173, 18178), False, 'import stix2\n'), ((19439, 19549), 'stix2elevator.options.warn', 'warn', (['"""The custom property name %s contains whitespace, replacing it with underscores"""', '(624)', 'cp.name'], {}), "(\n 'The custom property name %s contains whitespace, replacing it with underscores'\n , 624, cp.name)\n", (19443, 19549), False, 'from stix2elevator.options import error, info, warn\n'), ((20253, 20292), 'stix2.BooleanConstant', 'stix2.BooleanConstant', (['account.disabled'], {}), '(account.disabled)\n', (20274, 20292), False, 'import stix2\n'), ((20905, 20923), 'six.text_type', 'text_type', (['account'], {}), '(account)\n', (20914, 20923), False, 'from six import text_type\n'), ((33938, 33956), 'six.text_type', 'text_type', (['h.type_'], {}), '(h.type_)\n', (33947, 33956), False, 'from six import text_type\n'), ((34062, 34080), 'six.text_type', 'text_type', (['h.type_'], {}), '(h.type_)\n', (34071, 34080), False, 'from six import text_type\n'), ((34183, 34201), 'six.text_type', 'text_type', (['h.type_'], {}), '(h.type_)\n', (34192, 34201), False, 'from six import text_type\n'), ((34269, 34287), 'six.text_type', 'text_type', (['h.type_'], {}), '(h.type_)\n', (34278, 34287), False, 'from six import text_type\n'), ((34399, 34421), 'stix2elevator.options.warn', 'warn', (['err.message', '(626)'], {}), '(err.message, 626)\n', (34403, 34421), False, 'from stix2elevator.options import error, info, warn\n'), ((35923, 36000), 'stix2elevator.options.warn', 'warn', (['"""Unable to create a pattern for file:file_name from a File object"""', '(620)'], {}), "('Unable to create a pattern for file:file_name from a File object', 620)\n", (35927, 36000), False, 'from stix2elevator.options import error, info, warn\n'), ((39837, 39849), 'six.text_type', 'text_type', (['f'], {}), '(f)\n', (39846, 39849), False, 'from six import text_type\n'), ((40127, 40139), 'six.text_type', 'text_type', (['f'], {}), '(f)\n', (40136, 40139), False, 'from six import text_type\n'), ((40814, 40899), 'stix2elevator.options.warn', 'warn', (['"""Condition %s on a hive property not handled"""', '(812)', 'reg_key.hive.condition'], {}), "('Condition %s on a hive property not handled', 812, reg_key.hive.condition\n )\n", (40818, 40899), False, 'from stix2elevator.options import error, info, warn\n'), ((40976, 41094), 'stix2elevator.options.warn', 'warn', (['"""Hive property, %s, is already a prefix of the key property, %s"""', '(623)', 'reg_key.hive.value', 'reg_key.key.value'], {}), "('Hive property, %s, is already a prefix of the key property, %s', 623,\n reg_key.hive.value, reg_key.key.value)\n", (40980, 41094), False, 'from stix2elevator.options import error, info, warn\n'), ((45921, 45939), 'six.text_type', 'text_type', (['process'], {}), '(process)\n', (45930, 45939), False, 'from six import text_type\n'), ((63888, 63976), 'stix2elevator.options.warn', 'warn', (['"""Only HTTP_Request_Response used for http-request-ext, using first value"""', '(512)'], {}), "('Only HTTP_Request_Response used for http-request-ext, using first value',\n 512)\n", (63892, 63976), False, 'from stix2elevator.options import error, info, warn\n'), ((75339, 75455), 'stix2elevator.options.warn', 'warn', (['"""%s is used as a pattern, therefore it is not included as an observed_data instance"""', '(423)', "obj['id']"], {}), "(\n '%s is used as a pattern, therefore it is not included as an observed_data instance'\n , 423, obj['id'])\n", (75343, 75455), False, 'from stix2elevator.options import error, info, warn\n'), ((6796, 6827), 'stix2elevator.ids.get_object_id_value', 'get_object_id_value', (['self.idref'], {}), '(self.idref)\n', (6815, 6827), False, 'from stix2elevator.ids import add_object_id_value, exists_object_id_key, get_id_value, get_object_id_value\n'), ((17515, 17567), 'stix2elevator.options.warn', 'warn', (['"""Used MATCHES operator for %s"""', '(715)', 'condition'], {}), "('Used MATCHES operator for %s', 715, condition)\n", (17519, 17567), False, 'from stix2elevator.options import error, info, warn\n'), ((21131, 21208), 'stix2.StringConstant', 'stix2.StringConstant', (["('windows-domain' if account.domain else 'windows-local')"], {}), "('windows-domain' if account.domain else 'windows-local')\n", (21151, 21208), False, 'import stix2\n'), ((22031, 22063), 'six.text_type', 'text_type', (['account.user_id.value'], {}), '(account.user_id.value)\n', (22040, 22063), False, 'from six import text_type\n'), ((23126, 23197), 'stix2elevator.options.warn', 'warn', (['"""The address type %s is not part of Cybox 3.0"""', '(421)', 'add.category'], {}), "('The address type %s is not part of Cybox 3.0', 421, add.category)\n", (23130, 23197), False, 'from stix2elevator.options import error, info, warn\n'), ((30993, 31045), 'stix2elevator.utils.map_vocabs_to_label', 'map_vocabs_to_label', (['f.type_.value', 'WINDOWS_PEBINARY'], {}), '(f.type_.value, WINDOWS_PEBINARY)\n', (31012, 31045), False, 'from stix2elevator.utils import identifying_info, map_vocabs_to_label\n'), ((31800, 31853), 'stix2elevator.options.warn', 'warn', (['"""Entropy.min is not supported in STIX 2.0"""', '(424)'], {}), "('Entropy.min is not supported in STIX 2.0', 424)\n", (31804, 31853), False, 'from stix2elevator.options import error, info, warn\n'), ((31908, 31961), 'stix2elevator.options.warn', 'warn', (['"""Entropy.max is not supported in STIX 2.0"""', '(424)'], {}), "('Entropy.max is not supported in STIX 2.0', 424)\n", (31912, 31961), False, 'from stix2elevator.options import error, info, warn\n'), ((43833, 43862), 'stix2.StringConstant', 'stix2.StringConstant', (['a.value'], {}), '(a.value)\n', (43853, 43862), False, 'import stix2\n'), ((44918, 44949), 'stix2.IntegerConstant', 'stix2.IntegerConstant', (['cp.value'], {}), '(cp.value)\n', (44939, 44949), False, 'import stix2\n'), ((45425, 45495), 'stix2.ObjectPath.make_object_path', 'stix2.ObjectPath.make_object_path', (['"""process:opened_connection_refs[*]"""'], {}), "('process:opened_connection_refs[*]')\n", (45458, 45495), False, 'import stix2\n'), ((46236, 46254), 'six.text_type', 'text_type', (['process'], {}), '(process)\n', (46245, 46254), False, 'from six import text_type\n'), ((50843, 50863), 'stix2elevator.utils.identifying_info', 'identifying_info', (['ro'], {}), '(ro)\n', (50859, 50863), False, 'from stix2elevator.utils import identifying_info, map_vocabs_to_label\n'), ((34020, 34038), 'six.text_type', 'text_type', (['h.type_'], {}), '(h.type_)\n', (34029, 34038), False, 'from six import text_type\n'), ((34118, 34136), 'six.text_type', 'text_type', (['h.type_'], {}), '(h.type_)\n', (34127, 34136), False, 'from six import text_type\n'), ((32263, 32305), 'stix2.FloatConstant', 'stix2.FloatConstant', (['s.entropy.value.value'], {}), '(s.entropy.value.value)\n', (32282, 32305), False, 'import stix2\n'), ((50625, 50693), 'stix2.ObjectPath.make_object_path', 'stix2.ObjectPath.make_object_path', (['"""domain-name:resolves_to_refs[*]"""'], {}), "('domain-name:resolves_to_refs[*]')\n", (50658, 50693), False, 'import stix2\n'), ((68260, 68285), 'six.text_type', 'text_type', (['obj.properties'], {}), '(obj.properties)\n', (68269, 68285), False, 'from six import text_type\n')]
import lightgbm as lgb import numpy as np import pandas as pd from attrdict import AttrDict from sklearn.externals import joblib from steppy.base import BaseTransformer from .utils import NeptuneContext, get_logger neptune_ctx = NeptuneContext() logger = get_logger() class LightGBM(BaseTransformer): def __init__(self, name=None, **params): super().__init__() self.msg_prefix = 'LightGBM transformer' logger.info('initializing {}.'.format(self.msg_prefix)) self.params = params self.training_params = ['number_boosting_rounds', 'early_stopping_rounds'] self.evaluation_function = None self.callbacks = callbacks(channel_prefix=name) @property def model_config(self): return AttrDict({param: value for param, value in self.params.items() if param not in self.training_params}) @property def training_config(self): return AttrDict({param: value for param, value in self.params.items() if param in self.training_params}) def fit(self, X, y, X_valid, y_valid, feature_names='auto', categorical_features='auto', **kwargs): evaluation_results = {} self._check_target_shape_and_type(y, 'y') self._check_target_shape_and_type(y_valid, 'y_valid') y = self._format_target(y, 'y') y_valid = self._format_target(y_valid, 'y_valid') logger.info('{}, train data shape {}'.format(self.msg_prefix, X.shape)) logger.info('{}, validation data shape {}'.format(self.msg_prefix, X_valid.shape)) logger.info('{}, train labels shape {}'.format(self.msg_prefix, y.shape)) logger.info('{}, validation labels shape {}'.format(self.msg_prefix, y_valid.shape)) data_train = lgb.Dataset(data=X, label=y, feature_name=feature_names, categorical_feature=categorical_features, **kwargs) data_valid = lgb.Dataset(X_valid, label=y_valid, feature_name=feature_names, categorical_feature=categorical_features, **kwargs) self.estimator = lgb.train(self.model_config, data_train, feature_name=feature_names, categorical_feature=categorical_features, valid_sets=[data_train, data_valid], valid_names=['data_train', 'data_valid'], evals_result=evaluation_results, num_boost_round=self.training_config.number_boosting_rounds, early_stopping_rounds=self.training_config.early_stopping_rounds, verbose_eval=self.model_config.verbose, feval=self.evaluation_function, callbacks=self.callbacks, **kwargs) return self def transform(self, X, **kwargs): prediction = self.estimator.predict(X) return {'prediction': prediction} def load(self, filepath): self.estimator = joblib.load(filepath) return self def persist(self, filepath): joblib.dump(self.estimator, filepath) def _check_target_shape_and_type(self, target, name): if not any([isinstance(target, obj_type) for obj_type in [pd.Series, np.ndarray, list]]): raise TypeError( '{}: "{}" must be "numpy.ndarray" or "Pandas.Series" or "list", got {} instead.'.format( self.msg_prefix, name, type(target))) try: assert len(target.shape) == 1, '{}: "{}" must be 1-D. It is {}-D instead.'.format(self.msg_prefix, name, len(target.shape)) except AttributeError: print('{}: cannot determine shape of the {}.' 'Type must be "numpy.ndarray" or "Pandas.Series" or "list", got {} instead'.format(self.msg_prefix, name, type(target))) def _format_target(self, target, name): if isinstance(target, pd.Series): return target.values elif isinstance(target, np.ndarray): return target elif isinstance(target, list): return np.array(target) else: raise TypeError('{}: "{}" must be "numpy.ndarray" or "Pandas.Series" or "list", got {} instead.'.format( self.msg_prefix, name, type(target))) def callbacks(channel_prefix): neptune_monitor = neptune_monitor_lgbm(channel_prefix) return [neptune_monitor] def neptune_monitor_lgbm(channel_prefix=''): def callback(env): for name, loss_name, loss_value, _ in env.evaluation_result_list: if channel_prefix != '': channel_name = '{}_{}_{}'.format(channel_prefix, name, loss_name) else: channel_name = '{}_{}'.format(name, loss_name) neptune_ctx.ctx.channel_send(channel_name, x=env.iteration, y=loss_value) return callback
[ "sklearn.externals.joblib.dump", "lightgbm.train", "lightgbm.Dataset", "numpy.array", "sklearn.externals.joblib.load" ]
[((1858, 1970), 'lightgbm.Dataset', 'lgb.Dataset', ([], {'data': 'X', 'label': 'y', 'feature_name': 'feature_names', 'categorical_feature': 'categorical_features'}), '(data=X, label=y, feature_name=feature_names,\n categorical_feature=categorical_features, **kwargs)\n', (1869, 1970), True, 'import lightgbm as lgb\n'), ((2120, 2239), 'lightgbm.Dataset', 'lgb.Dataset', (['X_valid'], {'label': 'y_valid', 'feature_name': 'feature_names', 'categorical_feature': 'categorical_features'}), '(X_valid, label=y_valid, feature_name=feature_names,\n categorical_feature=categorical_features, **kwargs)\n', (2131, 2239), True, 'import lightgbm as lgb\n'), ((2394, 2879), 'lightgbm.train', 'lgb.train', (['self.model_config', 'data_train'], {'feature_name': 'feature_names', 'categorical_feature': 'categorical_features', 'valid_sets': '[data_train, data_valid]', 'valid_names': "['data_train', 'data_valid']", 'evals_result': 'evaluation_results', 'num_boost_round': 'self.training_config.number_boosting_rounds', 'early_stopping_rounds': 'self.training_config.early_stopping_rounds', 'verbose_eval': 'self.model_config.verbose', 'feval': 'self.evaluation_function', 'callbacks': 'self.callbacks'}), "(self.model_config, data_train, feature_name=feature_names,\n categorical_feature=categorical_features, valid_sets=[data_train,\n data_valid], valid_names=['data_train', 'data_valid'], evals_result=\n evaluation_results, num_boost_round=self.training_config.\n number_boosting_rounds, early_stopping_rounds=self.training_config.\n early_stopping_rounds, verbose_eval=self.model_config.verbose, feval=\n self.evaluation_function, callbacks=self.callbacks, **kwargs)\n", (2403, 2879), True, 'import lightgbm as lgb\n'), ((3476, 3497), 'sklearn.externals.joblib.load', 'joblib.load', (['filepath'], {}), '(filepath)\n', (3487, 3497), False, 'from sklearn.externals import joblib\n'), ((3560, 3597), 'sklearn.externals.joblib.dump', 'joblib.dump', (['self.estimator', 'filepath'], {}), '(self.estimator, filepath)\n', (3571, 3597), False, 'from sklearn.externals import joblib\n'), ((5003, 5019), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (5011, 5019), True, 'import numpy as np\n')]
from libs.base import get_webdriver def main(): driver_name = "firefox" # This will not work on my linux box because my # version of chrome is too new... # driver_name = "chrome" browser = get_webdriver(driver_name=driver_name) browser.get("http://seleniumhq.org/") browser.implicitly_wait(10) browser.find_element_by_name() if __name__ == "__main__": main()
[ "libs.base.get_webdriver" ]
[((213, 251), 'libs.base.get_webdriver', 'get_webdriver', ([], {'driver_name': 'driver_name'}), '(driver_name=driver_name)\n', (226, 251), False, 'from libs.base import get_webdriver\n')]
import logging import inspect import ast import io import importlib import operator from ._base_node import NodeEntityBase from ._class_node import ClassNode from ._function_node import FunctionNode from apistub import Navigation, Kind, NavigationTag filter_function = lambda x: isinstance(x, FunctionNode) filter_class = lambda x: isinstance(x, ClassNode) class ModuleNode(NodeEntityBase): """ModuleNode represents module level node and all it's children :param str: namespace :param module: module :param dict: node_index """ def __init__(self, namespace, module, node_index, pkg_root_namespace): super().__init__(namespace, None, module) self.namespace_id = self.generate_id() self.node_index = node_index self.pkg_root_namespace = pkg_root_namespace self._inspect() def _inspect(self): """Imports module, identify public entities in module and inspect them recursively """ # Parse public entities only if __all is present. Otherwise all Classes and Functions not starting with "_" can be included. public_entities = [] if hasattr(self.obj, "__all__"): public_entities = getattr(self.obj, "__all__") # find class and function nodes in module for name, member_obj in inspect.getmembers(self.obj): if self._should_skip_parsing(name, member_obj, public_entities): continue if inspect.isclass(member_obj): class_node = ClassNode( name=name, namespace=self.namespace, parent_node=self, obj=member_obj, pkg_root_namespace=self.pkg_root_namespace ) key = "{0}.{1}".format(self.namespace, class_node.name) self.node_index.add(key, class_node) self.child_nodes.append(class_node) elif inspect.isroutine(member_obj): func_node = FunctionNode(self.namespace, self, obj=member_obj, is_module_level=True) key = "{0}.{1}".format(self.namespace, func_node.name) self.node_index.add(key, func_node) self.child_nodes.append(func_node) else: logging.debug("Skipping unknown type member in module: {}".format(name)) def _should_skip_parsing(self, name, member_obj, public_entities): # If module has list of published entities ( __all__) then include only those members if public_entities and name not in public_entities: logging.debug( "Object is not listed in __all__. Skipping object {}".format(name) ) return True # Skip any private members if name.startswith("_"): logging.debug("Skipping object {}".format(name)) return True # Skip any member in module level that is defined in external or built in package if hasattr(member_obj, "__module__"): return not getattr(member_obj, "__module__").startswith(self.pkg_root_namespace) # Don't skip member if module name is not available. This is just to be on safer side return False def generate_tokens(self, apiview): """Generates token for the node and it's children recursively and add it to apiview :param ApiView: apiview """ if self.child_nodes: # Add name space level functions first for c in filter(filter_function, self.child_nodes): c.generate_tokens(apiview) apiview.set_blank_lines(2) # Add classes for c in filter(filter_class, self.child_nodes): c.generate_tokens(apiview) apiview.set_blank_lines(2) def get_navigation(self): """Generate navigation tree recursively by generating Navigation obejct for classes and functions in name space """ if self.child_nodes: navigation = Navigation(self.namespace_id, self.namespace_id) navigation.tags = NavigationTag(Kind.type_module) # Generate child navigation for each child nodes for c in filter(filter_function, self.child_nodes): child_nav = Navigation(c.name, c.namespace_id) child_nav.tags = NavigationTag(Kind.type_method) navigation.add_child(child_nav) for c in filter(filter_class, self.child_nodes): child_nav = Navigation(c.name, c.namespace_id) child_nav.tags = NavigationTag(Kind.type_enum if c.is_enum else Kind.type_class) navigation.add_child(child_nav) return navigation
[ "apistub.Navigation", "inspect.isroutine", "inspect.isclass", "apistub.NavigationTag", "inspect.getmembers" ]
[((1312, 1340), 'inspect.getmembers', 'inspect.getmembers', (['self.obj'], {}), '(self.obj)\n', (1330, 1340), False, 'import inspect\n'), ((1460, 1487), 'inspect.isclass', 'inspect.isclass', (['member_obj'], {}), '(member_obj)\n', (1475, 1487), False, 'import inspect\n'), ((4039, 4087), 'apistub.Navigation', 'Navigation', (['self.namespace_id', 'self.namespace_id'], {}), '(self.namespace_id, self.namespace_id)\n', (4049, 4087), False, 'from apistub import Navigation, Kind, NavigationTag\n'), ((4118, 4149), 'apistub.NavigationTag', 'NavigationTag', (['Kind.type_module'], {}), '(Kind.type_module)\n', (4131, 4149), False, 'from apistub import Navigation, Kind, NavigationTag\n'), ((1955, 1984), 'inspect.isroutine', 'inspect.isroutine', (['member_obj'], {}), '(member_obj)\n', (1972, 1984), False, 'import inspect\n'), ((4303, 4337), 'apistub.Navigation', 'Navigation', (['c.name', 'c.namespace_id'], {}), '(c.name, c.namespace_id)\n', (4313, 4337), False, 'from apistub import Navigation, Kind, NavigationTag\n'), ((4371, 4402), 'apistub.NavigationTag', 'NavigationTag', (['Kind.type_method'], {}), '(Kind.type_method)\n', (4384, 4402), False, 'from apistub import Navigation, Kind, NavigationTag\n'), ((4541, 4575), 'apistub.Navigation', 'Navigation', (['c.name', 'c.namespace_id'], {}), '(c.name, c.namespace_id)\n', (4551, 4575), False, 'from apistub import Navigation, Kind, NavigationTag\n'), ((4609, 4672), 'apistub.NavigationTag', 'NavigationTag', (['(Kind.type_enum if c.is_enum else Kind.type_class)'], {}), '(Kind.type_enum if c.is_enum else Kind.type_class)\n', (4622, 4672), False, 'from apistub import Navigation, Kind, NavigationTag\n')]
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow_serving/config/logging_config.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tensorboard_plugin_wit._vendor.tensorflow_serving.config import log_collector_config_pb2 as tensorflow__serving_dot_config_dot_log__collector__config__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='tensorflow_serving/config/logging_config.proto', package='tensorflow.serving', syntax='proto3', serialized_options=_b('\370\001\001'), serialized_pb=_b('\n.tensorflow_serving/config/logging_config.proto\x12\x12tensorflow.serving\x1a\x34tensorflow_serving/config/log_collector_config.proto\"\'\n\x0eSamplingConfig\x12\x15\n\rsampling_rate\x18\x01 \x01(\x01\"\x92\x01\n\rLoggingConfig\x12\x44\n\x14log_collector_config\x18\x01 \x01(\x0b\x32&.tensorflow.serving.LogCollectorConfig\x12;\n\x0fsampling_config\x18\x02 \x01(\x0b\x32\".tensorflow.serving.SamplingConfigB\x03\xf8\x01\x01\x62\x06proto3') , dependencies=[tensorflow__serving_dot_config_dot_log__collector__config__pb2.DESCRIPTOR,]) _SAMPLINGCONFIG = _descriptor.Descriptor( name='SamplingConfig', full_name='tensorflow.serving.SamplingConfig', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='sampling_rate', full_name='tensorflow.serving.SamplingConfig.sampling_rate', index=0, number=1, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=124, serialized_end=163, ) _LOGGINGCONFIG = _descriptor.Descriptor( name='LoggingConfig', full_name='tensorflow.serving.LoggingConfig', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='log_collector_config', full_name='tensorflow.serving.LoggingConfig.log_collector_config', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='sampling_config', full_name='tensorflow.serving.LoggingConfig.sampling_config', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=166, serialized_end=312, ) _LOGGINGCONFIG.fields_by_name['log_collector_config'].message_type = tensorflow__serving_dot_config_dot_log__collector__config__pb2._LOGCOLLECTORCONFIG _LOGGINGCONFIG.fields_by_name['sampling_config'].message_type = _SAMPLINGCONFIG DESCRIPTOR.message_types_by_name['SamplingConfig'] = _SAMPLINGCONFIG DESCRIPTOR.message_types_by_name['LoggingConfig'] = _LOGGINGCONFIG _sym_db.RegisterFileDescriptor(DESCRIPTOR) SamplingConfig = _reflection.GeneratedProtocolMessageType('SamplingConfig', (_message.Message,), dict( DESCRIPTOR = _SAMPLINGCONFIG, __module__ = 'tensorflow_serving.config.logging_config_pb2' # @@protoc_insertion_point(class_scope:tensorflow.serving.SamplingConfig) )) _sym_db.RegisterMessage(SamplingConfig) LoggingConfig = _reflection.GeneratedProtocolMessageType('LoggingConfig', (_message.Message,), dict( DESCRIPTOR = _LOGGINGCONFIG, __module__ = 'tensorflow_serving.config.logging_config_pb2' # @@protoc_insertion_point(class_scope:tensorflow.serving.LoggingConfig) )) _sym_db.RegisterMessage(LoggingConfig) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
[ "google.protobuf.symbol_database.Default", "google.protobuf.descriptor.FieldDescriptor" ]
[((470, 496), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (494, 496), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((2402, 2783), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""log_collector_config"""', 'full_name': '"""tensorflow.serving.LoggingConfig.log_collector_config"""', 'index': '(0)', 'number': '(1)', 'type': '(11)', 'cpp_type': '(10)', 'label': '(1)', 'has_default_value': '(False)', 'default_value': 'None', 'message_type': 'None', 'enum_type': 'None', 'containing_type': 'None', 'is_extension': '(False)', 'extension_scope': 'None', 'serialized_options': 'None', 'file': 'DESCRIPTOR'}), "(name='log_collector_config', full_name=\n 'tensorflow.serving.LoggingConfig.log_collector_config', index=0,\n number=1, type=11, cpp_type=10, label=1, has_default_value=False,\n default_value=None, message_type=None, enum_type=None, containing_type=\n None, is_extension=False, extension_scope=None, serialized_options=None,\n file=DESCRIPTOR)\n", (2429, 2783), True, 'from google.protobuf import descriptor as _descriptor\n'), ((2804, 3176), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""sampling_config"""', 'full_name': '"""tensorflow.serving.LoggingConfig.sampling_config"""', 'index': '(1)', 'number': '(2)', 'type': '(11)', 'cpp_type': '(10)', 'label': '(1)', 'has_default_value': '(False)', 'default_value': 'None', 'message_type': 'None', 'enum_type': 'None', 'containing_type': 'None', 'is_extension': '(False)', 'extension_scope': 'None', 'serialized_options': 'None', 'file': 'DESCRIPTOR'}), "(name='sampling_config', full_name=\n 'tensorflow.serving.LoggingConfig.sampling_config', index=1, number=2,\n type=11, cpp_type=10, label=1, has_default_value=False, default_value=\n None, message_type=None, enum_type=None, containing_type=None,\n is_extension=False, extension_scope=None, serialized_options=None, file\n =DESCRIPTOR)\n", (2831, 3176), True, 'from google.protobuf import descriptor as _descriptor\n')]
from django.db import models from treebeard.mp_tree import MP_Node class Object(models.Model): name = models.CharField(max_length=50) class TreeNode(MP_Node): name = models.CharField(max_length=30) def __unicode__(self): return 'Category: %s' % self.name
[ "django.db.models.CharField" ]
[((108, 139), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (124, 139), False, 'from django.db import models\n'), ((178, 209), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (194, 209), False, 'from django.db import models\n')]
# -*- coding: utf-8 -*- # Copyright 2018 <NAME> & <NAME>. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # -*- coding: utf-8 -*- import numpy as np # relu激活函数 def relu(x): x = np.array(x) return np.maximum(0, x) # tanh激活函数 def tanh(x): x = np.array(x) return np.tanh(x) # sigmoid激活函数 def sigmoid(x): x = np.array(x) return 1 / (1 + np.exp(-x)) # softmax激活函数 def softmax(x): x = np.array(x) assert len(x.shape) == 1 or len(x.shape) == 2 if len(x.shape) == 1: x = x - x.max() x = np.exp(x) return x / x.sum() else: x = x - x.max(1, keepdims=True) x = np.exp(x) return x / x.sum(1, keepdims=True) # linear激活函数 def linear(x): x = np.array(x) return x # 阈值激活函数 def threshold(x, threshold=0): x = np.array(x) out = np.zeros_like(x, dtype=np.float) out[x >= threshold] = 1 return out # arctan激活函数 def arctan(x): x = np.array(x) return np.arctan(x) # leaky relu def leaky_relu(x, alpha=0.1): x = np.array(x, dtype=np.float) x[x < 0] = (x * alpha)[x < 0] return x # prelu激活函数 def prelu(x, p): x = np.array(x, dtype=np.float) x[x < 0] = (x * p)[x < 0] return x # elu激活函数 def elu(x, alpha=0.1): x = np.array(x, dtype=np.float) x[x < 0] = (alpha * (np.exp(x) - 1))[x < 0] return x # softplus激活函数 def softplus(x): x = np.array(x) return np.log(1 + np.exp(x)) # bent identity def bent_identity(x): x = np.array(x) return (np.sqrt(np.square(x) + 1) - 1) * 0.5 + x # Soft Exponential def soft_exponential(x, p): x = np.array(x, dtype=np.float) x[p < 0] = (-np.log(np.maximum(1 - p[p < 0] * (x[p < 0] + p[p < 0]), 1e-7)) / p[p < 0]) x[p == 0] = 0 x[p > 0] = ((np.exp(p * x) - 1) / p + p)[p > 0] return x # Sinusoid def sin(x): x = np.array(x) return np.sin(x) # Sinc def sinc(x): x = np.array(x, dtype=np.float) out = np.ones_like(x, dtype=np.float) out[x != 0] = np.sin(x[x != 0]) / x[x != 0] return out # Gaussian def guassian(x): x = np.array(x) return np.exp(-np.square(x))
[ "numpy.zeros_like", "numpy.maximum", "numpy.tanh", "numpy.ones_like", "numpy.square", "numpy.sin", "numpy.array", "numpy.exp", "numpy.arctan" ]
[((725, 736), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (733, 736), True, 'import numpy as np\n'), ((749, 765), 'numpy.maximum', 'np.maximum', (['(0)', 'x'], {}), '(0, x)\n', (759, 765), True, 'import numpy as np\n'), ((805, 816), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (813, 816), True, 'import numpy as np\n'), ((829, 839), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (836, 839), True, 'import numpy as np\n'), ((885, 896), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (893, 896), True, 'import numpy as np\n'), ((975, 986), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (983, 986), True, 'import numpy as np\n'), ((1303, 1314), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1311, 1314), True, 'import numpy as np\n'), ((1384, 1395), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1392, 1395), True, 'import numpy as np\n'), ((1407, 1439), 'numpy.zeros_like', 'np.zeros_like', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (1420, 1439), True, 'import numpy as np\n'), ((1528, 1539), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1536, 1539), True, 'import numpy as np\n'), ((1552, 1564), 'numpy.arctan', 'np.arctan', (['x'], {}), '(x)\n', (1561, 1564), True, 'import numpy as np\n'), ((1623, 1650), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (1631, 1650), True, 'import numpy as np\n'), ((1744, 1771), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (1752, 1771), True, 'import numpy as np\n'), ((1865, 1892), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (1873, 1892), True, 'import numpy as np\n'), ((2003, 2014), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2011, 2014), True, 'import numpy as np\n'), ((2102, 2113), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2110, 2113), True, 'import numpy as np\n'), ((2230, 2257), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (2238, 2257), True, 'import numpy as np\n'), ((2475, 2486), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2483, 2486), True, 'import numpy as np\n'), ((2499, 2508), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (2505, 2508), True, 'import numpy as np\n'), ((2544, 2571), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (2552, 2571), True, 'import numpy as np\n'), ((2583, 2614), 'numpy.ones_like', 'np.ones_like', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (2595, 2614), True, 'import numpy as np\n'), ((2723, 2734), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2731, 2734), True, 'import numpy as np\n'), ((1103, 1112), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (1109, 1112), True, 'import numpy as np\n'), ((1206, 1215), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (1212, 1215), True, 'import numpy as np\n'), ((2634, 2651), 'numpy.sin', 'np.sin', (['x[x != 0]'], {}), '(x[x != 0])\n', (2640, 2651), True, 'import numpy as np\n'), ((918, 928), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (924, 928), True, 'import numpy as np\n'), ((2038, 2047), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (2044, 2047), True, 'import numpy as np\n'), ((2755, 2767), 'numpy.square', 'np.square', (['x'], {}), '(x)\n', (2764, 2767), True, 'import numpy as np\n'), ((1919, 1928), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (1925, 1928), True, 'import numpy as np\n'), ((2283, 2338), 'numpy.maximum', 'np.maximum', (['(1 - p[p < 0] * (x[p < 0] + p[p < 0]))', '(1e-07)'], {}), '(1 - p[p < 0] * (x[p < 0] + p[p < 0]), 1e-07)\n', (2293, 2338), True, 'import numpy as np\n'), ((2388, 2401), 'numpy.exp', 'np.exp', (['(p * x)'], {}), '(p * x)\n', (2394, 2401), True, 'import numpy as np\n'), ((2135, 2147), 'numpy.square', 'np.square', (['x'], {}), '(x)\n', (2144, 2147), True, 'import numpy as np\n')]
#Author-<NAME> #Description-Create a basic multi-post setup sheet import adsk.core, adsk.fusion, adsk.cam, traceback import os, sys, re import math import time import pathlib THISSCRIPT = "Setup Sheet Generator v2 (c) <NAME> 2020" # Set these to True or False (case sensitive) to enable or disable output TXTOUTPUT = False HTMLOUTPUT = True SCREENOUTPUT = False PARAMETER_REGEX = r"\d+:\s*onParameter\(\'([\-\._:\w]+)\',\s*\'?\s*([!-&\(-~\s]*)\'?\)" LINEAR_REGEX = r"\d+:\s*onLinear\(([-\.0-9eE]+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+)\s*\)" CIRCULAR_REGEX = r"\d+:\s*onCircular\((\w+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+),\s*([-\.0-9eE]+)\s*\)" POSITION_REGEX = r"\s*STATE\s+position=\[([\-\.0-9]+),\s*([\-\.0-9]+),\s*([\-\.0-9eE]+)\s*\]" STYLESHEET = """ <style type="text/css"> body {background-color:white; font-family: Arial, Helvetica, sans-serif;} h1 {font-size: 16pt;text-align: center;} table { border: none; border-spacing: 0;} table.setup, table.sheet {width: 18cm; border: 1px solid Black;} table.info {padding-top: 0.1cm;} table.info td { padding-left: 0.1cm;} tr {border: 1px solid Black; page-break-inside: avoid; padding-top: 30px; padding-bottom: 20px; white-space: nowrap;} tr.lined td {border-bottom: 1px solid Gray} tr.tool td {background-color: #e0e0f0; border-bottom: 1px solid Gray; border-top: 1px solid Gray;} th {background-color: #d0d0f0; border-bottom: 1px solid Gray; border-top: 1px solid Gray;} td {font-size: 9pt; vertical-align: top;} td .description {display: inline; font-variant: small-caps;} td .value {display: inline; font-family: Geneva, sans-serif; color: #404060;} </style>\n """ def floatMatch(f1,f2,e=0.00001): return abs(f1-f2) < e def diffAngle(cw, a1, a2): # Angles in range -pi to pi. 0 = across, +ve =up # Return angle from a1 to a2 in direction specified pi2 = 2 * math.pi if cw: while(a1 < a2): a1 += pi2 da = a1 - a2 else: while(a2 < a1): a2 += pi2 da = a2 - a1 while (da > pi2): da -= pi2 while (da <= 0): da += pi2 return da def OpenFile(fname): if (os.name == 'posix'): os.system('open "%s"' % fname) elif (os.name == 'nt'): os.startfile(fname) def WaitForFile(fname): time.sleep(0.2) my_file = pathlib.Path(fname) # Wait until the file exists triesleft = 100 while triesleft > 0 and not my_file.is_file(): time.sleep(0.1) triesleft -= 1 if triesleft == 0: return False # Wait until the file stops growing oldsize = my_file.stat().st_size time.sleep(0.1) newsize = my_file.stat().st_size while newsize == 0 or newsize != oldsize: time.sleep(0.1) oldsize = newsize newsize = my_file.stat().st_size return True def ParseOnStatePosition(p): try: matches = re.finditer(POSITION_REGEX, p, re.ASCII) firstmatch=(list(matches))[0] x = float(firstmatch.group(1)) y = float(firstmatch.group(2)) z = float(firstmatch.group(3)) return x, y, z except: # Something went wrong adsk.core.Application.get().userInterface.messageBox(p,"Failed to match Position regex") return "","" def ParseOnParameter(p): try: pkey = "" pvalue = "" matches = re.finditer(PARAMETER_REGEX, p, re.ASCII) firstmatch=(list(matches))[0] pkey = firstmatch.group(1) pvalue = firstmatch.group(2) return pkey,pvalue except: # Some parameters may have a ' in the text, which will break the regex match #adsk.core.Application.get().userInterface.messageBox(p,"Failed to match OnParameter regex") return pkey,pvalue def ParseOnLinear(p, ox, oy, oz, of): try: matches = re.finditer(LINEAR_REGEX, p, re.ASCII) firstmatch=(list(matches))[0] x = float(firstmatch.group(1)) y = float(firstmatch.group(2)) z = float(firstmatch.group(3)) f = float(firstmatch.group(4)) dx = x - ox dy = y - oy dz = z - oz dist = math.sqrt(dx*dx + dy*dy + dz*dz) dur = dist / f return x, y, z, f, dist, dur except: # Something went wrong adsk.core.Application.get().userInterface.messageBox(p,"Failed to match OnLinear regex") raise return ox, oy, oz, of, 0, 0 def ParseOnCircular(p, ox, oy, oz, of): # Does not correctly calculate angle difference for multiple revolutions, such as a helix ramp try: matches = re.finditer(CIRCULAR_REGEX, p, re.ASCII) firstmatch=(list(matches))[0] cw = bool(firstmatch.group(1)) cx = float(firstmatch.group(2)) cy = float(firstmatch.group(3)) cz = float(firstmatch.group(4)) x = float(firstmatch.group(5)) y = float(firstmatch.group(6)) z = float(firstmatch.group(7)) f = float(firstmatch.group(8)) # Find start and finish offset from centre sdx = ox - cx sdy = oy - cy sdz = oz - cz fdx = x - cx fdy = y - cy fdz = z - cz dx = abs(x - ox) dy = abs(y - oy) dz = abs(z - oz) # Find which plane the rotation is in axis = "Z" # Look for the smallest axis change and assume a circle or helix around that if dx <= dy and dx <= dz: axis = "X" if dy <= dx and dy <= dz: axis = "Y" if dz <= dx and dz <= dy: axis = "Z" if axis == "X": r1 = math.sqrt(sdy*sdy + sdz*sdz) a1 = math.atan2(sdy, sdz) a2 = math.atan2(fdy, fdz) dother = dx elif axis == "Y": r1 = math.sqrt(sdx*sdx + sdz*sdz) a1 = math.atan2(sdz, sdx) a2 = math.atan2(fdz, fdx) dother = dy else: r1 = math.sqrt(sdx*sdx + sdy*sdy) a1 = math.atan2(sdy, sdx) a2 = math.atan2(fdy, fdx) dother = dz # How far around the circle? da = diffAngle(cw, a1, a2) dist = da * r1 if dother != 0: dist = math.sqrt(dist * dist + dother * dother) dur = dist / f return x, y, z, f, dist, dur except: # Something went wrong adsk.core.Application.get().userInterface.messageBox(p,"Failed to match OnCircular regex") raise return ox, oy, oz, of, 0, 0 def run(context): ui = None allstocksizes = {} allstocklimits = {} alltools = {} setuptools = {} operationtools = {} alloperations = {} allparameters = {} tempfiles = [] distances = {} durations = {} tooldistances = {} tooldurations = {} try: # Get access to various application and document levels app = adsk.core.Application.get() ui = app.userInterface if not TXTOUTPUT and not HTMLOUTPUT and not SCREENOUTPUT: ui.messageBox("No output modes are enabled\nWhy are we doing this?", "Waste of time") return doc = app.activeDocument products = doc.products product = products.itemByProductType('CAMProductType') # check if the document has a CAMProductType if product == None: ui.messageBox('There are no CAM operations in the active document. This script requires the active document to contain at least one CAM operation.', 'No CAM Operations Exist', adsk.core.MessageBoxButtonTypes.OKButtonType, adsk.core.MessageBoxIconTypes.CriticalIconType) return cam = adsk.cam.CAM.cast(product) for setup in cam.setups: if not setup.isValid: ui.messageBox("Invalid setup", setup.name) continue alloperations[setup.name] = {} allparameters[setup.name] = {} setuptools[setup.name] = [] operationtools[setup.name] = {} distances[setup.name] = {} durations[setup.name] = {} operations = setup.allOperations for operation in operations: alloperations[setup.name][operation.name] = {} distances[setup.name][operation.name]=0 durations[setup.name][operation.name]=0 # Get operation information via the Dumper post processor # Indirect method as not all information is directly exposed by the API # This seems to be the only way of getting stock size information at least programName = 'postdump_'+doc.name+"_"+setup.name+"_"+operation.name outputFolder = cam.temporaryFolder firstSetupOperationType = cam.setups.item(0).operationType postConfig = os.path.join(cam.genericPostFolder, 'dump.cps') units = adsk.cam.PostOutputUnitOptions.DocumentUnitsOutput postInput = adsk.cam.PostProcessInput.create(programName, postConfig, outputFolder, units) postInput.isOpenInEditor = False # create the post properties postProperties = adsk.core.NamedValues.create() # add the post properties to the post process input postInput.postProperties = postProperties # Process individual operation if operation.hasToolpath == True: cam.postProcess(operation, postInput) else: ui.messageBox('Operation {} has no toolpath to post'.format(operation.name)) continue # Let the file processing finish fname = os.path.join(outputFolder,programName+".dmp") if not WaitForFile(fname): continue # Read the dump back in and look for key information tempfiles.append(fname) fdump = open(fname,"r") lnum = 0 stockline="" toolnum = 0 tooldesc = "" toolstrat = "" tooltype = "" toolunit = "" toolcool = "" tooldia = 0 toollen = 0 toolflutelen = 0 toolflutes = 0 toolshaft = 0 posx = 0 posy = 0 posz = 0 feedspeed = 1 minspeed = float('inf') maxspeed = 0 distance = 0 cuttime = 0 # Read each line for dline in fdump.readlines(): lnum += 1 if dline.find("onParameter(") >= 0: pkey, pvalue = ParseOnParameter(dline) if pkey != "": # A possibly useful bit of information, so cache it allparameters[setup.name][operation.name+"|"+pkey] = pvalue # Recognise what we need if pkey == "stock": stockline = pvalue if pkey == "operation:tool_number": toolnum = pvalue if pkey == "operation:tool_description": tooldesc = pvalue if pkey == "operation-strategy": toolstrat = pvalue if pkey == "operation:tool_type": tooltype = pvalue if pkey == "operation:tool_diameter": tooldia = pvalue if pkey == "operation:tool_bodyLength": toollen = pvalue if pkey == "operation:tool_fluteLength": toolflutelen = pvalue if pkey == "operation:tool_numberOfFlutes": toolflutes = pvalue if pkey == "operation:tool_shaftDiameter": toolshaft = pvalue if pkey == "operation:tool_unit": toolunit = pvalue if pkey == "operation:tool_coolant": toolcool = pvalue if dline.find("STATE position") >= 0: posx, posy, posz = ParseOnStatePosition(dline) if dline.find("onLinear") >= 0: posx, posy, posz, feedspeed, dist, dur = ParseOnLinear(dline, posx, posy, posz, feedspeed) distance += dist cuttime += dur if feedspeed > maxspeed: maxspeed = feedspeed if feedspeed < minspeed: minspeed = feedspeed if dline.find("onCircular") >= 0: posx, posy, posz, feedspeed, dist, dur = ParseOnCircular(dline, posx, posy, posz, feedspeed) distance += dist cuttime += dur if feedspeed > maxspeed: maxspeed = feedspeed if feedspeed < minspeed: minspeed = feedspeed fdump.close() operationtools[setup.name][operation.name] = toolnum if stockline == "": ui.messageBox(str(lnum)+" lines searched, but no stock information found") else: # Rearrange the stock information to a useful format stocksize = stockline.replace("\'","").replace("(","").replace(")","") msg = "Stock is {}\n".format(stocksize) stocksize = stocksize.split(",") minx = stocksize[0] miny = stocksize[1] minz = stocksize[2] maxx = stocksize[3] maxy = stocksize[4] maxz = stocksize[5] allstocksizes[setup.name]="{} x {} x {}".format(float(maxx)-float(minx), float(maxy)-float(miny), float(maxz)-float(minz)) allstocklimits[setup.name]="Lower: {}, {}, {}; Upper: {}, {}, {}".format(minx, miny, minz, maxx, maxy, maxz) # Store tooling information related to the operation msg += "Tool number: {}\n".format(toolnum) msg += "{}".format(tooldesc) if toolnum != 0: if toolnum not in alltools: alltools[toolnum] = {} alltools[toolnum]["description"] = tooldesc alltools[toolnum]["type"] = tooltype alltools[toolnum]["cuttingdiameter"] = tooldia alltools[toolnum]["length"] = toollen alltools[toolnum]["flutelength"] = toolflutelen alltools[toolnum]["numflutes"] = toolflutes alltools[toolnum]["shaftdiameter"] = toolshaft alltools[toolnum]["units"] = toolunit alltools[toolnum]["minspeed"] = minspeed alltools[toolnum]["maxspeed"] = maxspeed if toolnum not in setuptools[setup.name]: setuptools[setup.name].append(toolnum) if toolnum not in tooldistances: tooldistances[toolnum] = 0 if toolnum not in tooldurations: tooldurations[toolnum] = 0 alloperations[setup.name][operation.name]["tool"] = toolnum alloperations[setup.name][operation.name]["strategy"] = toolstrat alloperations[setup.name][operation.name]["minspeed"] = minspeed alloperations[setup.name][operation.name]["maxspeed"] = maxspeed alloperations[setup.name][operation.name]["coolant"] = toolcool distances[setup.name][operation.name]=distance durations[setup.name][operation.name]=cuttime tooldistances[toolnum] = tooldistances[toolnum] + distance tooldurations[toolnum] = tooldurations[toolnum] + cuttime # Report wanted information msg = doc.name + "\nStock:\n" for stock in allstocksizes: msg += "\t"+stock+":\n" msg += "\t\tSize: "+allstocksizes[stock]+"\n" msg += "\t\t"+allstocklimits[stock]+"\n" msg += "\nOperations:\n" for setup in alloperations: d = 0 t = 0 for op in distances[setup]: d += distances[setup][op] for op in durations[setup]: t += durations[setup][op] msg += "\t{} ({:.0f}mm in {:d}m{:d}s not allowing for acc/deceleration)\n".format(setup, d, int(t), int(t*60) % 60) msg += "\t\tTools: " for t in setuptools[setup]: msg += "#{} ".format(t) msg += "\n" operationsdetails = alloperations[setup] for op in operationsdetails: msg += "\t\t{}: {} with #{}\n".format(op, operationsdetails[op]["strategy"], operationsdetails[op]["tool"]) msg += "\nFull tool list:\n" for tool in alltools: msg += "\t#{}: {}\n".format(tool, alltools[tool]["description"]) if TXTOUTPUT: # Write it to a file as well homedir = pathlib.Path.home() outputname = os.path.join(homedir,doc.name+"_setup.txt") foutput = open(outputname,"w") foutput.write(msg) # Add other parsed information foutput.write("\n\n\n") for setup in allparameters: for pkey in allparameters[setup]: pvalue = allparameters[setup][pkey] foutput.write("{}|{} = {}\n".format(setup, pkey, pvalue)) foutput.write("\nProduced by {}\n".format(THISSCRIPT)) foutput.flush() foutput.close() # Open the file OpenFile(outputname) if HTMLOUTPUT: # Write HTML version homedir = pathlib.Path.home() outputname = os.path.join(homedir,doc.name+" setupsheet.html") foutput = open(outputname,"w") title = "Setup Sheet for {}".format(doc.name) HTMLheader(foutput,title) foutput.write("<body>\n") HTMLBodyTitle(foutput,title) HTMLsetups(foutput, allstocksizes, allstocklimits) foutput.write("<br><br>\n") HTMLtools(foutput, alltools, tooldistances, tooldurations) foutput.write("<br><br>\n") HTMLoperations(foutput, alltools, alloperations, allparameters, distances, durations) foutput.write("\n<br><div align=\"left\" style=\"font-size:5pt; color: PowderBlue\">Produced by {}</div>\n".format(THISSCRIPT)) foutput.write("</body>") foutput.flush() foutput.close() # Open the file OpenFile(outputname) if SCREENOUTPUT: # Display the information on screen ui.messageBox(msg, doc.name) except: if ui: ui.messageBox('Failed:\n{}'.format(traceback.format_exc())) #Clear up temporary files sleep(1) for f in tempfiles: os.remove(f) def HTMLheader(f, title): f.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n") f.write(" \"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\n") f.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n") f.write(STYLESHEET) f.write("<title>{}</title>\n".format(title)) f.write("</head>\n") def HTMLBodyTitle(f, title): f.write("<h1>{}</h1>\n".format(title)) def HTMLsetups(f, sizes, limits): f.write("<table class=\"setup\" cellspacing=0 align=\"center\">\n") f.write("<tr><th colspan=3>Stocks</th></tr>\n") f.write("<tr class=\"lined\"><td class=\"description\">Setup name</td><td class=\"description\">Stock Size</td><td class=\"description\">Limits</td></tr>") for setup in sizes: f.write("<tr><td>") f.write("<div class=\"value\"><b>{}</b></div>".format(setup)) f.write("</td>\n<td>") f.write("<div class=\"value\">{}</div>".format(sizes[setup])) f.write("</td>\n<td>") f.write("<div class=\"value\">") limitlist = limits[setup].split(";") for n in range(len(limitlist)): limit = limitlist[n].strip() f.write("{}".format(limit)) if n < len(limitlist)-1 : f.write("<br>") f.write("</div></td></tr>\n") f.write("</table>\n") def HTMLtools(f, toollist, tooldist, tooltime): f.write("<table class=\"setup\" cellspacing=0 align=\"center\">\n") f.write("<tr><th colspan=2>Tools</th></tr>\n") for t in toollist: if toollist[t]["units"] == "millimeters" or toollist[t]["units"] == "mm": units = "mm" else: units = "in" f.write("<tr class=\"tool\"><td colspan=2 align=\"left\"><b>#{}</b></td></tr>\n".format(t)) f.write("<tr class=\"lined\"><td class=\"description\">Description</td><td class=\"description\">Usage</td></tr>") f.write("<tr><td>") f.write("<div class=\"value\"><b>{}</b></div>".format(toollist[t]["description"])) f.write("<br>") f.write("<div class=\"description\">Type: </div>") f.write("<div class=\"value\">{}</div>".format(toollist[t]["type"])) f.write("<br>") f.write("<div class=\"description\">Cutting diameter: </div>") f.write("<div class=\"value\">{}{}</div>".format(toollist[t]["cuttingdiameter"], units)) f.write("<br>") f.write("<div class=\"description\">External length: </div>") f.write("<div class=\"value\">{}{}</div>".format(toollist[t]["length"], units)) f.write("<br>") #f.write("<div class=\"description\">Flute length: </div>") #f.write("<div class=\"value\">{}{}</div>".format(toollist[t]["flutelength"], units)) #f.write("<br>") f.write("<div class=\"description\">Number of flutes: </div>") f.write("<div class=\"value\">{}</div>".format(toollist[t]["numflutes"])) f.write("<br>") f.write("<div class=\"description\">Shaft diameter: </div>") f.write("<div class=\"value\">{}{}</div>".format(toollist[t]["shaftdiameter"], units)) f.write("</td><td>") f.write("<div class=\"description\">Travel: </div>") f.write("<div class=\"value\">{:.0f}{}</div>".format(tooldist[t], units)) f.write("<br>") f.write("<div class=\"description\">Time: </div>") f.write("<div class=\"value\">{}m{}s</div>".format(int(tooltime[t]), int(tooltime[t]*60) % 60)) f.write("<br>") f.write("<div class=\"description\">Minimum cutting speed: </div>") f.write("<div class=\"value\">{:.1f}{}/min</div>".format(toollist[t]["minspeed"], units)) f.write("<br>") f.write("<div class=\"description\">Maximum cutting speed: </div>") f.write("<div class=\"value\">{:.1f}{}/min</div>".format(toollist[t]["maxspeed"], units)) f.write("</td></tr>") f.write("</table>\n") def HTMLoperations(f, toollist, operations, allparams, dist, dur): for setup in operations: f.write("<table class=\"setup\" cellspacing=0 align=\"center\">\n") f.write("<tr><th colspan=3>Operations for {}</th></tr>\n".format(setup)) setupparams = allparams[setup] n = 0 for op in operations[setup]: n += 1 basename="{}|".format(op) f.write("<tr class=\"tool\"><td colspan=2 align=\"left\">Operations {}/{}: {}</td>".format(n, len(operations[setup]), op)) toolnum = operations[setup][op]["tool"] units = toollist[toolnum]["units"] if units == "millimeters" or units == "mm": units = "mm" else: units = "in" f.write("<td>#{}</td></tr>\n".format(toolnum)) f.write("<tr><td>") f.write("<div class=\"description\">Strategy: </div><div class=\"value\">{}</div>".format(operations[setup][op]["strategy"])) if basename+"operation:tolerance" in setupparams: f.write("<br><div class=\"description\">Tolerance: </div><div class=\"value\">{}{}</div>".format(setupparams[basename+"operation:tolerance"],units)) if basename+"operation:maximumStepdown" in setupparams: f.write("<br><div class=\"description\">Max stepdown: </div><div class=\"value\">{}{}</div>".format(setupparams[basename+"operation:maximumStepdown"],units)) if basename+"operation:maximumStepover" in setupparams: f.write("<br><div class=\"description\">Max stepover: </div><div class=\"value\">{}{}</div>".format(setupparams[basename+"operation:maximumStepover"],units)) if basename+"operation:optimalLoad" in setupparams: f.write("<br><div class=\"description\">Optical load: </div><div class=\"value\">{}{}</div>".format(setupparams[basename+"operation:optimalLoad"],units)) f.write("</td><td>") f.write("<div class=\"description\">Distance: </div><div class=\"value\">{:.0f}{}</div>".format(dist[setup][op],units)) duration = dur[setup][op] f.write("<br><div class=\"description\">Time: </div><div class=\"value\">{}m{}s</div>".format(int(duration), int(duration*60) % 60)) f.write("<br><div class=\"description\">Minimum speed: </div><div class=\"value\">{:.1f}{}/min</div>".format(operations[setup][op]["minspeed"],units)) f.write("<br><div class=\"description\">Maximum speed: </div><div class=\"value\">{:.1f}{}/min</div>".format(operations[setup][op]["maxspeed"],units)) f.write("<br><div class=\"description\">Coolant: </div><div class=\"value\">{}</div>".format(operations[setup][op]["coolant"])) f.write("</td><td>") f.write("<div class=\"description\">Type: </div>") f.write("<div class=\"value\">{}</div>".format(toollist[toolnum]["type"])) f.write("<br>") f.write("<div class=\"description\">Diameter: </div>") f.write("<div class=\"value\">{}{}</div>".format(toollist[toolnum]["cuttingdiameter"], units)) f.write("<br>") f.write("<div class=\"description\">External length: </div>") f.write("<div class=\"value\">{}{}</div>".format(toollist[toolnum]["length"], units)) f.write("<br>") f.write("<div class=\"description\">Number of flutes: </div>") f.write("<div class=\"value\">{}</div>".format(toollist[toolnum]["numflutes"])) f.write("<br>") f.write("<div class=\"value\">{}</div>".format(toollist[toolnum]["description"])) f.write("</td></tr>") f.write("</table><br>")
[ "os.remove", "pathlib.Path.home", "math.sqrt", "math.atan2", "re.finditer", "os.system", "time.sleep", "pathlib.Path", "traceback.format_exc", "os.path.join", "os.startfile" ]
[((2411, 2426), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (2421, 2426), False, 'import time\n'), ((2441, 2460), 'pathlib.Path', 'pathlib.Path', (['fname'], {}), '(fname)\n', (2453, 2460), False, 'import pathlib\n'), ((2737, 2752), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (2747, 2752), False, 'import time\n'), ((2294, 2324), 'os.system', 'os.system', (['(\'open "%s"\' % fname)'], {}), '(\'open "%s"\' % fname)\n', (2303, 2324), False, 'import os, sys, re\n'), ((2573, 2588), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (2583, 2588), False, 'import time\n'), ((2844, 2859), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (2854, 2859), False, 'import time\n'), ((3001, 3041), 're.finditer', 're.finditer', (['POSITION_REGEX', 'p', 're.ASCII'], {}), '(POSITION_REGEX, p, re.ASCII)\n', (3012, 3041), False, 'import os, sys, re\n'), ((3473, 3514), 're.finditer', 're.finditer', (['PARAMETER_REGEX', 'p', 're.ASCII'], {}), '(PARAMETER_REGEX, p, re.ASCII)\n', (3484, 3514), False, 'import os, sys, re\n'), ((3944, 3982), 're.finditer', 're.finditer', (['LINEAR_REGEX', 'p', 're.ASCII'], {}), '(LINEAR_REGEX, p, re.ASCII)\n', (3955, 3982), False, 'import os, sys, re\n'), ((4252, 4290), 'math.sqrt', 'math.sqrt', (['(dx * dx + dy * dy + dz * dz)'], {}), '(dx * dx + dy * dy + dz * dz)\n', (4261, 4290), False, 'import math\n'), ((4703, 4743), 're.finditer', 're.finditer', (['CIRCULAR_REGEX', 'p', 're.ASCII'], {}), '(CIRCULAR_REGEX, p, re.ASCII)\n', (4714, 4743), False, 'import os, sys, re\n'), ((19362, 19374), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (19371, 19374), False, 'import os, sys, re\n'), ((2361, 2380), 'os.startfile', 'os.startfile', (['fname'], {}), '(fname)\n', (2373, 2380), False, 'import os, sys, re\n'), ((5678, 5710), 'math.sqrt', 'math.sqrt', (['(sdy * sdy + sdz * sdz)'], {}), '(sdy * sdy + sdz * sdz)\n', (5687, 5710), False, 'import math\n'), ((5724, 5744), 'math.atan2', 'math.atan2', (['sdy', 'sdz'], {}), '(sdy, sdz)\n', (5734, 5744), False, 'import math\n'), ((5762, 5782), 'math.atan2', 'math.atan2', (['fdy', 'fdz'], {}), '(fdy, fdz)\n', (5772, 5782), False, 'import math\n'), ((6277, 6317), 'math.sqrt', 'math.sqrt', (['(dist * dist + dother * dother)'], {}), '(dist * dist + dother * dother)\n', (6286, 6317), False, 'import math\n'), ((17422, 17441), 'pathlib.Path.home', 'pathlib.Path.home', ([], {}), '()\n', (17439, 17441), False, 'import pathlib\n'), ((17467, 17513), 'os.path.join', 'os.path.join', (['homedir', "(doc.name + '_setup.txt')"], {}), "(homedir, doc.name + '_setup.txt')\n", (17479, 17513), False, 'import os, sys, re\n'), ((18152, 18171), 'pathlib.Path.home', 'pathlib.Path.home', ([], {}), '()\n', (18169, 18171), False, 'import pathlib\n'), ((18197, 18249), 'os.path.join', 'os.path.join', (['homedir', "(doc.name + ' setupsheet.html')"], {}), "(homedir, doc.name + ' setupsheet.html')\n", (18209, 18249), False, 'import os, sys, re\n'), ((5850, 5882), 'math.sqrt', 'math.sqrt', (['(sdx * sdx + sdz * sdz)'], {}), '(sdx * sdx + sdz * sdz)\n', (5859, 5882), False, 'import math\n'), ((5896, 5916), 'math.atan2', 'math.atan2', (['sdz', 'sdx'], {}), '(sdz, sdx)\n', (5906, 5916), False, 'import math\n'), ((5934, 5954), 'math.atan2', 'math.atan2', (['fdz', 'fdx'], {}), '(fdz, fdx)\n', (5944, 5954), False, 'import math\n'), ((6010, 6042), 'math.sqrt', 'math.sqrt', (['(sdx * sdx + sdy * sdy)'], {}), '(sdx * sdx + sdy * sdy)\n', (6019, 6042), False, 'import math\n'), ((6056, 6076), 'math.atan2', 'math.atan2', (['sdy', 'sdx'], {}), '(sdy, sdx)\n', (6066, 6076), False, 'import math\n'), ((6094, 6114), 'math.atan2', 'math.atan2', (['fdy', 'fdx'], {}), '(fdy, fdx)\n', (6104, 6114), False, 'import math\n'), ((8982, 9029), 'os.path.join', 'os.path.join', (['cam.genericPostFolder', '"""dump.cps"""'], {}), "(cam.genericPostFolder, 'dump.cps')\n", (8994, 9029), False, 'import os, sys, re\n'), ((9874, 9922), 'os.path.join', 'os.path.join', (['outputFolder', "(programName + '.dmp')"], {}), "(outputFolder, programName + '.dmp')\n", (9886, 9922), False, 'import os, sys, re\n'), ((19261, 19283), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (19281, 19283), False, 'import adsk.core, adsk.fusion, adsk.cam, traceback\n')]
from torch import nn from drnn import DRNN class DRNN_Copy(nn.Module): def __init__(self, input_size, hidden_size, num_layers, dropout, output_size): super(DRNN_Copy, self).__init__() self.drnn = DRNN(cell_type='GRU', dropout=dropout, n_hidden=hidden_size, n_input=input_size, n_layers=num_layers, batch_first=True) self.linear = nn.Linear(hidden_size, output_size) self.init_weights() def init_weights(self): self.linear.weight.data.normal_(0,0.01) def forward(self, x): # x: (batch, steps, input_size) y1, _ = self.drnn(x) # y1: (batch, steps, hidden_size) #import pdb #pdb.set_trace() return self.linear(y1) # (batch, steps, output_size)
[ "drnn.DRNN", "torch.nn.Linear" ]
[((219, 343), 'drnn.DRNN', 'DRNN', ([], {'cell_type': '"""GRU"""', 'dropout': 'dropout', 'n_hidden': 'hidden_size', 'n_input': 'input_size', 'n_layers': 'num_layers', 'batch_first': '(True)'}), "(cell_type='GRU', dropout=dropout, n_hidden=hidden_size, n_input=\n input_size, n_layers=num_layers, batch_first=True)\n", (223, 343), False, 'from drnn import DRNN\n'), ((386, 421), 'torch.nn.Linear', 'nn.Linear', (['hidden_size', 'output_size'], {}), '(hidden_size, output_size)\n', (395, 421), False, 'from torch import nn\n')]
""" .. function:: execnselect(query:None, [path:None, variables]) This function expecting the query results to be target queries for execution (similar to exec). Base on the parameters executes the target queries with the appropriate execution environment and returns the results of the last target query. *path* : set up the current working directory for the target queries execution. *variables* : key type variables references to the current environment variable value and key:value type variables are set up in the target queries execution environment. ***Notice also that forwards the connecntions to the target environment. """ import apsw import functions import os import re comment_line = re.compile(r'/\*.*?\*/(.*)$') registered = True def filterlinecomment(s): if re.match(r'\s*--', s, re.DOTALL | re.UNICODE): return '' else: return s # TODO Fix bug, break queries same line def breakquery(q): if len(q) > 1: raise functions.OperatorError(__name__.rsplit('.')[-1], "Ambiguous query column, result has more than one columns") st = '' for row in q[0].splitlines(): strow = filterlinecomment(row) if strow == '': continue if st != '': st += '\n' + strow else: st += strow if apsw.complete(st): yield st st = '' if len(st) > 0 and not re.match(r'\s+$', st, re.DOTALL | re.UNICODE): if len(st) > 35: raise functions.OperatorError(__name__.rsplit('.')[-1], "Incomplete statement found : %s ... %s" % (st[:15], st[-15:])) else: raise functions.OperatorError(__name__.rsplit('.')[-1], "Incomplete statement found : %s" % (st,)) class ExecNSelectVT(functions.vtable.vtbase.VT): def VTiter(self, *parsedArgs, **envars): # default parsing largs, dictargs = self.full_parse(parsedArgs) # print largs # print dictargs # get default connection connection = envars['db'] if functions.variables.execdb is None: functions.variables.execdb = connection.filename tconnection = functions.Connection(functions.variables.execdb) functions.register(tconnection) # get query if 'query' not in dictargs: raise functions.OperatorError(__name__.rsplit('.')[-1], "No query argument.") # print "error 1" else: query = dictargs['query'] # set up variables oldvars = functions.variables newvars = lambda x: x newpath = None path = os.getcwd() if 'path' in dictargs: newpath = os.path.abspath(dictargs['path']) del dictargs['path'] os.chdir(newpath) newvars.execdb = functions.variables.execdb newvars.flowname = 'notset' for key in largs: if hasattr(functions.variables, key): setattr(newvars, key, getattr(functions.variables, key)) else: raise functions.OperatorError(__name__.rsplit('.')[-1], "Variable %s doesn't exist" % (key,)) # print "error 2" for key, value in dictargs.items(): setattr(newvars, key, value) functions.variables = newvars # execute target queries try: counter = -1 cursor = connection.cursor() tcursor = tconnection.cursor() tqlast = '' databases = cursor.execute("PRAGMA database_list") for database in databases: dbname = database[1] dbfile = database[2] if dbname != "main" and dbname != "mem" and dbname != "temp" and dbfile != '': list(tcursor.execute("attach database '{0}' as {1};".format(dbfile, dbname))) counter = 0 results = cursor.execute(query, parse=False) for result in results: for tquery in breakquery(result): # print "tquery", tquery # print "tqlast", tqlast if tqlast != '': list(tcursor.execute(tqlast)) counter += 1 tqlast = tquery # print "tqlast", len(tqlast) if len(tqlast) > 0: tresults = tcursor.execute(tqlast) counter += 1 # print 'lala3' try: yield tcursor.getdescriptionsafe() except apsw.ExecutionCompleteError: try: raise finally: try: tcursor.close() tconnection.close() cursor.close() except: pass else: for tresult in tresults: yield tresult else: yield ('c1',) tcursor.close() tconnection.close() cursor.close() except Exception as ex: import traceback traceback.print_exc() raise functions.OperatorError(__name__.rsplit('.')[-1], "Error in query no. %d - %s" % (counter, str(ex))) # print "error 3" # restore env functions.variables = oldvars if newpath: os.chdir(path) def Source(): return functions.vtable.vtbase.VTGenerator(ExecNSelectVT) if not ('.' in __name__): """ This is needed to be able to test the function, put it at the end of every new function you create. """ import sys from functions import * testfunction() if __name__ == "__main__": reload(sys) sys.setdefaultencoding('utf-8') import doctest doctest.testmod()
[ "os.path.abspath", "traceback.print_exc", "os.getcwd", "functions.register", "re.match", "apsw.complete", "functions.Connection", "sys.setdefaultencoding", "functions.vtable.vtbase.VTGenerator", "os.chdir", "doctest.testmod", "re.compile" ]
[((725, 755), 're.compile', 're.compile', (['"""/\\\\*.*?\\\\*/(.*)$"""'], {}), "('/\\\\*.*?\\\\*/(.*)$')\n", (735, 755), False, 'import re\n'), ((808, 853), 're.match', 're.match', (['"""\\\\s*--"""', 's', '(re.DOTALL | re.UNICODE)'], {}), "('\\\\s*--', s, re.DOTALL | re.UNICODE)\n", (816, 853), False, 'import re\n'), ((5609, 5659), 'functions.vtable.vtbase.VTGenerator', 'functions.vtable.vtbase.VTGenerator', (['ExecNSelectVT'], {}), '(ExecNSelectVT)\n', (5644, 5659), False, 'import functions\n'), ((1373, 1390), 'apsw.complete', 'apsw.complete', (['st'], {}), '(st)\n', (1386, 1390), False, 'import apsw\n'), ((2256, 2304), 'functions.Connection', 'functions.Connection', (['functions.variables.execdb'], {}), '(functions.variables.execdb)\n', (2276, 2304), False, 'import functions\n'), ((2313, 2344), 'functions.register', 'functions.register', (['tconnection'], {}), '(tconnection)\n', (2331, 2344), False, 'import functions\n'), ((2708, 2719), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2717, 2719), False, 'import os\n'), ((5935, 5966), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (5957, 5966), False, 'import sys\n'), ((5999, 6016), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (6014, 6016), False, 'import doctest\n'), ((1461, 1506), 're.match', 're.match', (['"""\\\\s+$"""', 'st', '(re.DOTALL | re.UNICODE)'], {}), "('\\\\s+$', st, re.DOTALL | re.UNICODE)\n", (1469, 1506), False, 'import re\n'), ((2773, 2806), 'os.path.abspath', 'os.path.abspath', (["dictargs['path']"], {}), "(dictargs['path'])\n", (2788, 2806), False, 'import os\n'), ((2852, 2869), 'os.chdir', 'os.chdir', (['newpath'], {}), '(newpath)\n', (2860, 2869), False, 'import os\n'), ((5567, 5581), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (5575, 5581), False, 'import os\n'), ((5304, 5325), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (5323, 5325), False, 'import traceback\n')]
import pandas as pd import numpy as np from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score import time import matplotlib.pyplot as plt df = pd.read_csv("FinalData2.csv") df['label'] = df['label'].map({1: -1,0 : 1}) df.head() print(df.dtypes) from sklearn.cluster import DBSCAN t1 = time.process_time() outlier_detection = DBSCAN(eps = 4, metric="euclidean",min_samples = 2, n_jobs = -1) t2 = time.process_time() print("Training time is: ", (t2-t1)) t3 = time.process_time() clusters_o = outlier_detection.fit_predict(df[['blk_id', 'logType', 'location','ips','logmessageInfo','logMesType','logCount','ports','time']]) t4 = time.process_time() print("Prediction time is: ", (t4-t3)) for i in clusters_o: if i != -1: print("\n",i) print('\n\nClusters:\n') print(clusters_o) print('\n\n') #squarer = lambda t: if (t!=-1): t = 0 cluster_list = clusters_o.tolist() for i in range(len(cluster_list)): if cluster_list[i] != -1: cluster_list[i] = 1 #clustersoo[clustersoo != -1] = 0 acc = accuracy_score(df['label'], cluster_list) f1sc = f1_score(df['label'], cluster_list) prec = precision_score(df['label'], cluster_list) recal = recall_score(df['label'], cluster_list) print("Accuracy Score: ", acc) print("F1 Score: ", f1sc) print("Precision Score: ", prec) print("Recall Score: ", recal) from matplotlib import cm #cmap = cm.get_cmap("Set1") #plt.scatter(x=num[:,0],y=num[:,-1], c=clusters, cmap=cmap,colorbar = False) #plt.savefig('books_read.png') #plt.close() indx = [] acc_list = [] f1sc_list = [] prec_list = [] recal_list = [] for i in range(100,len(df['label']),900): acc_list.append(100*accuracy_score(df['label'][:i+1], cluster_list[:i+1])) f1sc_list.append(100*f1_score(df['label'][:i+1], cluster_list[:i+1])) prec_list.append(100*precision_score(df['label'][:i+1], cluster_list[:i+1])) recal_list.append(100*recall_score(df['label'][:i+1], cluster_list[:i+1])) indx.append(i+1) print(indx[0]) print(indx[1]) print(indx[2]) plt.plot(indx, acc_list) plt.plot(indx, f1sc_list) plt.plot(indx, prec_list) plt.plot(indx, recal_list) plt.xlabel('Number of records') plt.ylabel('Metric Value') plt.legend(["Accuracy", "F1 score","Precision","Recall"]) plt.savefig('DBS_metrics.png')
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "pandas.read_csv", "time.process_time", "sklearn.metrics.accuracy_score", "matplotlib.pyplot.legend", "sklearn.metrics.recall_score", "sklearn.metrics.f1_score", "sklearn.metrics.precision_score", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "sklearn.cluster.DBSCAN" ]
[((172, 201), 'pandas.read_csv', 'pd.read_csv', (['"""FinalData2.csv"""'], {}), "('FinalData2.csv')\n", (183, 201), True, 'import pandas as pd\n'), ((317, 336), 'time.process_time', 'time.process_time', ([], {}), '()\n', (334, 336), False, 'import time\n'), ((357, 416), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': '(4)', 'metric': '"""euclidean"""', 'min_samples': '(2)', 'n_jobs': '(-1)'}), "(eps=4, metric='euclidean', min_samples=2, n_jobs=-1)\n", (363, 416), False, 'from sklearn.cluster import DBSCAN\n'), ((427, 446), 'time.process_time', 'time.process_time', ([], {}), '()\n', (444, 446), False, 'import time\n'), ((489, 508), 'time.process_time', 'time.process_time', ([], {}), '()\n', (506, 508), False, 'import time\n'), ((658, 677), 'time.process_time', 'time.process_time', ([], {}), '()\n', (675, 677), False, 'import time\n'), ((1041, 1082), 'sklearn.metrics.accuracy_score', 'accuracy_score', (["df['label']", 'cluster_list'], {}), "(df['label'], cluster_list)\n", (1055, 1082), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n'), ((1090, 1125), 'sklearn.metrics.f1_score', 'f1_score', (["df['label']", 'cluster_list'], {}), "(df['label'], cluster_list)\n", (1098, 1125), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n'), ((1133, 1175), 'sklearn.metrics.precision_score', 'precision_score', (["df['label']", 'cluster_list'], {}), "(df['label'], cluster_list)\n", (1148, 1175), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n'), ((1184, 1223), 'sklearn.metrics.recall_score', 'recall_score', (["df['label']", 'cluster_list'], {}), "(df['label'], cluster_list)\n", (1196, 1223), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n'), ((2022, 2046), 'matplotlib.pyplot.plot', 'plt.plot', (['indx', 'acc_list'], {}), '(indx, acc_list)\n', (2030, 2046), True, 'import matplotlib.pyplot as plt\n'), ((2047, 2072), 'matplotlib.pyplot.plot', 'plt.plot', (['indx', 'f1sc_list'], {}), '(indx, f1sc_list)\n', (2055, 2072), True, 'import matplotlib.pyplot as plt\n'), ((2073, 2098), 'matplotlib.pyplot.plot', 'plt.plot', (['indx', 'prec_list'], {}), '(indx, prec_list)\n', (2081, 2098), True, 'import matplotlib.pyplot as plt\n'), ((2099, 2125), 'matplotlib.pyplot.plot', 'plt.plot', (['indx', 'recal_list'], {}), '(indx, recal_list)\n', (2107, 2125), True, 'import matplotlib.pyplot as plt\n'), ((2126, 2157), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of records"""'], {}), "('Number of records')\n", (2136, 2157), True, 'import matplotlib.pyplot as plt\n'), ((2158, 2184), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Metric Value"""'], {}), "('Metric Value')\n", (2168, 2184), True, 'import matplotlib.pyplot as plt\n'), ((2185, 2244), 'matplotlib.pyplot.legend', 'plt.legend', (["['Accuracy', 'F1 score', 'Precision', 'Recall']"], {}), "(['Accuracy', 'F1 score', 'Precision', 'Recall'])\n", (2195, 2244), True, 'import matplotlib.pyplot as plt\n'), ((2243, 2273), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""DBS_metrics.png"""'], {}), "('DBS_metrics.png')\n", (2254, 2273), True, 'import matplotlib.pyplot as plt\n'), ((1666, 1723), 'sklearn.metrics.accuracy_score', 'accuracy_score', (["df['label'][:i + 1]", 'cluster_list[:i + 1]'], {}), "(df['label'][:i + 1], cluster_list[:i + 1])\n", (1680, 1723), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n'), ((1746, 1797), 'sklearn.metrics.f1_score', 'f1_score', (["df['label'][:i + 1]", 'cluster_list[:i + 1]'], {}), "(df['label'][:i + 1], cluster_list[:i + 1])\n", (1754, 1797), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n'), ((1820, 1878), 'sklearn.metrics.precision_score', 'precision_score', (["df['label'][:i + 1]", 'cluster_list[:i + 1]'], {}), "(df['label'][:i + 1], cluster_list[:i + 1])\n", (1835, 1878), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n'), ((1902, 1957), 'sklearn.metrics.recall_score', 'recall_score', (["df['label'][:i + 1]", 'cluster_list[:i + 1]'], {}), "(df['label'][:i + 1], cluster_list[:i + 1])\n", (1914, 1957), False, 'from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n')]
# Generated by Django 3.2 on 2021-04-14 03:23 from django.db import migrations, models import game.models class Migration(migrations.Migration): dependencies = [ ('game', '0002_alter_room_players'), ] operations = [ migrations.AlterField( model_name='room', name='status', field=models.CharField(choices=[(game.models.GameRoom.StatusType['ORGANIZE'], game.models.GameRoom.StatusType['ORGANIZE']), (game.models.GameRoom.StatusType['PLAYING'], game.models.GameRoom.StatusType['PLAYING']), (game.models.GameRoom.StatusType['END'], game.models.GameRoom.StatusType['END'])], default='organize', max_length=8), ), ]
[ "django.db.models.CharField" ]
[((348, 691), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[(game.models.GameRoom.StatusType['ORGANIZE'], game.models.GameRoom.\n StatusType['ORGANIZE']), (game.models.GameRoom.StatusType['PLAYING'],\n game.models.GameRoom.StatusType['PLAYING']), (game.models.GameRoom.\n StatusType['END'], game.models.GameRoom.StatusType['END'])]", 'default': '"""organize"""', 'max_length': '(8)'}), "(choices=[(game.models.GameRoom.StatusType['ORGANIZE'],\n game.models.GameRoom.StatusType['ORGANIZE']), (game.models.GameRoom.\n StatusType['PLAYING'], game.models.GameRoom.StatusType['PLAYING']), (\n game.models.GameRoom.StatusType['END'], game.models.GameRoom.StatusType\n ['END'])], default='organize', max_length=8)\n", (364, 691), False, 'from django.db import migrations, models\n')]
# Copyright 2017 theloop, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A module about Transaction object""" import hashlib import collections import logging import struct import time import loopchain.utils as util from enum import Enum from loopchain import configure as conf from loopchain.tools import PublicVerifierContainer class TransactionStatus(Enum): unconfirmed = 1 confirmed = 2 class TransactionType(Enum): general = 1 peer_list = 2 class Transaction: """Transaction 거래 내용 Peer에서 데이터를 받으면 새로운 트랜잭션을 생성하며, 생성된 트랜잭션은 바로 BlockGenerator 에게 전달 된다 """ PEER_ID_KEY = 'peer_id' SCORE_ID_KEY = 'score_id' SCORE_VERSION_KEY = 'score_version' CHANNEL_KEY = 'channel_name' def __init__(self): # TODO Client 의 Sign이나 인증에 대한 내용을 트랜잭션에 넣어야 하지 않을까? self.__transaction_status = TransactionStatus.unconfirmed self.__transaction_type = TransactionType.general self.__meta = collections.OrderedDict() # peer_id, score_id, score_ver ... self.__data = [] self.__time_stamp = 0 self.__transaction_hash = "" self.__public_key = b"" self.__signature = b"" @property def tx_hash(self): return self.__transaction_hash @property def status(self): return self.__transaction_status @status.setter def status(self, tx_status): self.__transaction_status = tx_status @property def type(self): return self.__transaction_type @type.setter def type(self, tx_type): self.__transaction_type = tx_type @property def signature(self): return self.__signature @property def public_key(self): return self.__public_key @property def meta(self): return self.__meta.copy() def put_meta(self, key, value): """Tx 의 meta 정보를 구성한다. tx 의 put_data 발생시 tx 의 hash 를 생성하게 되며 이때 meta 정보를 hash 계산에 사용하게 되므로 meta 정보의 구성은 put_data 이전에 완료하거나 혹은 put_data 후에 meta 정보를 추가하게 된다면 hash 를 다시 생성하여야 한다. :param key: :param value: :return: """ self.__meta[key] = value def init_meta(self, peer_id, score_id, score_ver, channel_name: str): """Tx 의 meta 정보 중 Peer 에 의해서 초기화되는 부분을 집약하였댜. tx 의 put_data 발생시 tx 의 hash 를 생성하게 되며 이때 meta 정보를 hash 계산에 사용하게 되므로 meta 정보의 구성은 put_data 이전에 완료하거나 혹은 put_data 후에 meta 정보를 추가하게 된다면 hash 를 다시 생성하여야 한다. :param peer_id: :param score_id: :param score_ver: :param channel_name: :return: """ self.put_meta(Transaction.PEER_ID_KEY, peer_id) self.put_meta(Transaction.SCORE_ID_KEY, score_id) self.put_meta(Transaction.SCORE_VERSION_KEY, score_ver) self.put_meta(Transaction.CHANNEL_KEY, channel_name) def get_data(self): """트랜잭션 데이터를 리턴합니다. :return 트랜잭션 데이터: """ return self.__data def get_data_string(self): return self.__data.decode(conf.PEER_DATA_ENCODING) def put_data(self, data, time_stamp=None): """데이터 입력 data를 받으면 해당 시간의 Time stamp와 data를 가지고 Hash를 생성해서 기록한다. :param data: Transaction에 넣고 싶은 data. data가 스트링인 경우 bytearray로 변환한다. :param time_stamp: :return Transaction의 data를 가지고 만든 Hash값: """ if isinstance(data, str): self.__data = bytearray(data, 'utf-8') else: self.__data = data if time_stamp is None: self.__time_stamp = int(time.time()*1000000) else: self.__time_stamp = time_stamp # logging.debug("transaction Time %s , time_stamp Type %s", self.__time_stamp, type(self.__time_stamp)) return self.__generate_hash() def get_timestamp(self): """트랜잭션 timeStamp를 반환 """ return self.__time_stamp def __generate_hash(self): """트랜잭션의 hash를 생성한다. :return Transaction의 data를 가지고 만든 Hash값: """ # self.__transaction_hash = Transaction.generate_transaction_hash(self) _meta_byte = util.dict_to_binary(self.__meta) _time_byte = struct.pack('Q', self.__time_stamp) _txByte = b''.join([_meta_byte, self.__data, _time_byte]) self.__transaction_hash = hashlib.sha256(_txByte).hexdigest() # logging.debug("__generate_hash \ntx hash : " + self.__transaction_hash + # "\ntx meta : " + str(self.__meta) + # "\ntx data : " + str(self.__data)) return self.__transaction_hash # TODO property.tx_hash 로 대체할 것 def get_tx_hash(self): """트랜잭션의 해쉬 값을 리턴합니다 :return: 트랜잭션의 해쉬 값 """ return self.__transaction_hash @staticmethod def generate_transaction_hash(tx): """트랜잭션 Hash 생성 :param tx: 트랜잭션 :return: 트랜잭션 Hash """ _meta_byte = util.dict_to_binary(tx.meta) _data_byte = tx.get_data() _time_byte = struct.pack('Q', tx.get_timestamp()) _txByte = b''.join([_meta_byte, _data_byte, _time_byte]) _txhash = hashlib.sha256(_txByte).hexdigest() # logging.debug("__generate_hash \ntx hash : " + _txhash + # "\ntx meta : " + str(tx.meta) + # "\ntx data : " + str(tx.get_data())) return _txhash def sign_hash(self, peer_authorization) -> bool: """sign to signature hash :param peer_authorization: peer_authorization for sign :return: if sign success return true, else return false """ signature = peer_authorization.sign_data(self.tx_hash, is_hash=True) self.__public_key = peer_authorization.get_public_der() if signature: self.__signature = signature return True else: logging.error(f"sign transaction {self.tx_hash} fail") return False @staticmethod def validate(tx, is_exception_log=True) -> bool: """validate tx(hash, signature) :param tx: transaction :return: validate result """ # HASH Validate # logging.debug("Transaction Hash %s", tx.get_tx_hash()) try: if Transaction.generate_transaction_hash(tx) != tx.get_tx_hash(): Transaction.__logging_tx_validate("hash validate fail", tx) return False # Get Cert Verifier for signature verify public_verifier = PublicVerifierContainer.get_public_verifier(tx.public_key) # Signature Validate if public_verifier.verify_hash(tx.get_tx_hash(), tx.signature): return True else: if is_exception_log: Transaction.__logging_tx_validate("signature validate fail", tx) return False except Exception as e: # logging.exception(e) if is_exception_log: Transaction.__logging_tx_validate(str(e), tx) return False @staticmethod def __logging_tx_validate(fail_message, tx): logging.error("validate tx fail \ntx hash : " + tx.get_tx_hash() + "\ntx meta : " + str(tx.meta) + "\ntx data : " + str(tx.get_data()) + "\ntx signature : " + str(tx.signature) + "\n cause by : " + fail_message)
[ "loopchain.utils.dict_to_binary", "logging.error", "struct.pack", "time.time", "hashlib.sha256", "collections.OrderedDict", "loopchain.tools.PublicVerifierContainer.get_public_verifier" ]
[((1467, 1492), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (1490, 1492), False, 'import collections\n'), ((4609, 4641), 'loopchain.utils.dict_to_binary', 'util.dict_to_binary', (['self.__meta'], {}), '(self.__meta)\n', (4628, 4641), True, 'import loopchain.utils as util\n'), ((4663, 4698), 'struct.pack', 'struct.pack', (['"""Q"""', 'self.__time_stamp'], {}), "('Q', self.__time_stamp)\n", (4674, 4698), False, 'import struct\n'), ((5418, 5446), 'loopchain.utils.dict_to_binary', 'util.dict_to_binary', (['tx.meta'], {}), '(tx.meta)\n', (5437, 5446), True, 'import loopchain.utils as util\n'), ((6350, 6404), 'logging.error', 'logging.error', (['f"""sign transaction {self.tx_hash} fail"""'], {}), "(f'sign transaction {self.tx_hash} fail')\n", (6363, 6404), False, 'import logging\n'), ((6988, 7046), 'loopchain.tools.PublicVerifierContainer.get_public_verifier', 'PublicVerifierContainer.get_public_verifier', (['tx.public_key'], {}), '(tx.public_key)\n', (7031, 7046), False, 'from loopchain.tools import PublicVerifierContainer\n'), ((4799, 4822), 'hashlib.sha256', 'hashlib.sha256', (['_txByte'], {}), '(_txByte)\n', (4813, 4822), False, 'import hashlib\n'), ((5623, 5646), 'hashlib.sha256', 'hashlib.sha256', (['_txByte'], {}), '(_txByte)\n', (5637, 5646), False, 'import hashlib\n'), ((4049, 4060), 'time.time', 'time.time', ([], {}), '()\n', (4058, 4060), False, 'import time\n')]
import numpy as np import pytest from numpy import linalg import numpy.testing as npt import itertools from utils import get_rstate, get_printing import dynesty # noqa from dynesty import utils as dyfunc # noqa """ Run a series of basic tests to check whether anything huge is broken. """ nlive = 500 printing = get_printing() def bootstrap_tol(results, rstate): """ Compute the uncertainty of means/covs by doing bootstrapping """ n = len(results.logz) niter = 50 pos = results.samples wts = np.exp(results.logwt - results.logz[-1]) means = [] covs = [] for i in range(niter): # curpos = dyfunc.resample_equal(pos, wts) # xid = np.random.randint(len(curpos), size=len(curpos)) sub = rstate.uniform(size=n) < wts / wts.max() ind0 = np.nonzero(sub)[0] ind1 = rstate.choice(ind0, size=len(ind0), replace=True) mean = pos[ind1].mean(axis=0) cov = np.cov(pos[ind1].T) means.append(mean) covs.append(cov) return np.std(means, axis=0), np.std(covs, axis=0) def check_results(results, mean_truth, cov_truth, logz_truth, mean_tol, cov_tol, logz_tol, sig=5): """ Check if means and covariances match match expectations within the tolerances """ results.summary() pos = results.samples wts = np.exp(results.logwt - results.logz[-1]) mean, cov = dyfunc.mean_and_cov(pos, wts) logz = results.logz[-1] logzerr = results.logzerr[-1] assert logzerr < 10 # check that it is not too large npt.assert_array_less(np.abs(mean - mean_truth), sig * mean_tol) npt.assert_array_less(np.abs(cov - cov_truth), sig * cov_tol) npt.assert_array_less(np.abs((logz_truth - logz)), sig * logz_tol) # GAUSSIAN TEST class Gaussian: def __init__(self, corr=.95, prior_win=10): self.ndim = 3 self.mean = np.linspace(-1, 1, self.ndim) self.cov = np.identity(self.ndim) # set covariance to identity matrix self.cov[self.cov == 0] = corr # set off-diagonal terms (strongly correlated) self.cov_inv = linalg.inv(self.cov) # precision matrix self.lnorm = -0.5 * (np.log(2 * np.pi) * self.ndim + np.log(linalg.det(self.cov))) self.prior_win = prior_win # +/- on both sides self.logz_truth = self.ndim * (-np.log(2 * self.prior_win)) # 3-D correlated multivariate normal log-likelihood def loglikelihood(self, x): """Multivariate normal log-likelihood.""" return -0.5 * np.dot( (x - self.mean), np.dot(self.cov_inv, (x - self.mean))) + self.lnorm # prior transform def prior_transform(self, u): """Flat prior between -10. and 10.""" return self.prior_win * (2. * u - 1.) # gradient (no jacobian) def grad_x(self, x): """Multivariate normal log-likelihood gradient.""" return -np.dot(self.cov_inv, (x - self.mean)) # gradient (with jacobian) def grad_u(self, x): """Multivariate normal log-likelihood gradient.""" return -np.dot(self.cov_inv, x - self.mean) * 2 * self.prior_win def check_results_gau(results, g, rstate, sig=5, logz_tol=None): if logz_tol is None: logz_tol = sig * results.logzerr[-1] mean_tol, cov_tol = bootstrap_tol(results, rstate) # just check that resample_equal works dyfunc.resample_equal(results.samples, np.exp(results.logwt - results.logz[-1])) check_results(results, g.mean, g.cov, g.logz_truth, mean_tol, cov_tol, logz_tol, sig=sig) def test_gaussian(): sig = 5 rstate = get_rstate() g = Gaussian() sampler = dynesty.NestedSampler(g.loglikelihood, g.prior_transform, g.ndim, nlive=nlive, rstate=rstate) sampler.run_nested(print_progress=printing) # check that jitter/resample/simulate_run work # for not dynamic sampler dyfunc.jitter_run(sampler.results, rstate=rstate) dyfunc.resample_run(sampler.results, rstate=rstate) dyfunc.simulate_run(sampler.results, rstate=rstate) # add samples # check continuation behavior sampler.run_nested(dlogz=0.1, print_progress=printing) # get errors nerr = 3 result_list = [] for i in range(nerr): sampler.reset() sampler.run_nested(print_progress=False) results = sampler.results result_list.append(results) pos = results.samples wts = np.exp(results.logwt - results.logz[-1]) mean, cov = dyfunc.mean_and_cov(pos, wts) logz = results.logz[-1] assert (np.abs(logz - g.logz_truth) < sig * results.logzerr[-1]) res_comb = dyfunc.merge_runs(result_list) assert (np.abs(res_comb.logz[-1] - g.logz_truth) < sig * results.logzerr[-1]) # check summary res = sampler.results res.summary() # try all combinations excepte none/unif @pytest.mark.parametrize( "bound,sample", list( itertools.product(['single', 'multi', 'balls', 'cubes', 'none'], ['unif', 'rwalk', 'slice', 'rslice']))) def test_bounding_sample(bound, sample): # check various bounding methods rstate = get_rstate() if bound == 'none': if sample != 'unif': g = Gaussian(0.1) else: g = Gaussian(corr=0., prior_win=10) # make live easy if bound is none # but also not too easy so propose_point() is exercised else: g = Gaussian() sampler = dynesty.NestedSampler(g.loglikelihood, g.prior_transform, g.ndim, nlive=nlive, bound=bound, sample=sample, rstate=rstate) sampler.run_nested(print_progress=printing) check_results_gau(sampler.results, g, rstate) @pytest.mark.parametrize("bound,sample", itertools.product( ['single', 'multi', 'balls', 'cubes'], ['unif'])) def test_bounding_bootstrap(bound, sample): # check various bounding methods rstate = get_rstate() g = Gaussian() sampler = dynesty.NestedSampler(g.loglikelihood, g.prior_transform, g.ndim, nlive=nlive, bound=bound, sample=sample, bootstrap=5, rstate=rstate) sampler.run_nested(print_progress=printing) check_results_gau(sampler.results, g, rstate) # extra checks for gradients def test_slice_nograd(): rstate = get_rstate() g = Gaussian() sampler = dynesty.NestedSampler(g.loglikelihood, g.prior_transform, g.ndim, nlive=nlive, sample='hslice', rstate=rstate) sampler.run_nested(print_progress=printing) check_results_gau(sampler.results, g, rstate) def test_slice_grad(): rstate = get_rstate() g = Gaussian() sampler = dynesty.NestedSampler(g.loglikelihood, g.prior_transform, g.ndim, nlive=nlive, sample='hslice', gradient=g.grad_x, compute_jac=True, rstate=rstate) sampler.run_nested(print_progress=printing) check_results_gau(sampler.results, g, rstate) def test_slice_grad1(): rstate = get_rstate() g = Gaussian() sampler = dynesty.NestedSampler(g.loglikelihood, g.prior_transform, g.ndim, nlive=nlive, sample='hslice', gradient=g.grad_u, rstate=rstate) sampler.run_nested(print_progress=printing) check_results_gau(sampler.results, g, rstate) def test_dynamic(): # check dynamic nested sampling behavior rstate = get_rstate() g = Gaussian() dsampler = dynesty.DynamicNestedSampler(g.loglikelihood, g.prior_transform, g.ndim, rstate=rstate) dsampler.run_nested(print_progress=printing) # chechk explicit adding batches dsampler.add_batch(mode='auto') dsampler.add_batch(mode='weight') dsampler.add_batch(mode='full') dsampler.add_batch(logl_bounds=(-10, 0), mode='manual') dsampler.add_batch(logl_bounds=(-10000000, -1000), mode='manual') check_results_gau(dsampler.results, g, rstate) # check error analysis functions dres = dyfunc.jitter_run(dsampler.results, rstate=rstate) check_results_gau(dres, g, rstate) dres = dyfunc.resample_run(dsampler.results, rstate=rstate) check_results_gau(dres, g, rstate) dres = dyfunc.simulate_run(dsampler.results, rstate=rstate) check_results_gau(dres, g, rstate) dyfunc.kld_error(dsampler.results, rstate=rstate) def test_ravel_unravel(): """ Here I test that ravel/unravel preserves things correctly """ rstate = get_rstate() g = Gaussian() dsampler = dynesty.DynamicNestedSampler(g.loglikelihood, g.prior_transform, g.ndim, bound='single', sample='unif', rstate=rstate, nlive=nlive) maxiter = 1800 dsampler.run_nested(maxiter=maxiter, use_stop=False, nlive_batch=100, print_progress=printing) dres = dsampler.results dres_list = dyfunc.unravel_run(dres) dres_merge = dyfunc.merge_runs(dres_list) assert np.abs(dres.logz[-1] - dres_merge.logz[-1]) < 0.01
[ "numpy.abs", "dynesty.utils.mean_and_cov", "dynesty.DynamicNestedSampler", "dynesty.utils.jitter_run", "numpy.exp", "utils.get_printing", "dynesty.utils.unravel_run", "numpy.std", "numpy.identity", "numpy.linspace", "dynesty.utils.simulate_run", "itertools.product", "numpy.linalg.det", "numpy.cov", "numpy.linalg.inv", "numpy.dot", "dynesty.NestedSampler", "dynesty.utils.merge_runs", "dynesty.utils.kld_error", "utils.get_rstate", "numpy.log", "dynesty.utils.resample_run", "numpy.nonzero" ]
[((317, 331), 'utils.get_printing', 'get_printing', ([], {}), '()\n', (329, 331), False, 'from utils import get_rstate, get_printing\n'), ((520, 560), 'numpy.exp', 'np.exp', (['(results.logwt - results.logz[-1])'], {}), '(results.logwt - results.logz[-1])\n', (526, 560), True, 'import numpy as np\n'), ((1451, 1491), 'numpy.exp', 'np.exp', (['(results.logwt - results.logz[-1])'], {}), '(results.logwt - results.logz[-1])\n', (1457, 1491), True, 'import numpy as np\n'), ((1508, 1537), 'dynesty.utils.mean_and_cov', 'dyfunc.mean_and_cov', (['pos', 'wts'], {}), '(pos, wts)\n', (1527, 1537), True, 'from dynesty import utils as dyfunc\n'), ((3918, 3930), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (3928, 3930), False, 'from utils import get_rstate, get_printing\n'), ((3964, 4062), 'dynesty.NestedSampler', 'dynesty.NestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'nlive': 'nlive', 'rstate': 'rstate'}), '(g.loglikelihood, g.prior_transform, g.ndim, nlive=\n nlive, rstate=rstate)\n', (3985, 4062), False, 'import dynesty\n'), ((4335, 4384), 'dynesty.utils.jitter_run', 'dyfunc.jitter_run', (['sampler.results'], {'rstate': 'rstate'}), '(sampler.results, rstate=rstate)\n', (4352, 4384), True, 'from dynesty import utils as dyfunc\n'), ((4389, 4440), 'dynesty.utils.resample_run', 'dyfunc.resample_run', (['sampler.results'], {'rstate': 'rstate'}), '(sampler.results, rstate=rstate)\n', (4408, 4440), True, 'from dynesty import utils as dyfunc\n'), ((4445, 4496), 'dynesty.utils.simulate_run', 'dyfunc.simulate_run', (['sampler.results'], {'rstate': 'rstate'}), '(sampler.results, rstate=rstate)\n', (4464, 4496), True, 'from dynesty import utils as dyfunc\n'), ((5085, 5115), 'dynesty.utils.merge_runs', 'dyfunc.merge_runs', (['result_list'], {}), '(result_list)\n', (5102, 5115), True, 'from dynesty import utils as dyfunc\n'), ((5604, 5616), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (5614, 5616), False, 'from utils import get_rstate, get_printing\n'), ((5923, 6049), 'dynesty.NestedSampler', 'dynesty.NestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'nlive': 'nlive', 'bound': 'bound', 'sample': 'sample', 'rstate': 'rstate'}), '(g.loglikelihood, g.prior_transform, g.ndim, nlive=\n nlive, bound=bound, sample=sample, rstate=rstate)\n', (5944, 6049), False, 'import dynesty\n'), ((6620, 6632), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (6630, 6632), False, 'from utils import get_rstate, get_printing\n'), ((6666, 6805), 'dynesty.NestedSampler', 'dynesty.NestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'nlive': 'nlive', 'bound': 'bound', 'sample': 'sample', 'bootstrap': '(5)', 'rstate': 'rstate'}), '(g.loglikelihood, g.prior_transform, g.ndim, nlive=\n nlive, bound=bound, sample=sample, bootstrap=5, rstate=rstate)\n', (6687, 6805), False, 'import dynesty\n'), ((6427, 6493), 'itertools.product', 'itertools.product', (["['single', 'multi', 'balls', 'cubes']", "['unif']"], {}), "(['single', 'multi', 'balls', 'cubes'], ['unif'])\n", (6444, 6493), False, 'import itertools\n'), ((7220, 7232), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (7230, 7232), False, 'from utils import get_rstate, get_printing\n'), ((7266, 7381), 'dynesty.NestedSampler', 'dynesty.NestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'nlive': 'nlive', 'sample': '"""hslice"""', 'rstate': 'rstate'}), "(g.loglikelihood, g.prior_transform, g.ndim, nlive=\n nlive, sample='hslice', rstate=rstate)\n", (7287, 7381), False, 'import dynesty\n'), ((7693, 7705), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (7703, 7705), False, 'from utils import get_rstate, get_printing\n'), ((7739, 7891), 'dynesty.NestedSampler', 'dynesty.NestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'nlive': 'nlive', 'sample': '"""hslice"""', 'gradient': 'g.grad_x', 'compute_jac': '(True)', 'rstate': 'rstate'}), "(g.loglikelihood, g.prior_transform, g.ndim, nlive=\n nlive, sample='hslice', gradient=g.grad_x, compute_jac=True, rstate=rstate)\n", (7760, 7891), False, 'import dynesty\n'), ((8276, 8288), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (8286, 8288), False, 'from utils import get_rstate, get_printing\n'), ((8322, 8456), 'dynesty.NestedSampler', 'dynesty.NestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'nlive': 'nlive', 'sample': '"""hslice"""', 'gradient': 'g.grad_u', 'rstate': 'rstate'}), "(g.loglikelihood, g.prior_transform, g.ndim, nlive=\n nlive, sample='hslice', gradient=g.grad_u, rstate=rstate)\n", (8343, 8456), False, 'import dynesty\n'), ((8846, 8858), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (8856, 8858), False, 'from utils import get_rstate, get_printing\n'), ((8893, 8984), 'dynesty.DynamicNestedSampler', 'dynesty.DynamicNestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'rstate': 'rstate'}), '(g.loglikelihood, g.prior_transform, g.ndim,\n rstate=rstate)\n', (8921, 8984), False, 'import dynesty\n'), ((9539, 9589), 'dynesty.utils.jitter_run', 'dyfunc.jitter_run', (['dsampler.results'], {'rstate': 'rstate'}), '(dsampler.results, rstate=rstate)\n', (9556, 9589), True, 'from dynesty import utils as dyfunc\n'), ((9640, 9692), 'dynesty.utils.resample_run', 'dyfunc.resample_run', (['dsampler.results'], {'rstate': 'rstate'}), '(dsampler.results, rstate=rstate)\n', (9659, 9692), True, 'from dynesty import utils as dyfunc\n'), ((9743, 9795), 'dynesty.utils.simulate_run', 'dyfunc.simulate_run', (['dsampler.results'], {'rstate': 'rstate'}), '(dsampler.results, rstate=rstate)\n', (9762, 9795), True, 'from dynesty import utils as dyfunc\n'), ((9840, 9889), 'dynesty.utils.kld_error', 'dyfunc.kld_error', (['dsampler.results'], {'rstate': 'rstate'}), '(dsampler.results, rstate=rstate)\n', (9856, 9889), True, 'from dynesty import utils as dyfunc\n'), ((10001, 10013), 'utils.get_rstate', 'get_rstate', ([], {}), '()\n', (10011, 10013), False, 'from utils import get_rstate, get_printing\n'), ((10049, 10184), 'dynesty.DynamicNestedSampler', 'dynesty.DynamicNestedSampler', (['g.loglikelihood', 'g.prior_transform', 'g.ndim'], {'bound': '"""single"""', 'sample': '"""unif"""', 'rstate': 'rstate', 'nlive': 'nlive'}), "(g.loglikelihood, g.prior_transform, g.ndim,\n bound='single', sample='unif', rstate=rstate, nlive=nlive)\n", (10077, 10184), False, 'import dynesty\n'), ((10680, 10704), 'dynesty.utils.unravel_run', 'dyfunc.unravel_run', (['dres'], {}), '(dres)\n', (10698, 10704), True, 'from dynesty import utils as dyfunc\n'), ((10722, 10750), 'dynesty.utils.merge_runs', 'dyfunc.merge_runs', (['dres_list'], {}), '(dres_list)\n', (10739, 10750), True, 'from dynesty import utils as dyfunc\n'), ((940, 959), 'numpy.cov', 'np.cov', (['pos[ind1].T'], {}), '(pos[ind1].T)\n', (946, 959), True, 'import numpy as np\n'), ((1023, 1044), 'numpy.std', 'np.std', (['means'], {'axis': '(0)'}), '(means, axis=0)\n', (1029, 1044), True, 'import numpy as np\n'), ((1046, 1066), 'numpy.std', 'np.std', (['covs'], {'axis': '(0)'}), '(covs, axis=0)\n', (1052, 1066), True, 'import numpy as np\n'), ((1684, 1709), 'numpy.abs', 'np.abs', (['(mean - mean_truth)'], {}), '(mean - mean_truth)\n', (1690, 1709), True, 'import numpy as np\n'), ((1753, 1776), 'numpy.abs', 'np.abs', (['(cov - cov_truth)'], {}), '(cov - cov_truth)\n', (1759, 1776), True, 'import numpy as np\n'), ((1819, 1844), 'numpy.abs', 'np.abs', (['(logz_truth - logz)'], {}), '(logz_truth - logz)\n', (1825, 1844), True, 'import numpy as np\n'), ((1991, 2020), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'self.ndim'], {}), '(-1, 1, self.ndim)\n', (2002, 2020), True, 'import numpy as np\n'), ((2040, 2062), 'numpy.identity', 'np.identity', (['self.ndim'], {}), '(self.ndim)\n', (2051, 2062), True, 'import numpy as np\n'), ((2227, 2247), 'numpy.linalg.inv', 'linalg.inv', (['self.cov'], {}), '(self.cov)\n', (2237, 2247), False, 'from numpy import linalg\n'), ((3608, 3648), 'numpy.exp', 'np.exp', (['(results.logwt - results.logz[-1])'], {}), '(results.logwt - results.logz[-1])\n', (3614, 3648), True, 'import numpy as np\n'), ((4874, 4914), 'numpy.exp', 'np.exp', (['(results.logwt - results.logz[-1])'], {}), '(results.logwt - results.logz[-1])\n', (4880, 4914), True, 'import numpy as np\n'), ((4935, 4964), 'dynesty.utils.mean_and_cov', 'dyfunc.mean_and_cov', (['pos', 'wts'], {}), '(pos, wts)\n', (4954, 4964), True, 'from dynesty import utils as dyfunc\n'), ((5128, 5168), 'numpy.abs', 'np.abs', (['(res_comb.logz[-1] - g.logz_truth)'], {}), '(res_comb.logz[-1] - g.logz_truth)\n', (5134, 5168), True, 'import numpy as np\n'), ((5381, 5487), 'itertools.product', 'itertools.product', (["['single', 'multi', 'balls', 'cubes', 'none']", "['unif', 'rwalk', 'slice', 'rslice']"], {}), "(['single', 'multi', 'balls', 'cubes', 'none'], ['unif',\n 'rwalk', 'slice', 'rslice'])\n", (5398, 5487), False, 'import itertools\n'), ((10762, 10805), 'numpy.abs', 'np.abs', (['(dres.logz[-1] - dres_merge.logz[-1])'], {}), '(dres.logz[-1] - dres_merge.logz[-1])\n', (10768, 10805), True, 'import numpy as np\n'), ((804, 819), 'numpy.nonzero', 'np.nonzero', (['sub'], {}), '(sub)\n', (814, 819), True, 'import numpy as np\n'), ((3077, 3112), 'numpy.dot', 'np.dot', (['self.cov_inv', '(x - self.mean)'], {}), '(self.cov_inv, x - self.mean)\n', (3083, 3112), True, 'import numpy as np\n'), ((5013, 5040), 'numpy.abs', 'np.abs', (['(logz - g.logz_truth)'], {}), '(logz - g.logz_truth)\n', (5019, 5040), True, 'import numpy as np\n'), ((2484, 2510), 'numpy.log', 'np.log', (['(2 * self.prior_win)'], {}), '(2 * self.prior_win)\n', (2490, 2510), True, 'import numpy as np\n'), ((2297, 2314), 'numpy.log', 'np.log', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (2303, 2314), True, 'import numpy as np\n'), ((2365, 2385), 'numpy.linalg.det', 'linalg.det', (['self.cov'], {}), '(self.cov)\n', (2375, 2385), False, 'from numpy import linalg\n'), ((2710, 2745), 'numpy.dot', 'np.dot', (['self.cov_inv', '(x - self.mean)'], {}), '(self.cov_inv, x - self.mean)\n', (2716, 2745), True, 'import numpy as np\n'), ((3247, 3282), 'numpy.dot', 'np.dot', (['self.cov_inv', '(x - self.mean)'], {}), '(self.cov_inv, x - self.mean)\n', (3253, 3282), True, 'import numpy as np\n')]
# Crichton, Admirable Source Configuration Management # Copyright 2012 British Broadcasting Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'FollowedProduct' db.create_table('frontend_followedproduct', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prodmgmt.Person'])), ('product', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prodmgmt.Product'])), )) db.send_create_signal('frontend', ['FollowedProduct']) def backwards(self, orm): # Deleting model 'FollowedProduct' db.delete_table('frontend_followedproduct') models = { 'frontend.followedproduct': { 'Meta': {'object_name': 'FollowedProduct'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'product': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['prodmgmt.Product']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['prodmgmt.Person']"}) }, 'issue.issue': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('name', 'project'),)", 'object_name': 'Issue'}, 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.SlugField', [], {'max_length': '128', 'db_index': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'issues'", 'to': "orm['issue.IssueTrackerProject']"}) }, 'issue.issuetracker': { 'Meta': {'ordering': "('name',)", 'object_name': 'IssueTracker'}, 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue_url_pattern': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}), 'name': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}), 'tracker_type': ('django.db.models.fields.CharField', [], {'default': "'jira'", 'max_length': '12'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'blank': 'True'}) }, 'issue.issuetrackerproject': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('name', 'issue_tracker'),)", 'object_name': 'IssueTrackerProject'}, 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'issue_tracker': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'projects'", 'to': "orm['issue.IssueTracker']"}), 'name': ('django.db.models.fields.SlugField', [], {'max_length': '128', 'db_index': 'True'}) }, 'prodmgmt.person': { 'Meta': {'ordering': "('username',)", 'object_name': 'Person'}, 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'distinguished_name': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'prodmgmt.product': { 'Meta': {'ordering': "('name',)", 'object_name': 'Product'}, 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'owned_products'", 'to': "orm['prodmgmt.Person']"}), 'pipeline_issue': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'+'", 'null': 'True', 'to': "orm['issue.Issue']"}) } } complete_apps = ['frontend']
[ "south.db.db.delete_table", "south.db.db.send_create_signal" ]
[((1270, 1324), 'south.db.db.send_create_signal', 'db.send_create_signal', (['"""frontend"""', "['FollowedProduct']"], {}), "('frontend', ['FollowedProduct'])\n", (1291, 1324), False, 'from south.db import db\n'), ((1417, 1460), 'south.db.db.delete_table', 'db.delete_table', (['"""frontend_followedproduct"""'], {}), "('frontend_followedproduct')\n", (1432, 1460), False, 'from south.db import db\n')]
#!python3 #encoding:utf-8 import subprocess import shlex import time import requests import json class Commiter: def __init__(self, db, client, user, repo): # def __init__(self, db, client): # def __init__(self, data, client): # self.data = data self.__db = db self.__client = client self.__user = user self.__repo = repo def ShowCommitFiles(self): subprocess.call(shlex.split("git add -n .")) def AddCommitPush(self, commit_message): subprocess.call(shlex.split("git add .")) subprocess.call(shlex.split("git commit -m '{0}'".format(commit_message))) subprocess.call(shlex.split("git push origin master")) time.sleep(3) self.__InsertLanguages(self.__client.repo.list_languages()) def __InsertLanguages(self, j): self.__user.RepoDb.begin() repo_id = self.__user.RepoDb['Repositories'].find_one(Name=self.__repo.Name)['Id'] self.__user.RepoDb['Languages'].delete(RepositoryId=repo_id) for key in j.keys(): self.__user.RepoDb['Languages'].insert(dict( RepositoryId=repo_id, Language=key, Size=j[key] )) self.__user.RepoDb.commit()
[ "shlex.split", "time.sleep" ]
[((707, 720), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (717, 720), False, 'import time\n'), ((428, 455), 'shlex.split', 'shlex.split', (['"""git add -n ."""'], {}), "('git add -n .')\n", (439, 455), False, 'import shlex\n'), ((527, 551), 'shlex.split', 'shlex.split', (['"""git add ."""'], {}), "('git add .')\n", (538, 551), False, 'import shlex\n'), ((660, 697), 'shlex.split', 'shlex.split', (['"""git push origin master"""'], {}), "('git push origin master')\n", (671, 697), False, 'import shlex\n')]
# Copyright (c) 2019-2021, <NAME>, <NAME>, <NAME>, and <NAME>. # # Distributed under the 3-clause BSD license, see accompanying file LICENSE # or https://github.com/scikit-hep/vector for details. import numpy from vector.compute.planar import x, y from vector.compute.spatial import z from vector.methods import ( AzimuthalRhoPhi, AzimuthalXY, LongitudinalEta, LongitudinalTheta, LongitudinalZ, _aztype, _from_signature, _ltype, ) # Rotation is only computed in Cartesian coordinates; the rest are conversions. # Follows ROOT's conventions. # # https://github.com/root-project/root/blob/f8efb11a51cbe5b5152ebef19a4f7b78744ca2fa/math/genvector/src/3DConversions.cxx#L478-L502 # # I don't know how this relates to Wikipedia's representation: # # https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix def cartesian(lib, u, i, j, k, x, y, z): q00 = u * u q01 = u * i q02 = u * j q03 = u * k q11 = i * i q12 = i * j q13 = i * k q22 = j * j q23 = j * k q33 = k * k xp = (q00 + q11 - q22 - q33) * x + (2 * (q12 - q03)) * y + (2 * (q02 + q13)) * z yp = (2 * (q12 + q03)) * x + (q00 - q11 + q22 - q33) * y + (2 * (q23 - q01)) * z zp = (2 * (q13 - q02)) * x + (2 * (q23 + q01)) * y + (q00 - q11 - q22 + q33) * z return (xp, yp, zp) dispatch_map = { (AzimuthalXY, LongitudinalZ): (cartesian, AzimuthalXY, LongitudinalZ), } def make_conversion(azimuthal, longitudinal): if (azimuthal, longitudinal) != (AzimuthalXY, LongitudinalZ): if azimuthal is AzimuthalXY: to_x = x.xy to_y = y.xy if longitudinal is LongitudinalZ: to_z = z.xy_z elif longitudinal is LongitudinalTheta: to_z = z.xy_theta elif longitudinal is LongitudinalEta: to_z = z.xy_eta elif azimuthal is AzimuthalRhoPhi: to_x = x.rhophi to_y = y.rhophi if longitudinal is LongitudinalZ: to_z = z.rhophi_z elif longitudinal is LongitudinalTheta: to_z = z.rhophi_theta elif longitudinal is LongitudinalEta: to_z = z.rhophi_eta cartesian, azout, lout = dispatch_map[AzimuthalXY, LongitudinalZ] def f(lib, u, i, j, k, coord1, coord2, coord3): return cartesian( lib, u, i, j, k, to_x(lib, coord1, coord2), to_y(lib, coord1, coord2), to_z(lib, coord1, coord2, coord3), ) dispatch_map[azimuthal, longitudinal] = (f, azout, lout) for azimuthal in (AzimuthalXY, AzimuthalRhoPhi): for longitudinal in (LongitudinalZ, LongitudinalTheta, LongitudinalEta): make_conversion(azimuthal, longitudinal) def dispatch(u, i, j, k, vec): function, *returns = _from_signature( __name__, dispatch_map, ( _aztype(vec), _ltype(vec), ), ) with numpy.errstate(all="ignore"): return vec._wrap_result( function( vec.lib, u, i, j, k, *vec.azimuthal.elements, *vec.longitudinal.elements ), returns, )
[ "vector.methods._ltype", "vector.methods._aztype", "numpy.errstate" ]
[((3109, 3137), 'numpy.errstate', 'numpy.errstate', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (3123, 3137), False, 'import numpy\n'), ((3044, 3056), 'vector.methods._aztype', '_aztype', (['vec'], {}), '(vec)\n', (3051, 3056), False, 'from vector.methods import AzimuthalRhoPhi, AzimuthalXY, LongitudinalEta, LongitudinalTheta, LongitudinalZ, _aztype, _from_signature, _ltype\n'), ((3070, 3081), 'vector.methods._ltype', '_ltype', (['vec'], {}), '(vec)\n', (3076, 3081), False, 'from vector.methods import AzimuthalRhoPhi, AzimuthalXY, LongitudinalEta, LongitudinalTheta, LongitudinalZ, _aztype, _from_signature, _ltype\n')]
from django.db import models class Thing(models.Model): color = models.CharField(max_length=10) __str__ = __repr__ = lambda self: self.color
[ "django.db.models.CharField" ]
[((69, 100), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)'}), '(max_length=10)\n', (85, 100), False, 'from django.db import models\n')]
import os import pytest import tempfile import pickle import numpy as np from ogindia.utils import comp_array, comp_scalar, dict_compare from ogindia.get_micro_data import get_calculator from ogindia import SS, TPI, utils from ogindia.parameters import Specifications from taxcalc import GrowFactors TOL = 1e-5 CUR_PATH = os.path.abspath(os.path.dirname(__file__)) @pytest.yield_fixture def picklefile1(): x = {'a': 1} pfile = tempfile.NamedTemporaryFile(mode='a', delete=False) pickle.dump(x, open(pfile.name, 'wb')) pfile.close() # must close and then yield for Windows platform yield pfile os.remove(pfile.name) @pytest.yield_fixture def picklefile2(): y = {'a': 1, 'b': 2} pfile = tempfile.NamedTemporaryFile(mode='a', delete=False) pickle.dump(y, open(pfile.name, 'wb')) pfile.close() # must close and then yield for Windows platform yield pfile os.remove(pfile.name) @pytest.yield_fixture def picklefile3(): x = {'a': np.array([100., 200., 300.]), 'b': 2} pfile = tempfile.NamedTemporaryFile(mode='a', delete=False) pickle.dump(x, open(pfile.name, 'wb')) pfile.close() # must close and then yield for Windows platform yield pfile os.remove(pfile.name) @pytest.yield_fixture def picklefile4(): x = {'a': np.array([100., 200., 300.1]), 'b': 2} pfile = tempfile.NamedTemporaryFile(mode='a', delete=False) pickle.dump(x, open(pfile.name, 'wb')) pfile.close() # must close and then yield for Windows platform yield pfile os.remove(pfile.name) def test_import_ok(): import ogindia @pytest.mark.full_run @pytest.mark.parametrize('time_path', [False, True], ids=['SS', 'TPI']) def test_run_small(time_path): from ogindia.execute import runner # Monkey patch enforcement flag since small data won't pass checks SS.ENFORCE_SOLUTION_CHECKS = False TPI.ENFORCE_SOLUTION_CHECKS = False SS.MINIMIZER_TOL = 1e-6 TPI.MINIMIZER_TOL = 1e-6 output_base = './OUTPUT' input_dir = './OUTPUT' user_params = {'frisch': 0.41, 'debt_ratio_ss': 0.4} runner(output_base=output_base, baseline_dir=input_dir, test=True, time_path=time_path, baseline=True, user_params=user_params, run_micro=False) @pytest.mark.full_run def test_constant_demographics_TPI(): ''' This tests solves the model under the assumption of constant demographics, a balanced budget, and tax functions that do not vary over time. In this case, given how initial guesss for the time path are made, the time path should be solved for on the first iteration and the values all along the time path should equal their steady-state values. ''' output_base = './OUTPUT' baseline_dir = './OUTPUT' # Create output directory structure ss_dir = os.path.join(output_base, 'SS') tpi_dir = os.path.join(output_base, 'TPI') dirs = [ss_dir, tpi_dir] for _dir in dirs: try: print('making dir: ', _dir) os.makedirs(_dir) except OSError: pass spec = Specifications(run_micro=False, output_base=output_base, baseline_dir=baseline_dir, test=False, time_path=True, baseline=True, reform={}, guid='') user_params = {'constant_demographics': True, 'budget_balance': True, 'zero_taxes': True, 'maxiter': 2, 'eta': (spec.omega_SS.reshape(spec.S, 1) * spec.lambdas.reshape(1, spec.J))} spec.update_specifications(user_params) spec.get_tax_function_parameters(None, False) # Run SS ss_outputs = SS.run_SS(spec, None) # save SS results utils.mkdirs(os.path.join(baseline_dir, 'SS')) ss_dir = os.path.join(baseline_dir, 'SS', 'SS_vars.pkl') pickle.dump(ss_outputs, open(ss_dir, 'wb')) # Run TPI tpi_output = TPI.run_TPI(spec, None) assert(np.allclose(tpi_output['bmat_splus1'][:spec.T, :, :], ss_outputs['bssmat_splus1'])) def test_compare_pickle_file_bad(picklefile1, picklefile2): from ogindia.utils import pickle_file_compare assert not pickle_file_compare(picklefile1.name, picklefile2.name) def test_compare_pickle_file_bad2(picklefile3, picklefile4): from ogindia.utils import pickle_file_compare assert not pickle_file_compare(picklefile3.name, picklefile4.name) def test_compare_pickle_file_relative(picklefile3, picklefile4): from ogindia.utils import pickle_file_compare assert pickle_file_compare( picklefile3.name, picklefile4.name, relative=True) def test_compare_pickle_file_basic(picklefile1): from ogindia.utils import pickle_file_compare assert pickle_file_compare(picklefile1.name, picklefile1.name) def test_compare_dict_basic(): from ogindia.utils import dict_compare lhs = {'a': 1, 'b': 2} rhs = {'c': 4, 'b': 2} assert not dict_compare('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL) def test_compare_dict_more_lhs(): from ogindia.utils import dict_compare lhs = {'a': 1, 'b': 2, 'c': 3} rhs = {'c': 4, 'b': 2} assert not dict_compare('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL) def test_compare_dict_diff_ndarrays(): from ogindia.utils import dict_compare lhs = {'a': np.array([1, 2, 3]), 'b': 2} rhs = {'a': np.array([1, 3]), 'b': 2} assert not dict_compare('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL) def test_compare_dict_diff_ndarrays2(): from ogindia.utils import dict_compare lhs = {'a': np.array([1., 2., 3.]), 'b': 2} rhs = {'a': np.array([1., 2., 3.1]), 'b': 2} assert not dict_compare('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL) def test_comp_array_relative(): x = np.array([100., 200., 300.]) y = np.array([100.01, 200.02, 300.03]) unequal = [] assert not comp_array('test', y, x, 1e-3, unequal) assert comp_array('test', y, x, 1e-3, unequal, relative=True) def test_comp_array_relative_exception(): x = np.array([100., 200., 300.]) y = np.array([100.01, 200.02, 300.03]) unequal = [] exc = {'var': 1e-3} assert comp_array('var', y, x, 1e-5, unequal, exceptions=exc, relative=True) def test_comp_scalar_relative(): x = 100 y = 100.01 unequal = [] assert not comp_scalar('test', y, x, 1e-3, unequal) assert comp_scalar('test', y, x, 1e-3, unequal, relative=True) def test_comp_scalar_relative_exception(): x = 100 y = 100.01 unequal = [] exc = {'var': 1e-3} assert comp_scalar('var', y, x, 1e-5, unequal, exceptions=exc, relative=True) def test_compare_dict_diff_ndarrays_relative(): lhs = {'a': np.array([100., 200., 300.]), 'b': 2} rhs = {'a': np.array([100., 200., 300.1]), 'b': 2} assert dict_compare('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=1e-3, relative=True) def test_get_micro_data_get_calculator(): reform = {2017: { '_rate1': [0.09], '_rate2': [0.135], '_rate3': [0.225], '_rate4': [0.252] }} calc = get_calculator(baseline=False, calculator_start_year=2017, reform=reform, data='pitSmallData.csv', gfactors=GrowFactors(), records_start_year=2017) assert calc.current_year == 2017
[ "tempfile.NamedTemporaryFile", "os.remove", "ogindia.TPI.run_TPI", "ogindia.execute.runner", "os.makedirs", "taxcalc.GrowFactors", "os.path.dirname", "numpy.allclose", "ogindia.utils.pickle_file_compare", "ogindia.utils.dict_compare", "ogindia.parameters.Specifications", "ogindia.SS.run_SS", "numpy.array", "ogindia.utils.comp_scalar", "pytest.mark.parametrize", "os.path.join", "ogindia.utils.comp_array" ]
[((1635, 1705), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""time_path"""', '[False, True]'], {'ids': "['SS', 'TPI']"}), "('time_path', [False, True], ids=['SS', 'TPI'])\n", (1658, 1705), False, 'import pytest\n'), ((340, 365), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (355, 365), False, 'import os\n'), ((439, 490), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'mode': '"""a"""', 'delete': '(False)'}), "(mode='a', delete=False)\n", (466, 490), False, 'import tempfile\n'), ((625, 646), 'os.remove', 'os.remove', (['pfile.name'], {}), '(pfile.name)\n', (634, 646), False, 'import os\n'), ((728, 779), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'mode': '"""a"""', 'delete': '(False)'}), "(mode='a', delete=False)\n", (755, 779), False, 'import tempfile\n'), ((914, 935), 'os.remove', 'os.remove', (['pfile.name'], {}), '(pfile.name)\n', (923, 935), False, 'import os\n'), ((1043, 1094), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'mode': '"""a"""', 'delete': '(False)'}), "(mode='a', delete=False)\n", (1070, 1094), False, 'import tempfile\n'), ((1229, 1250), 'os.remove', 'os.remove', (['pfile.name'], {}), '(pfile.name)\n', (1238, 1250), False, 'import os\n'), ((1359, 1410), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'mode': '"""a"""', 'delete': '(False)'}), "(mode='a', delete=False)\n", (1386, 1410), False, 'import tempfile\n'), ((1545, 1566), 'os.remove', 'os.remove', (['pfile.name'], {}), '(pfile.name)\n', (1554, 1566), False, 'import os\n'), ((2100, 2253), 'ogindia.execute.runner', 'runner', ([], {'output_base': 'output_base', 'baseline_dir': 'input_dir', 'test': '(True)', 'time_path': 'time_path', 'baseline': '(True)', 'user_params': 'user_params', 'run_micro': '(False)'}), '(output_base=output_base, baseline_dir=input_dir, test=True,\n time_path=time_path, baseline=True, user_params=user_params, run_micro=\n False)\n', (2106, 2253), False, 'from ogindia.execute import runner\n'), ((2829, 2860), 'os.path.join', 'os.path.join', (['output_base', '"""SS"""'], {}), "(output_base, 'SS')\n", (2841, 2860), False, 'import os\n'), ((2875, 2907), 'os.path.join', 'os.path.join', (['output_base', '"""TPI"""'], {}), "(output_base, 'TPI')\n", (2887, 2907), False, 'import os\n'), ((3094, 3250), 'ogindia.parameters.Specifications', 'Specifications', ([], {'run_micro': '(False)', 'output_base': 'output_base', 'baseline_dir': 'baseline_dir', 'test': '(False)', 'time_path': '(True)', 'baseline': '(True)', 'reform': '{}', 'guid': '""""""'}), "(run_micro=False, output_base=output_base, baseline_dir=\n baseline_dir, test=False, time_path=True, baseline=True, reform={}, guid=''\n )\n", (3108, 3250), False, 'from ogindia.parameters import Specifications\n'), ((3731, 3752), 'ogindia.SS.run_SS', 'SS.run_SS', (['spec', 'None'], {}), '(spec, None)\n', (3740, 3752), False, 'from ogindia import SS, TPI, utils\n'), ((3839, 3886), 'os.path.join', 'os.path.join', (['baseline_dir', '"""SS"""', '"""SS_vars.pkl"""'], {}), "(baseline_dir, 'SS', 'SS_vars.pkl')\n", (3851, 3886), False, 'import os\n'), ((3966, 3989), 'ogindia.TPI.run_TPI', 'TPI.run_TPI', (['spec', 'None'], {}), '(spec, None)\n', (3977, 3989), False, 'from ogindia import SS, TPI, utils\n'), ((4001, 4088), 'numpy.allclose', 'np.allclose', (["tpi_output['bmat_splus1'][:spec.T, :, :]", "ss_outputs['bssmat_splus1']"], {}), "(tpi_output['bmat_splus1'][:spec.T, :, :], ss_outputs[\n 'bssmat_splus1'])\n", (4012, 4088), True, 'import numpy as np\n'), ((4603, 4673), 'ogindia.utils.pickle_file_compare', 'pickle_file_compare', (['picklefile3.name', 'picklefile4.name'], {'relative': '(True)'}), '(picklefile3.name, picklefile4.name, relative=True)\n', (4622, 4673), False, 'from ogindia.utils import pickle_file_compare\n'), ((4795, 4850), 'ogindia.utils.pickle_file_compare', 'pickle_file_compare', (['picklefile1.name', 'picklefile1.name'], {}), '(picklefile1.name, picklefile1.name)\n', (4814, 4850), False, 'from ogindia.utils import pickle_file_compare\n'), ((5801, 5832), 'numpy.array', 'np.array', (['[100.0, 200.0, 300.0]'], {}), '([100.0, 200.0, 300.0])\n', (5809, 5832), True, 'import numpy as np\n'), ((5838, 5872), 'numpy.array', 'np.array', (['[100.01, 200.02, 300.03]'], {}), '([100.01, 200.02, 300.03])\n', (5846, 5872), True, 'import numpy as np\n'), ((5956, 6011), 'ogindia.utils.comp_array', 'comp_array', (['"""test"""', 'y', 'x', '(0.001)', 'unequal'], {'relative': '(True)'}), "('test', y, x, 0.001, unequal, relative=True)\n", (5966, 6011), False, 'from ogindia.utils import comp_array, comp_scalar, dict_compare\n'), ((6063, 6094), 'numpy.array', 'np.array', (['[100.0, 200.0, 300.0]'], {}), '([100.0, 200.0, 300.0])\n', (6071, 6094), True, 'import numpy as np\n'), ((6100, 6134), 'numpy.array', 'np.array', (['[100.01, 200.02, 300.03]'], {}), '([100.01, 200.02, 300.03])\n', (6108, 6134), True, 'import numpy as np\n'), ((6187, 6257), 'ogindia.utils.comp_array', 'comp_array', (['"""var"""', 'y', 'x', '(1e-05)', 'unequal'], {'exceptions': 'exc', 'relative': '(True)'}), "('var', y, x, 1e-05, unequal, exceptions=exc, relative=True)\n", (6197, 6257), False, 'from ogindia.utils import comp_array, comp_scalar, dict_compare\n'), ((6425, 6481), 'ogindia.utils.comp_scalar', 'comp_scalar', (['"""test"""', 'y', 'x', '(0.001)', 'unequal'], {'relative': '(True)'}), "('test', y, x, 0.001, unequal, relative=True)\n", (6436, 6481), False, 'from ogindia.utils import comp_array, comp_scalar, dict_compare\n'), ((6605, 6676), 'ogindia.utils.comp_scalar', 'comp_scalar', (['"""var"""', 'y', 'x', '(1e-05)', 'unequal'], {'exceptions': 'exc', 'relative': '(True)'}), "('var', y, x, 1e-05, unequal, exceptions=exc, relative=True)\n", (6616, 6676), False, 'from ogindia.utils import comp_array, comp_scalar, dict_compare\n'), ((6869, 6941), 'ogindia.utils.dict_compare', 'dict_compare', (['"""lhs.pkle"""', 'lhs', '"""rhs.pkle"""', 'rhs'], {'tol': '(0.001)', 'relative': '(True)'}), "('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=0.001, relative=True)\n", (6881, 6941), False, 'from ogindia.utils import dict_compare\n'), ((993, 1024), 'numpy.array', 'np.array', (['[100.0, 200.0, 300.0]'], {}), '([100.0, 200.0, 300.0])\n', (1001, 1024), True, 'import numpy as np\n'), ((1308, 1339), 'numpy.array', 'np.array', (['[100.0, 200.0, 300.1]'], {}), '([100.0, 200.0, 300.1])\n', (1316, 1339), True, 'import numpy as np\n'), ((3792, 3824), 'os.path.join', 'os.path.join', (['baseline_dir', '"""SS"""'], {}), "(baseline_dir, 'SS')\n", (3804, 3824), False, 'import os\n'), ((4235, 4290), 'ogindia.utils.pickle_file_compare', 'pickle_file_compare', (['picklefile1.name', 'picklefile2.name'], {}), '(picklefile1.name, picklefile2.name)\n', (4254, 4290), False, 'from ogindia.utils import pickle_file_compare\n'), ((4419, 4474), 'ogindia.utils.pickle_file_compare', 'pickle_file_compare', (['picklefile3.name', 'picklefile4.name'], {}), '(picklefile3.name, picklefile4.name)\n', (4438, 4474), False, 'from ogindia.utils import pickle_file_compare\n'), ((4996, 5051), 'ogindia.utils.dict_compare', 'dict_compare', (['"""lhs.pkle"""', 'lhs', '"""rhs.pkle"""', 'rhs'], {'tol': 'TOL'}), "('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL)\n", (5008, 5051), False, 'from ogindia.utils import dict_compare\n'), ((5208, 5263), 'ogindia.utils.dict_compare', 'dict_compare', (['"""lhs.pkle"""', 'lhs', '"""rhs.pkle"""', 'rhs'], {'tol': 'TOL'}), "('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL)\n", (5220, 5263), False, 'from ogindia.utils import dict_compare\n'), ((5364, 5383), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (5372, 5383), True, 'import numpy as np\n'), ((5409, 5425), 'numpy.array', 'np.array', (['[1, 3]'], {}), '([1, 3])\n', (5417, 5425), True, 'import numpy as np\n'), ((5450, 5505), 'ogindia.utils.dict_compare', 'dict_compare', (['"""lhs.pkle"""', 'lhs', '"""rhs.pkle"""', 'rhs'], {'tol': 'TOL'}), "('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL)\n", (5462, 5505), False, 'from ogindia.utils import dict_compare\n'), ((5607, 5632), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (5615, 5632), True, 'import numpy as np\n'), ((5655, 5680), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.1]'], {}), '([1.0, 2.0, 3.1])\n', (5663, 5680), True, 'import numpy as np\n'), ((5703, 5758), 'ogindia.utils.dict_compare', 'dict_compare', (['"""lhs.pkle"""', 'lhs', '"""rhs.pkle"""', 'rhs'], {'tol': 'TOL'}), "('lhs.pkle', lhs, 'rhs.pkle', rhs, tol=TOL)\n", (5715, 5758), False, 'from ogindia.utils import dict_compare\n'), ((5905, 5945), 'ogindia.utils.comp_array', 'comp_array', (['"""test"""', 'y', 'x', '(0.001)', 'unequal'], {}), "('test', y, x, 0.001, unequal)\n", (5915, 5945), False, 'from ogindia.utils import comp_array, comp_scalar, dict_compare\n'), ((6373, 6414), 'ogindia.utils.comp_scalar', 'comp_scalar', (['"""test"""', 'y', 'x', '(0.001)', 'unequal'], {}), "('test', y, x, 0.001, unequal)\n", (6384, 6414), False, 'from ogindia.utils import comp_array, comp_scalar, dict_compare\n'), ((6765, 6796), 'numpy.array', 'np.array', (['[100.0, 200.0, 300.0]'], {}), '([100.0, 200.0, 300.0])\n', (6773, 6796), True, 'import numpy as np\n'), ((6819, 6850), 'numpy.array', 'np.array', (['[100.0, 200.0, 300.1]'], {}), '([100.0, 200.0, 300.1])\n', (6827, 6850), True, 'import numpy as np\n'), ((3024, 3041), 'os.makedirs', 'os.makedirs', (['_dir'], {}), '(_dir)\n', (3035, 3041), False, 'import os\n'), ((7320, 7333), 'taxcalc.GrowFactors', 'GrowFactors', ([], {}), '()\n', (7331, 7333), False, 'from taxcalc import GrowFactors\n')]
# coding=utf-8 from setuptools import find_packages, setup base_requires = [ 'Click', 'ansible==3.0.0', 'backports.shutil_get_terminal_size', 'semver', 'junit_xml', 'structlog' ] test_requires = base_requires + [ 'mock', 'coverage', 'pep8', 'yapf==0.14.0' ] setup( name='origin-ci-tool', version='0.1.0', url='https://www.github.com/openshift/origin-ci-tool', maintainer='<NAME>', maintainer_email='<EMAIL>', packages=find_packages(exclude=['tests']), include_package_data=True, dependency_links=[ 'git+https://github.com/stevekuznetsov/ansible.git@skuznets/oct-release#egg=ansible-3.0.0' ], install_requires=base_requires, tests_require=test_requires, extras_require={ 'development': test_requires }, entry_points=''' [console_scripts] oct=oct.oct:oct_command ''', )
[ "setuptools.find_packages" ]
[((485, 517), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests']"}), "(exclude=['tests'])\n", (498, 517), False, 'from setuptools import find_packages, setup\n')]
from ansible.module_utils.basic import AnsibleModule, return_values """ (c) 2017 <NAME> <<EMAIL>> This file is part of Ansible Ansible is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Ansible is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Ansible. If not, see <http://www.gnu.org/licenses/>. """ DOCUMENTATION = ''' --- module: napalm_ping author: "<NAME> (@jedelman8)" version_added: "2.2" short_description: "Executes ping on the device and returns response using NAPALM" description: - "This module logs into the device, issues a ping request, and returns the response" requirements: - napalm options: hostname: description: - IP or FQDN of the device you want to connect to required: False username: description: - Username required: False password: description: - Password required: False provider: description: - Dictionary which acts as a collection of arguments used to define the characteristics of how to connect to the device. Note - hostname, username, password and dev_os must be defined in either provider or local param Note - local param takes precedence, e.g. hostname is preferred to provider['hostname'] required: False dev_os: description: - OS of the device required: False choices: ['eos', 'junos', 'ios', 'vyos', 'ros'] timeout: description: - Time in seconds to wait for the device to respond required: False default: 60 optional_args: description: - Dictionary of additional arguments passed to underlying driver required: False default: None destination: description: Host or IP Address of the destination required: True source: description: Source address of echo request required: False ttl: description: Maximum number of hops required: False ping_timeout: description: Maximum seconds to wait after sending final packet required: False size: description: Size of request (bytes) required: False count: description: Number of ping request to send required: False vrf: description: vrf to source the echo request required: False ''' EXAMPLES = ''' vars: napalm_provider: hostname: "{{ inventory_hostname }}" username: "napalm" password: "<PASSWORD>" dev_os: "eos" - napalm_ping: provider: "{{ napalm_provider }}" destination: 10.0.0.5 vrf: MANAGEMENT count: 2 - napalm_ping: provider: "{{ napalm_provider }}" destination: 8.8.8.8 count: 2 ''' RETURN = ''' changed: description: ALWAYS RETURNS FALSE returned: always type: bool sample: True results: description: structure response data of ping returned: always type: dict sample: # when echo request succeeds "{"success": {"packet_loss": 0, "probes_sent": 2, "results": [{"ip_address": "10.0.0.5:", "rtt": 1.71}, {"ip_address": "10.0.0.5:", "rtt": 0.733}], "rtt_avg": 1.225, "rtt_max": 1.718, "rtt_min": 0.733, "rtt_stddev": 0.493}} # when echo request fails {"error": "connect: Network is unreachable\n"}} ''' napalm_found = False try: from napalm import get_network_driver napalm_found = True except ImportError: pass # Legacy for pre-reunification napalm (remove in future) if not napalm_found: try: from napalm_base import get_network_driver # noqa napalm_found = True except ImportError: pass def main(): os_choices = ['eos', 'junos', 'ios', 'vyos', 'ros'] module = AnsibleModule( argument_spec=dict( hostname=dict(type='str', required=False, aliases=['host']), username=dict(type='str', required=False), password=dict(type='str', required=False, no_log=True), provider=dict(type='dict', required=False), timeout=dict(type='int', required=False, default=60), optional_args=dict(required=False, type='dict', default=None), dev_os=dict(type='str', required=False, choices=os_choices), destination=dict(type='str', required=True), source=dict(type='str', required=False), ttl=dict(type='str', required=False), ping_timeout=dict(type='str', required=False), size=dict(type='str', required=False), count=dict(type='str', required=False), vrf=dict(type='str', required=False), ), supports_check_mode=True ) if not napalm_found: module.fail_json(msg="the python module napalm is required") provider = module.params['provider'] or {} no_log = ['password', 'secret'] for param in no_log: if provider.get(param): module.no_log_values.update(return_values(provider[param])) if provider.get('optional_args') and provider['optional_args'].get(param): module.no_log_values.update(return_values(provider['optional_args'].get(param))) if module.params.get('optional_args') and module.params['optional_args'].get(param): module.no_log_values.update(return_values(module.params['optional_args'].get(param))) # allow host or hostname provider['hostname'] = provider.get('hostname', None) or provider.get('host', None) # allow local params to override provider for param, pvalue in provider.items(): if module.params.get(param) is not False: module.params[param] = module.params.get(param) or pvalue hostname = module.params['hostname'] username = module.params['username'] dev_os = module.params['dev_os'] password = module.params['password'] timeout = module.params['timeout'] destination = module.params['destination'] ping_optional_args = {} ping_args = ['source', 'ttl', 'ping_timeout', 'size', 'count', 'vrf'] for param, pvalue in module.params.items(): if param in ping_args and pvalue is not None: ping_optional_args[param] = pvalue if 'ping_timeout' in ping_optional_args: ping_optional_args['timeout'] = ping_optional_args['ping_timeout'] ping_optional_args.pop('ping_timeout') argument_check = {'hostname': hostname, 'username': username, 'dev_os': dev_os, 'password': password} for key, val in argument_check.items(): if val is None: module.fail_json(msg=str(key) + " is required") # use checks outside of ansible defined checks, since params come can come from provider if dev_os not in os_choices: module.fail_json(msg="dev_os is not set to " + str(os_choices)) if module.params['optional_args'] is None: optional_args = {} else: optional_args = module.params['optional_args'] try: network_driver = get_network_driver(dev_os) device = network_driver(hostname=hostname, username=username, password=password, timeout=timeout, optional_args=optional_args) device.open() except Exception as e: module.fail_json(msg="cannot connect to device: " + str(e)) ping_response = device.ping(destination, **ping_optional_args) try: device.close() except Exception as e: module.fail_json(msg="cannot close device connection: " + str(e)) module.exit_json(changed=False, results=ping_response) if __name__ == '__main__': main()
[ "ansible.module_utils.basic.return_values", "napalm_base.get_network_driver" ]
[((7451, 7477), 'napalm_base.get_network_driver', 'get_network_driver', (['dev_os'], {}), '(dev_os)\n', (7469, 7477), False, 'from napalm_base import get_network_driver\n'), ((5428, 5458), 'ansible.module_utils.basic.return_values', 'return_values', (['provider[param]'], {}), '(provider[param])\n', (5441, 5458), False, 'from ansible.module_utils.basic import AnsibleModule, return_values\n')]
#Deploys a stack and S3bucket to cloudformation. #test #Imports Python libraries import boto3 import re import sys import argparse import random import string import subprocess import logging from datetime import date from os.path import dirname script_dir = dirname(__file__) #Sets logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') file_handler = logging.FileHandler('deployStackS3Bucket.log') file_handler.setFormatter(formatter) streamHandler = logging.StreamHandler(sys.stdout) streamHandler.setLevel(logging.INFO) logger.addHandler(file_handler) logger.addHandler(streamHandler) #Creates cloudformation client cf_client = boto3.client('cloudformation', region_name='us-west-2') #Requires user initials input parameter. def main(input_initials): #Read in stack template file stack_template = _stack_template_file() #Parses input initials parser = argparse.ArgumentParser(description='Input Initials Required.') parser.add_argument('input_initials', metavar='input_initials', help='Input User Initials To Use In Stack Name.', nargs='?', type=str) args = parser.parse_args() #Gets initials initials = args.input_initials logger.info("Your Initials Entered: " + initials + "\n") #Gererates unique id unique_id = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(5)) #Gets the date date_created = date.today().strftime("%m%d%y") #Uses initials, date, and unique id for stack name delimiter = "-" stack_vars = (initials, date_created, unique_id, 'stack') stack_name = delimiter.join(stack_vars) #Uses stack with bucket name bucket_vars = (stack_name, 'reactapp', 'bucket') bucket_name = delimiter.join(bucket_vars) #Sets bucket name parameter parameters=_set_parameters(bucket_name) #Creates stack and S3bucket _create_stack_s3bucket(initials, stack_name, bucket_name, stack_template, parameters) #Verifies initials and creates new stack def _create_stack_s3bucket(initials, stack_name, bucket_name, stack_template, parameters): patternAlpha = re.compile("[A-Za-z]+") if patternAlpha.fullmatch(initials)==None: logger.error("Initials Must Contain Alphabetic Characters Only.\n") elif len(initials) == '': logger.error("Initials Must Not Be Empty.\n") elif len(initials) < 2: logger.error("Initials Must Be At Least 2 characters Long.\n") elif len(initials) > 5: logger.error("Initials Must Not Be More Than 5 characters Long.\n") else: logger.info("Your Stack Will Be Named: " + "'" + stack_name + "'\n") logger.info("Your S3Bucket Will Be Named: " + "'" + bucket_name + "'\n") logger.info("Please Wait While Your Stack and S3Bucket Are Being Deployed To Cloudformation.\n") logger.info("Waiting...\n") #Checks if stack already exists if _stack_exists(stack_name): logger.error("A Stack Named " + "'" + stack_name + "' Already Exists, Please Try Again.\n") else: #Creates stack and S3bucket stack_result = cf_client.create_stack(StackName=stack_name, TemplateBody=stack_template, Parameters=parameters) waiter = cf_client.get_waiter('stack_create_complete') waiter.wait(StackName=stack_name) logger.info("Congradulations! Your Stack " + stack_name + " And S3Bucket " + bucket_name + " Are Now Completed.\n") #Echos bucket name as Github environment variable echo_arg = ("echo BUCKET_NAME=" + bucket_name + " >> $GITHUB_ENV") subprocess.Popen(echo_arg, shell=True) logger.debug(echo_arg) #Reads in stack template file def _stack_template_file(): stack_template = '' with open(f"{script_dir}/StackTemplate.json", 'r') as fd: stack_template = fd.read() return stack_template # Verifies if stack already exists def _stack_exists(stack_name): paginator = cf_client.get_paginator('list_stacks') for page in paginator.paginate(): for stack in page['StackSummaries']: if stack['StackStatus'] == 'DELETE_COMPLETE': continue if stack['StackName'] == stack_name: return True #Sets parameters def _set_parameters(bucket_name): return [ { 'ParameterKey': 'BucketName', 'ParameterValue': bucket_name } ] #Runs main program if __name__ == '__main__': main(*sys.argv[1:])
[ "subprocess.Popen", "random.SystemRandom", "logging.FileHandler", "boto3.client", "argparse.ArgumentParser", "os.path.dirname", "logging.StreamHandler", "datetime.date.today", "logging.Formatter", "logging.getLogger", "re.compile" ]
[((259, 276), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (266, 276), False, 'from os.path import dirname\n'), ((301, 328), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (318, 328), False, 'import logging\n'), ((372, 470), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': '"""%(asctime)s %(levelname)-8s %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt=\n '%Y-%m-%d %H:%M:%S')\n", (389, 470), False, 'import logging\n'), ((481, 527), 'logging.FileHandler', 'logging.FileHandler', (['"""deployStackS3Bucket.log"""'], {}), "('deployStackS3Bucket.log')\n", (500, 527), False, 'import logging\n'), ((581, 614), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (602, 614), False, 'import logging\n'), ((761, 816), 'boto3.client', 'boto3.client', (['"""cloudformation"""'], {'region_name': '"""us-west-2"""'}), "('cloudformation', region_name='us-west-2')\n", (773, 816), False, 'import boto3\n'), ((1004, 1067), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Input Initials Required."""'}), "(description='Input Initials Required.')\n", (1027, 1067), False, 'import argparse\n'), ((2339, 2362), 're.compile', 're.compile', (['"""[A-Za-z]+"""'], {}), "('[A-Za-z]+')\n", (2349, 2362), False, 'import re\n'), ((1632, 1644), 'datetime.date.today', 'date.today', ([], {}), '()\n', (1642, 1644), False, 'from datetime import date\n'), ((1505, 1526), 'random.SystemRandom', 'random.SystemRandom', ([], {}), '()\n', (1524, 1526), False, 'import random\n'), ((3836, 3874), 'subprocess.Popen', 'subprocess.Popen', (['echo_arg'], {'shell': '(True)'}), '(echo_arg, shell=True)\n', (3852, 3874), False, 'import subprocess\n')]
from distutils.core import setup from setuptools import find_packages setup( name="dgk", version="0.08.1", packages=find_packages(), package_data={"dgk": ["config/*.ini", "database/*.db"]}, url="https://github.com/sg679/disc-golf-keeper", license="MIT", author="<NAME>", description="A simple graphical application to track your disc golf games.", long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", python_requires=">=3.0", entry_points={"console_scripts": ["dgk=dgk.app:main"]}, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Topic :: Database", "Topic :: Other/Nonlisted Topic", ], )
[ "setuptools.find_packages" ]
[((130, 145), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (143, 145), False, 'from setuptools import find_packages\n')]
import logging from typing import Any, AsyncIterator, Callable import aioredis from aiohttp_example.darq import darq from aiohttp_example.db import create_engine from aiohttp_example.services import services log = logging.getLogger(__name__) async def connect_darq(*args: Any) -> AsyncIterator[None]: await darq.connect() yield await darq.disconnect() async def connect_db(*args: Any) -> AsyncIterator[None]: db = await create_engine() services.db = db log.info('Connected to dummy database') yield db.close() await db.wait_closed() log.info('Disconnected from dummy database') async def connect_redis(*args: Any) -> AsyncIterator[None]: redis_client = await aioredis.create_redis_pool('redis://redis') services.redis = redis_client log.info(f'Connected to redis (db={redis_client.db})') yield redis_client.close() await redis_client.wait_closed() log.info('Disconnected from redis') def get_cleanup_ctx_factories( ) -> list[Callable[..., AsyncIterator[None]]]: return [ connect_db, connect_redis, ]
[ "aiohttp_example.darq.darq.disconnect", "aioredis.create_redis_pool", "aiohttp_example.darq.darq.connect", "aiohttp_example.db.create_engine", "logging.getLogger" ]
[((217, 244), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (234, 244), False, 'import logging\n'), ((316, 330), 'aiohttp_example.darq.darq.connect', 'darq.connect', ([], {}), '()\n', (328, 330), False, 'from aiohttp_example.darq import darq\n'), ((351, 368), 'aiohttp_example.darq.darq.disconnect', 'darq.disconnect', ([], {}), '()\n', (366, 368), False, 'from aiohttp_example.darq import darq\n'), ((443, 458), 'aiohttp_example.db.create_engine', 'create_engine', ([], {}), '()\n', (456, 458), False, 'from aiohttp_example.db import create_engine\n'), ((713, 756), 'aioredis.create_redis_pool', 'aioredis.create_redis_pool', (['"""redis://redis"""'], {}), "('redis://redis')\n", (739, 756), False, 'import aioredis\n')]
# This file uses the `convert` system function to convert character (such as # letter, numbers, symbols) to png format images, which will be used to # annotate objects in YOLO detection. # # AUTHORS # # The Veracruz Development Team. # # COPYRIGHT AND LICENSING # # See the `LICENSE_MIT.markdown` file in the Veracruz deep learning server # example repository root directory for copyright and licensing information. # Based on darknet, YOLO LICENSE https://github.com/pjreddie/darknet/blob/master/LICENSE #!/usr/bin/env python # -*- coding: utf-8 -*- import os import string import pipes # a function that calls `convert` system function to convert character as # png images. # # - Input: font size # - Output: png images of character def make_labels(s): l = string.printable for word in l: if word == ' ': os.system('convert -fill black -background white -bordercolor white -pointsize %d label:"\ " data/labels/32_%d.png'%(s,s/12-1)) if word == '@': os.system('convert -fill black -background white -bordercolor white -pointsize %d label:"\@" data/labels/64_%d.png'%(s,s/12-1)) elif word == '\\': os.system('convert -fill black -background white -bordercolor white -pointsize %d label:"\\\\\\\\" data/labels/92_%d.png'%(s,s/12-1)) elif ord(word) in [9,10,11,12,13,14]: pass else: os.system("convert -fill black -background white -bordercolor white -pointsize %d label:%s \"data/labels/%d_%d.png\""%(s,pipes.quote(word), ord(word),s/12-1)) # for different font sizes for i in [12,24,36,48,60,72,84,96]: make_labels(i)
[ "pipes.quote", "os.system" ]
[((841, 986), 'os.system', 'os.system', (['(\'convert -fill black -background white -bordercolor white -pointsize %d label:"\\\\ " data/labels/32_%d.png\'\n % (s, s / 12 - 1))'], {}), '(\n \'convert -fill black -background white -bordercolor white -pointsize %d label:"\\\\ " data/labels/32_%d.png\'\n % (s, s / 12 - 1))\n', (850, 986), False, 'import os\n'), ((1005, 1150), 'os.system', 'os.system', (['(\'convert -fill black -background white -bordercolor white -pointsize %d label:"\\\\@" data/labels/64_%d.png\'\n % (s, s / 12 - 1))'], {}), '(\n \'convert -fill black -background white -bordercolor white -pointsize %d label:"\\\\@" data/labels/64_%d.png\'\n % (s, s / 12 - 1))\n', (1014, 1150), False, 'import os\n'), ((1172, 1322), 'os.system', 'os.system', (['(\'convert -fill black -background white -bordercolor white -pointsize %d label:"\\\\\\\\\\\\\\\\" data/labels/92_%d.png\'\n % (s, s / 12 - 1))'], {}), '(\n \'convert -fill black -background white -bordercolor white -pointsize %d label:"\\\\\\\\\\\\\\\\" data/labels/92_%d.png\'\n % (s, s / 12 - 1))\n', (1181, 1322), False, 'import os\n'), ((1516, 1533), 'pipes.quote', 'pipes.quote', (['word'], {}), '(word)\n', (1527, 1533), False, 'import pipes\n')]
from flask import Flask from flask import request, jsonify from flask_cors import CORS, cross_origin from .redactioncalc import get_distances_from_filepaths import os, json app= Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' @app.route('/', methods=['GET']) def home(): return '''<h1>New Testament Helper API</h1><p>A prototype API for New Testament Studies.</p>''' # Route to return all available texts that can be compared @app.route('/texts', methods=['GET']) @cross_origin() def texts(): # TODO Rather than using local files use a database response = { 'manuscripts': os.listdir('./testmss') } return jsonify(response) @app.route('/display', methods=['GET']) @cross_origin() def display(): #TODO this function returns an internal server error rather than displaying mss # something to do with escape characters and format issues I think... mss_name = request.args.get('mss') mss_list = os.listdir('./testmss') content = '' if mss_name in mss_list: filename = './testmss/' + mss_name content = get_file_contents(filename) else: content ='Manuscript not found' response = { 'contents' : content } return jsonify(response) @app.route('/levenshtein', methods=['GET']) @cross_origin() def levenshtein(): # Get parameters for documents to compare from url mss1_name = request.args.get('mss1') mss2_name = request.args.get('mss2') mss3_name = request.args.get('mss3') response = {} if (mss1_name is None) or (mss2_name is None) or (mss3_name is None): response = {'error': 'invalid manuscript names'} else: files = { mss1_name : concat_filepath(mss1_name), mss2_name : concat_filepath(mss2_name), mss3_name : concat_filepath(mss3_name) } values = get_distances_from_filepaths(files) response = { 'levenshtein': { 'mss': [mss1_name, mss2_name, mss3_name], 'values': json.loads(values.to_json()) } } return jsonify(response) def concat_filepath(filename): return './testmss/' + filename def get_file_contents(filename): fd = os.open(filename, os.O_RDWR) ret = os.read(fd, os.path.getsize(filename)) rval = ret.decode("utf-8") os.close(fd) return rval
[ "os.open", "flask.request.args.get", "flask_cors.CORS", "os.path.getsize", "flask.Flask", "flask_cors.cross_origin", "flask.jsonify", "os.close", "os.listdir" ]
[((178, 193), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (183, 193), False, 'from flask import Flask\n'), ((201, 210), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (205, 210), False, 'from flask_cors import CORS, cross_origin\n'), ((498, 512), 'flask_cors.cross_origin', 'cross_origin', ([], {}), '()\n', (510, 512), False, 'from flask_cors import CORS, cross_origin\n'), ((711, 725), 'flask_cors.cross_origin', 'cross_origin', ([], {}), '()\n', (723, 725), False, 'from flask_cors import CORS, cross_origin\n'), ((1261, 1275), 'flask_cors.cross_origin', 'cross_origin', ([], {}), '()\n', (1273, 1275), False, 'from flask_cors import CORS, cross_origin\n'), ((651, 668), 'flask.jsonify', 'jsonify', (['response'], {}), '(response)\n', (658, 668), False, 'from flask import request, jsonify\n'), ((909, 932), 'flask.request.args.get', 'request.args.get', (['"""mss"""'], {}), "('mss')\n", (925, 932), False, 'from flask import request, jsonify\n'), ((946, 969), 'os.listdir', 'os.listdir', (['"""./testmss"""'], {}), "('./testmss')\n", (956, 969), False, 'import os, json\n'), ((1197, 1214), 'flask.jsonify', 'jsonify', (['response'], {}), '(response)\n', (1204, 1214), False, 'from flask import request, jsonify\n'), ((1363, 1387), 'flask.request.args.get', 'request.args.get', (['"""mss1"""'], {}), "('mss1')\n", (1379, 1387), False, 'from flask import request, jsonify\n'), ((1402, 1426), 'flask.request.args.get', 'request.args.get', (['"""mss2"""'], {}), "('mss2')\n", (1418, 1426), False, 'from flask import request, jsonify\n'), ((1441, 1465), 'flask.request.args.get', 'request.args.get', (['"""mss3"""'], {}), "('mss3')\n", (1457, 1465), False, 'from flask import request, jsonify\n'), ((1985, 2002), 'flask.jsonify', 'jsonify', (['response'], {}), '(response)\n', (1992, 2002), False, 'from flask import request, jsonify\n'), ((2111, 2139), 'os.open', 'os.open', (['filename', 'os.O_RDWR'], {}), '(filename, os.O_RDWR)\n', (2118, 2139), False, 'import os, json\n'), ((2218, 2230), 'os.close', 'os.close', (['fd'], {}), '(fd)\n', (2226, 2230), False, 'import os, json\n'), ((614, 637), 'os.listdir', 'os.listdir', (['"""./testmss"""'], {}), "('./testmss')\n", (624, 637), False, 'import os, json\n'), ((2160, 2185), 'os.path.getsize', 'os.path.getsize', (['filename'], {}), '(filename)\n', (2175, 2185), False, 'import os, json\n')]
from flask import Flask, render_template, make_response, request from routes.index import main from routes.hello import hello from routes import allow_cross_domain from flask_cors import CORS app = Flask(__name__) CORS(app, supports_credentials=True) # 设置 secret_key 来使用 flask 自带的 session # 这个字符串随便你设置什么内容都可以 app.secret_key = 'random string' app.register_blueprint(main, url_prefix='/account') app.register_blueprint(hello, url_prefix='/hello') @app.route('/') # @allow_cross_domain def index(): return render_template('index.html') if __name__ == "__main__": app.run(host='0.0.0.0', debug=True, port=5000)
[ "flask_cors.CORS", "flask.Flask", "flask.render_template" ]
[((200, 215), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (205, 215), False, 'from flask import Flask, render_template, make_response, request\n'), ((216, 252), 'flask_cors.CORS', 'CORS', (['app'], {'supports_credentials': '(True)'}), '(app, supports_credentials=True)\n', (220, 252), False, 'from flask_cors import CORS\n'), ((513, 542), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (528, 542), False, 'from flask import Flask, render_template, make_response, request\n')]
from flask import jsonify, session, request from flask_restx import Resource, reqparse, inputs from modules.LoginModule.LoginModule import user_multi_auth from modules.FlaskModule.FlaskModule import user_api_ns as api from opentera.db.models.TeraUser import TeraUser from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup from modules.DatabaseModule.DBManager import DBManager from sqlalchemy.exc import InvalidRequestError from sqlalchemy import exc from flask_babel import gettext # Parser definition(s) get_parser = api.parser() get_parser.add_argument('id_group', type=int, help='ID of the participant group to query' ) get_parser.add_argument('id_project', type=int, help='ID of the project from which to get all participant groups') get_parser.add_argument('id', type=int, help='Alias for "id_group"') get_parser.add_argument('list', type=inputs.boolean, help='Flag that limits the returned data to minimal information') # post_parser = reqparse.RequestParser() # post_parser.add_argument('group', type=str, location='json', help='Participant group to create / update', required=True) post_schema = api.schema_model('user_participant_group', {'properties': TeraParticipantGroup.get_json_schema(), 'type': 'object', 'location': 'json'}) delete_parser = reqparse.RequestParser() delete_parser.add_argument('id', type=int, help='Participant Group ID to delete', required=True) class UserQueryParticipantGroup(Resource): def __init__(self, _api, *args, **kwargs): Resource.__init__(self, _api, *args, **kwargs) self.module = kwargs.get('flaskModule', None) @user_multi_auth.login_required @api.expect(get_parser) @api.doc(description='Get participant groups information. Only one of the ID parameter is supported at once. ' 'If no ID is specified, returns all accessible groups for the logged user', responses={200: 'Success - returns list of participant groups', 500: 'Database error'}) def get(self): current_user = TeraUser.get_user_by_uuid(session['_user_id']) user_access = DBManager.userAccess(current_user) parser = get_parser args = parser.parse_args() groups = [] # If we have no arguments, return all accessible participants if args['id']: args['id_group'] = args['id'] if not any(args.values()): groups = user_access.get_accessible_groups() elif args['id_group']: if args['id_group'] in user_access.get_accessible_groups_ids(): groups = [TeraParticipantGroup.get_participant_group_by_id(args['id_group'])] elif args['id_project']: if args['id_project'] in user_access.get_accessible_projects_ids(): groups = TeraParticipantGroup.get_participant_group_for_project(args['id_project']) try: group_list = [] for group in groups: if args['list'] is None: group_json = group.to_json() group_list.append(group_json) else: group_json = group.to_json(minimal=True) group_json['group_participant_count'] = len(user_access.query_participants_for_group( group.id_participant_group)) group_list.append(group_json) return jsonify(group_list) except InvalidRequestError as e: self.module.logger.log_error(self.module.module_name, UserQueryParticipantGroup.__name__, 'get', 500, 'InvalidRequestError', str(e)) return '', 500 @user_multi_auth.login_required @api.expect(post_schema) @api.doc(description='Create / update participant groups. id_participant_group must be set to "0" to create a new ' 'group. A group can be created/modified if the user has admin rights to the project.', responses={200: 'Success', 403: 'Logged user can\'t create/update the specified device', 400: 'Badly formed JSON or missing fields(id_participant_group or id_project) in the JSON body', 500: 'Internal error occured when saving device'}) def post(self): # parser = post_parser current_user = TeraUser.get_user_by_uuid(session['_user_id']) user_access = DBManager.userAccess(current_user) # Using request.json instead of parser, since parser messes up the json! if 'group' not in request.json: return gettext('Missing group'), 400 json_group = request.json['group'] # Validate if we have an id if 'id_participant_group' not in json_group or 'id_project' not in json_group: return gettext('Missing id_participant_group or id_project'), 400 # Check if current user can modify the posted group # User can modify or add a group if it has admin access to that project if json_group['id_project'] not in user_access.get_accessible_projects_ids(admin_only=True): return gettext('Forbidden'), 403 # Do the update! if json_group['id_participant_group'] > 0: # Already existing try: TeraParticipantGroup.update(json_group['id_participant_group'], json_group) except exc.SQLAlchemyError as e: import sys print(sys.exc_info()) self.module.logger.log_error(self.module.module_name, UserQueryParticipantGroup.__name__, 'post', 500, 'Database error', str(e)) return gettext('Database error'), 500 else: # New try: new_group = TeraParticipantGroup() new_group.from_json(json_group) TeraParticipantGroup.insert(new_group) # Update ID for further use json_group['id_participant_group'] = new_group.id_participant_group except exc.SQLAlchemyError as e: import sys print(sys.exc_info()) self.module.logger.log_error(self.module.module_name, UserQueryParticipantGroup.__name__, 'post', 500, 'Database error', str(e)) return gettext('Database error'), 500 # TODO: Publish update to everyone who is subscribed to sites update... update_group = TeraParticipantGroup.get_participant_group_by_id(json_group['id_participant_group']) return jsonify([update_group.to_json()]) @user_multi_auth.login_required @api.expect(delete_parser) @api.doc(description='Delete a specific participant group', responses={200: 'Success', 403: 'Logged user can\'t delete participant group (only project admin can delete)', 500: 'Database error.'}) def delete(self): parser = delete_parser current_user = TeraUser.get_user_by_uuid(session['_user_id']) user_access = DBManager.userAccess(current_user) args = parser.parse_args() id_todel = args['id'] # Check if current user can delete # Only projects admins can delete a group group = TeraParticipantGroup.get_participant_group_by_id(id_todel) if user_access.get_project_role(group.id_project) != 'admin': return gettext('Forbidden'), 403 # If we are here, we are allowed to delete. Do so. try: TeraParticipantGroup.delete(id_todel=id_todel) except exc.IntegrityError as e: # Causes that could make an integrity error when deleting a participant: # - Participants with associated sessions self.module.logger.log_error(self.module.module_name, UserQueryParticipantGroup.__name__, 'delete', 500, 'Database error', str(e)) return gettext('Can\'t delete participant group: please delete all sessions from all ' 'participants before deleting.'), 500 except exc.SQLAlchemyError as e: import sys print(sys.exc_info()) self.module.logger.log_error(self.module.module_name, UserQueryParticipantGroup.__name__, 'delete', 500, 'Database error', str(e)) return gettext('Database error'), 500 return '', 200
[ "opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.insert", "modules.FlaskModule.FlaskModule.user_api_ns.expect", "opentera.db.models.TeraParticipantGroup.TeraParticipantGroup", "opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_participant_group_by_id", "opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.update", "modules.DatabaseModule.DBManager.DBManager.userAccess", "flask_restx.reqparse.RequestParser", "flask_restx.Resource.__init__", "flask.jsonify", "modules.FlaskModule.FlaskModule.user_api_ns.doc", "opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.delete", "sys.exc_info", "modules.FlaskModule.FlaskModule.user_api_ns.parser", "opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_participant_group_for_project", "opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_json_schema", "opentera.db.models.TeraUser.TeraUser.get_user_by_uuid", "flask_babel.gettext" ]
[((538, 550), 'modules.FlaskModule.FlaskModule.user_api_ns.parser', 'api.parser', ([], {}), '()\n', (548, 550), True, 'from modules.FlaskModule.FlaskModule import user_api_ns as api\n'), ((1419, 1443), 'flask_restx.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (1441, 1443), False, 'from flask_restx import Resource, reqparse, inputs\n'), ((1785, 1807), 'modules.FlaskModule.FlaskModule.user_api_ns.expect', 'api.expect', (['get_parser'], {}), '(get_parser)\n', (1795, 1807), True, 'from modules.FlaskModule.FlaskModule import user_api_ns as api\n'), ((1813, 2102), 'modules.FlaskModule.FlaskModule.user_api_ns.doc', 'api.doc', ([], {'description': '"""Get participant groups information. Only one of the ID parameter is supported at once. If no ID is specified, returns all accessible groups for the logged user"""', 'responses': "{(200): 'Success - returns list of participant groups', (500): 'Database error'\n }"}), "(description=\n 'Get participant groups information. Only one of the ID parameter is supported at once. If no ID is specified, returns all accessible groups for the logged user'\n , responses={(200): 'Success - returns list of participant groups', (\n 500): 'Database error'})\n", (1820, 2102), True, 'from modules.FlaskModule.FlaskModule import user_api_ns as api\n'), ((3907, 3930), 'modules.FlaskModule.FlaskModule.user_api_ns.expect', 'api.expect', (['post_schema'], {}), '(post_schema)\n', (3917, 3930), True, 'from modules.FlaskModule.FlaskModule import user_api_ns as api\n'), ((3936, 4401), 'modules.FlaskModule.FlaskModule.user_api_ns.doc', 'api.doc', ([], {'description': '"""Create / update participant groups. id_participant_group must be set to "0" to create a new group. A group can be created/modified if the user has admin rights to the project."""', 'responses': '{(200): \'Success\', (403):\n "Logged user can\'t create/update the specified device", (400):\n \'Badly formed JSON or missing fields(id_participant_group or id_project) in the JSON body\'\n , (500): \'Internal error occured when saving device\'}'}), '(description=\n \'Create / update participant groups. id_participant_group must be set to "0" to create a new group. A group can be created/modified if the user has admin rights to the project.\'\n , responses={(200): \'Success\', (403):\n "Logged user can\'t create/update the specified device", (400):\n \'Badly formed JSON or missing fields(id_participant_group or id_project) in the JSON body\'\n , (500): \'Internal error occured when saving device\'})\n', (3943, 4401), True, 'from modules.FlaskModule.FlaskModule import user_api_ns as api\n'), ((6994, 7019), 'modules.FlaskModule.FlaskModule.user_api_ns.expect', 'api.expect', (['delete_parser'], {}), '(delete_parser)\n', (7004, 7019), True, 'from modules.FlaskModule.FlaskModule import user_api_ns as api\n'), ((7025, 7237), 'modules.FlaskModule.FlaskModule.user_api_ns.doc', 'api.doc', ([], {'description': '"""Delete a specific participant group"""', 'responses': '{(200): \'Success\', (403):\n "Logged user can\'t delete participant group (only project admin can delete)"\n , (500): \'Database error.\'}'}), '(description=\'Delete a specific participant group\', responses={(200):\n \'Success\', (403):\n "Logged user can\'t delete participant group (only project admin can delete)"\n , (500): \'Database error.\'})\n', (7032, 7237), True, 'from modules.FlaskModule.FlaskModule import user_api_ns as api\n'), ((1207, 1245), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_json_schema', 'TeraParticipantGroup.get_json_schema', ([], {}), '()\n', (1243, 1245), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((1642, 1688), 'flask_restx.Resource.__init__', 'Resource.__init__', (['self', '_api', '*args'], {}), '(self, _api, *args, **kwargs)\n', (1659, 1688), False, 'from flask_restx import Resource, reqparse, inputs\n'), ((2191, 2237), 'opentera.db.models.TeraUser.TeraUser.get_user_by_uuid', 'TeraUser.get_user_by_uuid', (["session['_user_id']"], {}), "(session['_user_id'])\n", (2216, 2237), False, 'from opentera.db.models.TeraUser import TeraUser\n'), ((2260, 2294), 'modules.DatabaseModule.DBManager.DBManager.userAccess', 'DBManager.userAccess', (['current_user'], {}), '(current_user)\n', (2280, 2294), False, 'from modules.DatabaseModule.DBManager import DBManager\n'), ((4560, 4606), 'opentera.db.models.TeraUser.TeraUser.get_user_by_uuid', 'TeraUser.get_user_by_uuid', (["session['_user_id']"], {}), "(session['_user_id'])\n", (4585, 4606), False, 'from opentera.db.models.TeraUser import TeraUser\n'), ((4629, 4663), 'modules.DatabaseModule.DBManager.DBManager.userAccess', 'DBManager.userAccess', (['current_user'], {}), '(current_user)\n', (4649, 4663), False, 'from modules.DatabaseModule.DBManager import DBManager\n'), ((6817, 6906), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_participant_group_by_id', 'TeraParticipantGroup.get_participant_group_by_id', (["json_group['id_participant_group']"], {}), "(json_group[\n 'id_participant_group'])\n", (6865, 6906), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((7357, 7403), 'opentera.db.models.TeraUser.TeraUser.get_user_by_uuid', 'TeraUser.get_user_by_uuid', (["session['_user_id']"], {}), "(session['_user_id'])\n", (7382, 7403), False, 'from opentera.db.models.TeraUser import TeraUser\n'), ((7426, 7460), 'modules.DatabaseModule.DBManager.DBManager.userAccess', 'DBManager.userAccess', (['current_user'], {}), '(current_user)\n', (7446, 7460), False, 'from modules.DatabaseModule.DBManager import DBManager\n'), ((7637, 7695), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_participant_group_by_id', 'TeraParticipantGroup.get_participant_group_by_id', (['id_todel'], {}), '(id_todel)\n', (7685, 7695), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((3549, 3568), 'flask.jsonify', 'jsonify', (['group_list'], {}), '(group_list)\n', (3556, 3568), False, 'from flask import jsonify, session, request\n'), ((7897, 7943), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.delete', 'TeraParticipantGroup.delete', ([], {'id_todel': 'id_todel'}), '(id_todel=id_todel)\n', (7924, 7943), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((4804, 4828), 'flask_babel.gettext', 'gettext', (['"""Missing group"""'], {}), "('Missing group')\n", (4811, 4828), False, 'from flask_babel import gettext\n'), ((5021, 5074), 'flask_babel.gettext', 'gettext', (['"""Missing id_participant_group or id_project"""'], {}), "('Missing id_participant_group or id_project')\n", (5028, 5074), False, 'from flask_babel import gettext\n'), ((5341, 5361), 'flask_babel.gettext', 'gettext', (['"""Forbidden"""'], {}), "('Forbidden')\n", (5348, 5361), False, 'from flask_babel import gettext\n'), ((5508, 5583), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.update', 'TeraParticipantGroup.update', (["json_group['id_participant_group']", 'json_group'], {}), "(json_group['id_participant_group'], json_group)\n", (5535, 5583), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((6060, 6082), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup', 'TeraParticipantGroup', ([], {}), '()\n', (6080, 6082), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((6147, 6185), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.insert', 'TeraParticipantGroup.insert', (['new_group'], {}), '(new_group)\n', (6174, 6185), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((7786, 7806), 'flask_babel.gettext', 'gettext', (['"""Forbidden"""'], {}), "('Forbidden')\n", (7793, 7806), False, 'from flask_babel import gettext\n'), ((8368, 8486), 'flask_babel.gettext', 'gettext', (['"""Can\'t delete participant group: please delete all sessions from all participants before deleting."""'], {}), '(\n "Can\'t delete participant group: please delete all sessions from all participants before deleting."\n )\n', (8375, 8486), False, 'from flask_babel import gettext\n'), ((8595, 8609), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (8607, 8609), False, 'import sys\n'), ((8855, 8880), 'flask_babel.gettext', 'gettext', (['"""Database error"""'], {}), "('Database error')\n", (8862, 8880), False, 'from flask_babel import gettext\n'), ((2742, 2808), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_participant_group_by_id', 'TeraParticipantGroup.get_participant_group_by_id', (["args['id_group']"], {}), "(args['id_group'])\n", (2790, 2808), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((2948, 3022), 'opentera.db.models.TeraParticipantGroup.TeraParticipantGroup.get_participant_group_for_project', 'TeraParticipantGroup.get_participant_group_for_project', (["args['id_project']"], {}), "(args['id_project'])\n", (3002, 3022), False, 'from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup\n'), ((5678, 5692), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (5690, 5692), False, 'import sys\n'), ((5952, 5977), 'flask_babel.gettext', 'gettext', (['"""Database error"""'], {}), "('Database error')\n", (5959, 5977), False, 'from flask_babel import gettext\n'), ((6408, 6422), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (6420, 6422), False, 'import sys\n'), ((6682, 6707), 'flask_babel.gettext', 'gettext', (['"""Database error"""'], {}), "('Database error')\n", (6689, 6707), False, 'from flask_babel import gettext\n')]
#!/usr/bin/env python """ .. py:currentmodule:: FileFormat.Results.exported.test_XrayIntensityXY .. moduleauthor:: <NAME> <<EMAIL>> Tests for the module XrayIntensityXY. """ # Script information for the file. __author__ = "<NAME> (<EMAIL>)" __version__ = "" __date__ = "" __copyright__ = "Copyright (c) 2014 Hendrix Demers" __license__ = "" # Standard library modules. import unittest import logging import os.path # Third party modules. # Local modules. # Project modules import pymcxray.FileFormat.Results.exported.XrayIntensityXY as XrayIntensityXY # Globals and constants variables. class TestXrayIntensityXY(unittest.TestCase): """ TestCase class for the module `XrayIntensityXY`. """ def setUp(self): """ Setup method. """ unittest.TestCase.setUp(self) def tearDown(self): """ Teardown method. """ unittest.TestCase.tearDown(self) def testSkeleton(self): """ First test to check if the testcase is working with the testing framework. """ #self.fail("Test if the testcase is working.") self.assert_(True) def testOpenFile(self): """ Test if the test data file can be open. """ path = "../../test_data" filename = "AlMgBulk5keVB_Generated.txt" filepath = os.path.join(path, filename) xrayIntensityXY = XrayIntensityXY.XrayIntensityXY() xrayIntensityXY.readData(filepath) #self.fail("Test if the testcase is working.") self.assert_(True) if __name__ == '__main__': #pragma: no cover logging.getLogger().setLevel(logging.DEBUG) from pymcxray.Testings import runTestModuleWithCoverage runTestModuleWithCoverage(__file__)
[ "unittest.TestCase.setUp", "pymcxray.FileFormat.Results.exported.XrayIntensityXY.XrayIntensityXY", "unittest.TestCase.tearDown", "pymcxray.Testings.runTestModuleWithCoverage", "logging.getLogger" ]
[((1732, 1767), 'pymcxray.Testings.runTestModuleWithCoverage', 'runTestModuleWithCoverage', (['__file__'], {}), '(__file__)\n', (1757, 1767), False, 'from pymcxray.Testings import runTestModuleWithCoverage\n'), ((787, 816), 'unittest.TestCase.setUp', 'unittest.TestCase.setUp', (['self'], {}), '(self)\n', (810, 816), False, 'import unittest\n'), ((900, 932), 'unittest.TestCase.tearDown', 'unittest.TestCase.tearDown', (['self'], {}), '(self)\n', (926, 932), False, 'import unittest\n'), ((1412, 1445), 'pymcxray.FileFormat.Results.exported.XrayIntensityXY.XrayIntensityXY', 'XrayIntensityXY.XrayIntensityXY', ([], {}), '()\n', (1443, 1445), True, 'import pymcxray.FileFormat.Results.exported.XrayIntensityXY as XrayIntensityXY\n'), ((1624, 1643), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1641, 1643), False, 'import logging\n')]
#!/usr/bin/env python '''Communicating with Benchtop RIGOL Spectrum Analyzer RSA5065-TG ''' from colorama import init, Fore, Back init(autoreset=True) #to convert termcolor to wins color from os.path import basename as bs mdlname = bs(__file__).split('.')[0] # module's name e.g. PSG from time import sleep import pyvisa as visa from pyqum.instrument.logger import address, set_status, status_code, debug from pyqum.instrument.logger import translate_scpi as Attribute debugger = debug(mdlname) # INITIALIZATION def Initiate(which, mode='DATABASE'): ad = address(mode) rs = ad.lookup(mdlname, which) # Instrument's Address rm = visa.ResourceManager() try: bench = rm.open_resource(rs) #establishing connection using GPIB# with the machine stat = bench.write('*CLS') #Clear buffer memory; Load preset bench.read_termination = '\n' #omit termination tag from output bench.timeout = 150000 #set timeout in ms bench.write(":INIT:CONT ON") #continuous mode sleep(3) set_status(mdlname, dict(state='connected')) print(Fore.GREEN + "%s's connection Initialized: %s" % (mdlname, str(stat))) except: set_status(mdlname, dict(state='DISCONNECTED')) print(Fore.RED + "%s's connection NOT FOUND" % mdlname) # bench = "disconnected" return bench @Attribute def model(bench, action=['Get', '']): SCPIcore = '*IDN' #inquiring machine identity: "who r u?" return mdlname, bench, SCPIcore, action @Attribute def frequency(bench, action=['Get', '']): '''This command sets the signal generator output frequency for the CW frequency mode, or increments or decrements the current RF frequency setting.\n action=['Set','5GHz']''' SCPIcore = ':FREQ:CENT' return mdlname, bench, SCPIcore, action @Attribute def fspan(bench, action=['Get', '']): '''This command sets the signal generator output frequency for the CW frequency mode, or increments or decrements the current RF frequency setting.\n action=['Set','150MHz']''' SCPIcore = ':FREQ:SPAN' return mdlname, bench, SCPIcore, action @Attribute def rbw(bench, action=['Get', '']): '''This command sets the signal generator output frequency for the CW frequency mode, or increments or decrements the current RF frequency setting.\n action=['Set','1MHz']''' SCPIcore = ':BANDwidth:RESolution' return mdlname, bench, SCPIcore, action @Attribute def vbw(bench, action=['Get', '']): '''This command sets the signal generator output frequency for the CW frequency mode, or increments or decrements the current RF frequency setting.\n action=['Set','100kHz']''' SCPIcore = ':BANDwidth:VIDeo' return mdlname, bench, SCPIcore, action @Attribute def trigger_source(bench, action=['Get', '']): '''Trigger Source:\n EXTernal1|EXTernal2|IMMediate|VIDeo|FMT|POWer action=['Set','EXTernal1']''' SCPIcore = ':TRIGger:SOURCe' return mdlname, bench, SCPIcore, action @Attribute def preamp(bench, action=['Get', '']): '''Pre-amplifier state.\n action=['Set','ON']''' SCPIcore = ':POW:GAIN' return mdlname, bench, SCPIcore, action @Attribute def attenuation(bench, action=['Get', '']): '''Attenuation: 0 dB to 50 dB\n action=['Set','0dB']''' SCPIcore = ':POW:ATT' return mdlname, bench, SCPIcore, action @Attribute def attenuation_auto(bench, action=['Get', '']): '''Auto Attenuation mode.\n action=['Set','ON']''' SCPIcore = ':POW:ATT:AUTO' return mdlname, bench, SCPIcore, action def fpower(bench, freq): bench.query('*OPC?') bench.write(":CALC:MARK1:MODE POS") bench.write(":CALC:MARK1:X %s" %freq) return bench.query(":CALCulate:MARKer1:Y?") def close(bench, reset=True): if reset: bench.write('*RST') # reset to factory setting (including switch-off) set_status(mdlname, dict(config='reset')) else: set_status(mdlname, dict(config='previous')) try: bench.close() #None means Success? status = "Success" except: status = "Error" set_status(mdlname, dict(state='disconnected')) print(Back.WHITE + Fore.BLACK + "%s's connection Closed" %(mdlname)) return status # Test Zone def test(detail=True): S={} S['x'] = Initiate(1) s = S['x'] if s == "disconnected": pass else: if debug(mdlname, detail): print(Fore.RED + "Detailed Test:") # print('SCPI TEST:') # s.write("*SAV 00,1") model(s) frequency(s) frequency(s, action=['Set','5.5GHz']) fspan(s) fspan(s, action=['Set','150MHz']) else: print(Fore.RED + "Basic IO Test") if not bool(input("Press ENTER (OTHER KEY) to (skip) reset: ")): state = True else: state = False close(s, reset=state) return
[ "colorama.init", "pyqum.instrument.logger.address", "pyvisa.ResourceManager", "os.path.basename", "time.sleep", "pyqum.instrument.logger.debug" ]
[((131, 151), 'colorama.init', 'init', ([], {'autoreset': '(True)'}), '(autoreset=True)\n', (135, 151), False, 'from colorama import init, Fore, Back\n'), ((485, 499), 'pyqum.instrument.logger.debug', 'debug', (['mdlname'], {}), '(mdlname)\n', (490, 499), False, 'from pyqum.instrument.logger import address, set_status, status_code, debug\n'), ((565, 578), 'pyqum.instrument.logger.address', 'address', (['mode'], {}), '(mode)\n', (572, 578), False, 'from pyqum.instrument.logger import address, set_status, status_code, debug\n'), ((646, 668), 'pyvisa.ResourceManager', 'visa.ResourceManager', ([], {}), '()\n', (666, 668), True, 'import pyvisa as visa\n'), ((1023, 1031), 'time.sleep', 'sleep', (['(3)'], {}), '(3)\n', (1028, 1031), False, 'from time import sleep\n'), ((4405, 4427), 'pyqum.instrument.logger.debug', 'debug', (['mdlname', 'detail'], {}), '(mdlname, detail)\n', (4410, 4427), False, 'from pyqum.instrument.logger import address, set_status, status_code, debug\n'), ((234, 246), 'os.path.basename', 'bs', (['__file__'], {}), '(__file__)\n', (236, 246), True, 'from os.path import basename as bs\n')]
from Bagpipe.importer import raw_importer, pre_analyzed_importer from itertools import product as prod, combinations, chain from Bagpipe.exporter import pre_analyzed_exporter from Rexy.Core.general import cal_sim_product from statistics import median, mean from collections import defaultdict class ProductPreAnalyzer: def __init__(self, *args, **kwargs): self.products = kwargs['products'] def find_similarity_products(self, products=None): products = products or self.products for p1, p2 in combinations(products, 2): tags1 = dict(p1['tags']) tags2 = dict(p2['tags']) yield (p1, p2, *cal_sim_product(tags1, tags2)) def generate_product(self): similars = defaultdict(dict) for p1, p2, sim, diff_p1p2, diff_p2p1 in self.find_similarity_products(): # Similarity between products is a symmetric relation in this module # So we use one similarity value for both products. if sim: similars[p1['id']].update({p2['id']: {'similarity': sim, 'diff': diff_p2p1}}) similars[p2['id']].update({p1['id']: {'similarity': sim, 'diff': diff_p1p2}}) for p in self.products: yield dict({'similar_products': similars[p['id']]}, **p) # User class class UserPreAnalyzer: def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.max_rate = kwargs['max_rate'] self.download_factor = kwargs['download_factor'] self.view_factor = kwargs['view_factor'] self.rate_power_factor = kwargs['rate_power_factor'] self.products = kwargs['products'] self.users = kwargs['users'] self.add_product_affinity_user_tags() def get_users(self): return self.importer.import_user() def find_similarity(self): for u1, u2 in combinations(self.users, 2): yield (u1, u2, *self.cal_sim_user(u1, u2)) def cal_sim_user(self, u1, u2): products1 = u1['products'] products2 = u2['products'] product_id1 = {p['id'] for p in products1} product_id2 = {p['id'] for p in products2} common_ids = product_id1 & product_id2 union_ids = product_id1 | product_id2 diff_u1u2 = [p for k in product_id1 - product_id2 for p in products1 if p['id'] == k] diff_u2u1 = [p for k in product_id2 - product_id1 for p in products2 if p['id'] == k] # The ratio of the length of common products on all union products. intersection_factor = len(common_ids) / len(union_ids) # After calculating the intersection factor we will calculate the similarity factor # Which is mean of the medians of the similarities of each product related to user_1 # to each product related to user_2 combination = prod(products1, products2) d = defaultdict(list) for p1, p2 in combination: d[p1['id']].append(self.get_product_sim(p1, p2)) medians = map(median, d.values()) similarity_factor = mean(medians) return mean((similarity_factor, intersection_factor)), diff_u1u2, diff_u2u1 def get_product_sim(self, p1, p2): p1_id = p1['id'] p2_id = p2['id'] for p in self.products: if p['id'] == p1_id: return p['similar_products'].get(p2_id, {}).get('similarity', 0) elif p['id'] == p2_id: return p['similar_products'].get(p1_id, {}).get('similarity', 0) def add_product_affinity_user_tags(self): """Add `tags` field to users. Aggregate tags from user products and add an affinity based on produst's affinity to users and density of each tag for each product. The affinity of each tag to user calculates as follows: each tag has a list (Nj) contains tuples of the density of that tag to a user product and the affinity of that product to the user the final affinity is calculated based on following formula: aff(t(j)) = [Sigma(i=0 -> Nj) dens(i)*affinity(i)]/Nj + Nj/Sigma(j=0 -> M) Nj """ for u in self.users: tags = defaultdict(list) user_products = u['products'] product_ids = {p['id'] for p in user_products} affinities = {} for product in user_products: aff = self.affinity_calculator(product) product['affinity'] = aff affinities[product['id']] = aff for p in self.products: for t, dens in p['tags'].items(): if p['id'] in product_ids: tags[t].append((dens, affinities[p['id']])) tag_length = sum(map(len, tags.values())) u['tags'] = {t: (sum(dens * aff for dens, aff in lst) / len(lst) + len(lst) / tag_length) / 2 for t, lst in tags.items()} def affinity_calculator(self, product): status = product['status'] activity = product['activity'] rate = activity.get('rate') comment = activity.get('comment') share = activity.get('share') if status.lower() == 'download': stat_factor = self.download_factor if rate: rate_factor = rate / self.max_rate stat_factor = self.apply_rate_factor(stat_factor, rate_factor) else: # reduce the stat_factor if user has downloaded the product but doesn't rate. stat_factor = stat_factor * 3 / 4 if share: # increase the stat_factor in case the user has shared the product. stat_factor = stat_factor * 4 / 3 elif status.lower() == 'view': stat_factor = self.view_factor return stat_factor def apply_rate_factor(self, stat_factor, rate_factor): if rate_factor == 0.5: return stat_factor elif rate_factor < 0.5: return max(0, stat_factor - pow(rate_factor, self.rate_power_factor)) elif rate_factor > 0.5: return min(1, stat_factor + pow(rate_factor, self.rate_power_factor)) def generate_user(self): # Similarity between users is a symmetric relation in this module # So we use one similarity value for both users. similars = defaultdict(dict) for u1, u2, sim, diff_u1u2, diff_u2u1 in self.find_similarity(): if sim: similars[u1['id']].update({u2['id']: {'similarity': sim, 'diff': diff_u2u1}}) similars[u2['id']].update({u1['id']: {'similarity': sim, 'diff': diff_u1u2}}) for u in self.users: yield dict({'similar_users': similars[u1['id']]}, **u)
[ "collections.defaultdict", "itertools.combinations", "statistics.mean", "itertools.product", "Rexy.Core.general.cal_sim_product" ]
[((528, 553), 'itertools.combinations', 'combinations', (['products', '(2)'], {}), '(products, 2)\n', (540, 553), False, 'from itertools import product as prod, combinations, chain\n'), ((740, 757), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (751, 757), False, 'from collections import defaultdict\n'), ((1995, 2022), 'itertools.combinations', 'combinations', (['self.users', '(2)'], {}), '(self.users, 2)\n', (2007, 2022), False, 'from itertools import product as prod, combinations, chain\n'), ((2962, 2988), 'itertools.product', 'prod', (['products1', 'products2'], {}), '(products1, products2)\n', (2966, 2988), True, 'from itertools import product as prod, combinations, chain\n'), ((3002, 3019), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3013, 3019), False, 'from collections import defaultdict\n'), ((3186, 3199), 'statistics.mean', 'mean', (['medians'], {}), '(medians)\n', (3190, 3199), False, 'from statistics import median, mean\n'), ((6495, 6512), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (6506, 6512), False, 'from collections import defaultdict\n'), ((3216, 3262), 'statistics.mean', 'mean', (['(similarity_factor, intersection_factor)'], {}), '((similarity_factor, intersection_factor))\n', (3220, 3262), False, 'from statistics import median, mean\n'), ((4312, 4329), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (4323, 4329), False, 'from collections import defaultdict\n'), ((657, 686), 'Rexy.Core.general.cal_sim_product', 'cal_sim_product', (['tags1', 'tags2'], {}), '(tags1, tags2)\n', (672, 686), False, 'from Rexy.Core.general import cal_sim_product\n')]
import multiprocessing import sys import torch.optim as optim import numpy as np from functools import partial from src.base_model import BaseModel from src.networks import Destilation_student_matchingInstance from src.utils import save_images from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform class ADAModel(BaseModel): def __init__(self, cf, writer, results_folder, models_folder, tensorboard_folder, run_name, starting_epoch=0): self.cf = cf self.results_folder = results_folder self.models_folder = models_folder self.tensorboard_folder = tensorboard_folder self.run_name = run_name self.starting_epoch = starting_epoch self.seg_model = Destilation_student_matchingInstance(self.cf.labels - 1, self.cf.channels) self.seg_model.cuda() self.writer = writer self.seg_optimizer = optim.Adam(self.seg_model.parameters(), lr=self.cf.lr) step_1 = 20000 if self.cf.task == 'ms' else 5000 step_2 = 20000 if self.cf.task == 'ms' else 10000 scheduler_S = optim.lr_scheduler.MultiStepLR(self.seg_optimizer, milestones=[step_1, step_2], gamma=0.1) self.criterion = dice_soft_loss if self.cf.loss == 'dice' else bland_altman_loss self.criterion2 = ss_loss self.iterations = self.cf.iterations # Discriminator setup # self.discriminator = DiscriminatorDomain(352, 2, self.cf.discriminator_complexity) self.optimizer_discriminator = optim.Adam(self.discriminator.parameters(), lr=1e-4) ######################## self.correct = 0 self.num_of_subjects = 0 def initialise(self): self.seg_model.cuda() self.discriminator.cuda() self.p = multiprocessing.Pool(10) def training_loop(self, source_dl, target_dl): if self.iterations < self.cf.iterations_adapt: alpha = 0 beta = 0 else: alpha = self.cf.alpha_lweights beta = self.cf.beta_lweights source_batch = next(source_dl) source_inputs, source_labels = (source_batch['inputs'].to(self.device), source_batch['labels'].to(self.device)) target_batch = next(target_dl) target_inputs, target_labels = (target_batch['inputs'].to(self.device), target_batch['labels'].to(self.device)) outputs, _, _, _, _, _, _, _, _, _ = self.seg_model(source_inputs) # Training Discriminator self.seg_model.eval() self.discriminator.train() # do the sampling here. # Source Domain sampling inputs_source_discriminator = source_inputs # Target batch batch_trs = target_inputs.cpu().numpy() batch_trs = self.p.map( partial(non_geometric_augmentations, method='bias', norm_training_images=None), np.copy(batch_trs)) batch_trs = self.p.map( partial(non_geometric_augmentations, method='kspace', norm_training_images=None), np.copy(batch_trs)) inputs_target_discriminator_aug = torch.Tensor(batch_trs).cuda() Theta, Theta_inv = generate_affine(inputs_target_discriminator_aug, degreeFreedom=self.cf.affine_rot_degree, scale=self.cf.affine_scale, shearingScale=self.cf.affine_shearing) inputs_target_discriminator_aug = apply_transform(inputs_target_discriminator_aug, Theta) inputs_models_discriminator = torch.cat( (inputs_source_discriminator, inputs_target_discriminator_aug), 0) labels_discriminator = to_var_gpu( torch.cat((torch.zeros(inputs_source_discriminator.size(0)), torch.ones(inputs_target_discriminator_aug.size(0))), 0).type(torch.LongTensor)) # print('size Discriminator') # print(inputs_models_discriminator.size()) _, _, _, _, _, _, dec4, dec3, dec2, dec1 = self.seg_model(inputs_models_discriminator) dec1 = F.interpolate(dec1, size=dec2.size()[2:], mode='bilinear') dec2 = F.interpolate(dec2, size=dec2.size()[2:], mode='bilinear') dec3 = F.interpolate(dec3, size=dec2.size()[2:], mode='bilinear') dec4 = F.interpolate(dec4, size=dec2.size()[2:], mode='bilinear') inputs_discriminator = torch.cat((dec1, dec2, dec3, dec4), 1) self.discriminator.zero_grad() outputs_discriminator = self.discriminator(inputs_discriminator) loss_discriminator = torch.nn.CrossEntropyLoss(size_average=True)(outputs_discriminator, labels_discriminator) self.correct += (torch.argmax(outputs_discriminator, dim=1) == labels_discriminator).float().sum() self.num_of_subjects += int(outputs_discriminator.size(0)) loss_discriminator.backward() self.optimizer_discriminator.step() discriminator_loss = loss_discriminator.item() # Train model self.seg_model.train() self.discriminator.eval() # Here we get a new batch of target domain slices target_batch = next(target_dl) target_inputs, target_labels = (target_batch['inputs'].to(device), target_batch['labels'].to(device)) outputst, _, _, _, _, _, _, _, _, _ = self.seg_model(target_inputs) batch_trs = target_inputs.cpu().numpy() batch_trs = self.p.map( partial(non_geometric_augmentations, method='bias', norm_training_images=None), np.copy(batch_trs)) batch_trs = self.p.map( partial(non_geometric_augmentations, method='kspace', norm_training_images=None), np.copy(batch_trs)) inputstaug = torch.Tensor(batch_trs).cuda() Theta, Theta_inv = generate_affine(inputstaug, degreeFreedom=self.cf.affine_rot_degree, scale=self.cf.affine_scale, shearingScale=self.cf.affine_shearing) inputstaug = apply_transform(inputstaug, Theta) self.seg_model.zero_grad() outputstaug, _, _, _, _, _, _, _, _, _ = self.seg_model(inputstaug) outputst_transformed = apply_transform(outputst, Theta) inputs_models_discriminator = torch.cat((source_inputs, inputstaug), 0) _, _, _, _, _, _, dec4, dec3, dec2, dec1 = self.seg_model(inputs_models_discriminator) dec1 = F.interpolate(dec1, size=dec2.size()[2:], mode='bilinear') dec2 = F.interpolate(dec2, size=dec2.size()[2:], mode='bilinear') dec3 = F.interpolate(dec3, size=dec2.size()[2:], mode='bilinear') dec4 = F.interpolate(dec4, size=dec2.size()[2:], mode='bilinear') inputs_discriminator = torch.cat((dec1, dec2, dec3, dec4), 1) outputs_discriminator = self.discriminator(inputs_discriminator) labels_discriminator = to_var_gpu( torch.cat((torch.zeros(source_inputs.size(0)), torch.ones(inputstaug.size(0))), 0).type(torch.LongTensor)) loss_discriminator = torch.nn.CrossEntropyLoss(size_average=True)(outputs_discriminator, labels_discriminator) supervised_loss = dice_soft_loss(torch.sigmoid(outputs), source_labels) pc_loss = alpha * self.criterion(torch.sigmoid(outputstaug), torch.sigmoid(outputst_transformed)) adversarial_loss = - beta * loss_discriminator loss = supervised_loss + pc_loss + adversarial_loss self.seg_model.zero_grad() loss.backward() self.seg_optimizer.step() postfix_dict = {'loss': loss.item(), 'supervised_loss': supervised_loss.item(), 'pc_loss': pc_loss.item(), 'adversarial_loss': adversarial_loss.item(), 'loss_discriminator': loss_discriminator.item(), 'acc_discriminator': self.correct/self.num_of_subjects } tensorboard_dict = {'source_inputs': source_inputs, 'target_inputs': target_inputs, 'source_labels': source_labels, 'target_labels': target_labels, 'inputstaug': inputstaug, 'outputs': outputs, 'outputst': outputst} def validation_loop(self): if self.iterations < self.cf.iterations_adapt: alpha = 0 beta = 0 else: alpha = self.cf.alpha_lweights beta = self.cf.beta_lweights self.seg_model.eval() self.discriminator.eval() source_batch = next(source_dl) source_inputs, source_labels = (source_batch['inputs'].to(self.device), source_batch['labels'].to(self.device)) target_batch = next(target_dl) target_inputs, target_labels = (target_batch['inputs'].to(self.device), target_batch['labels'].to(self.device)) outputs, _, _, _, _, _, _, _, _, _ = self.seg_model(source_inputs) # Source Domain sampling inputs_source_discriminator = source_inputs # Target batch batch_trs = target_inputs.cpu().numpy() batch_trs = self.p.map( partial(non_geometric_augmentations, method='bias', norm_training_images=None), np.copy(batch_trs)) batch_trs = self.p.map( partial(non_geometric_augmentations, method='kspace', norm_training_images=None), np.copy(batch_trs)) inputs_target_discriminator_aug = torch.Tensor(batch_trs).cuda() Theta, Theta_inv = generate_affine(inputs_target_discriminator_aug, degreeFreedom=self.cf.affine_rot_degree, scale=self.cf.affine_scale, shearingScale=self.cf.affine_shearing) inputs_target_discriminator_aug = apply_transform(inputs_target_discriminator_aug, Theta) inputs_models_discriminator = torch.cat( (inputs_source_discriminator, inputs_target_discriminator_aug), 0) labels_discriminator = to_var_gpu( torch.cat((torch.zeros(inputs_source_discriminator.size(0)), torch.ones(inputs_target_discriminator_aug.size(0))), 0).type(torch.LongTensor)) _, _, _, _, _, _, dec4, dec3, dec2, dec1 = self.seg_model(inputs_models_discriminator) dec1 = F.interpolate(dec1, size=dec2.size()[2:], mode='bilinear') dec2 = F.interpolate(dec2, size=dec2.size()[2:], mode='bilinear') dec3 = F.interpolate(dec3, size=dec2.size()[2:], mode='bilinear') dec4 = F.interpolate(dec4, size=dec2.size()[2:], mode='bilinear') inputs_discriminator = torch.cat((dec1, dec2, dec3, dec4), 1) outputs_discriminator = self.discriminator(inputs_discriminator) loss_discriminator = torch.nn.CrossEntropyLoss(size_average=True)(outputs_discriminator, labels_discriminator) self.correct += (torch.argmax(outputs_discriminator, dim=1) == labels_discriminator).float().sum() self.num_of_subjects += int(outputs_discriminator.size(0)) # Here we get a new batch of target domain slices target_batch = next(target_dl) target_inputs, target_labels = (target_batch['inputs'].to(device), target_batch['labels'].to(device)) outputst, _, _, _, _, _, _, _, _, _ = self.seg_model(target_inputs) batch_trs = target_inputs.cpu().numpy() batch_trs = self.p.map( partial(non_geometric_augmentations, method='bias', norm_training_images=None), np.copy(batch_trs)) batch_trs = self.p.map( partial(non_geometric_augmentations, method='kspace', norm_training_images=None), np.copy(batch_trs)) inputstaug = torch.Tensor(batch_trs).cuda() Theta, Theta_inv = generate_affine(inputstaug, degreeFreedom=self.cf.affine_rot_degree, scale=self.cf.affine_scale, shearingScale=self.cf.affine_shearing) inputstaug = apply_transform(inputstaug, Theta) outputstaug, _, _, _, _, _, _, _, _, _ = self.seg_model(inputstaug) outputst_transformed = apply_transform(outputst, Theta) supervised_loss = dice_soft_loss(torch.sigmoid(outputs), source_labels) pc_loss = alpha * self.criterion(torch.sigmoid(outputstaug), torch.sigmoid(outputst_transformed)) adversarial_loss = - beta * loss_discriminator loss = supervised_loss + pc_loss + adversarial_loss postfix_dict = {'loss': loss.item(), 'supervised_loss': supervised_loss.item(), 'pc_loss': pc_loss.item(), 'adversarial_loss': adversarial_loss.item(), 'loss_discriminator': loss_discriminator.item(), 'acc_discriminator': self.correct/self.num_of_subjects } tensorboard_dict = {'source_inputs': source_inputs, 'target_inputs': target_inputs, 'source_labels': source_labels, 'target_labels': target_labels, 'inputstaug': inputstaug, 'outputs': outputs, 'outputst': outputst} def tensorboard_logging(self, tensorboard_dict, split): if self.cf.task == 'tumour': for idx, modality in enumerate(['flair', 't1c', 't1', 't2']): save_images(writer=self.writer, images=tensorboard_dict['source_inputs'][:, (idx,), :, :], normalize=True, sigmoid=False, iteration=self.iterations, name='source_{}/{}'.format(modality, split)) save_images(writer=self.writer, images=tensorboard_dict['target_inputs'][:, (idx,), :, :], normalize=True, sigmoid=False, iteration=self.iterations, name='target_{}/{}'.format(modality, split)) save_images(writer=self.writer, images=tensorboard_dict['inputstaug'][:, (idx,), :, :], normalize=True, sigmoid=False, iteration=self.iterations, name='{}_aug/{}'.format(modality, split)) elif self.cf.task == 'ms': save_images(writer=self.writer, images=tensorboard_dict['source_labels'], normalize=True, sigmoid=False, iteration=self.iterations, name='source_labels/{}'.format(split), png=True) save_images(writer=self.writer, images=tensorboard_dict['target_labels'], normalize=True, sigmoid=False, iteration=self.iterations, name='target_labels/{}'.format(split), png=True) save_images(writer=self.writer, images=tensorboard_dict['outputs'], normalize=False, sigmoid=True, iteration=self.iterations, name='outputs_source/{}'.format(split), png=True) save_images(writer=self.writer, images=tensorboard_dict['source_inputs'], normalize=True, sigmoid=False, png=True, iteration=self.iterations, name='source_inputs/{}'.format(split)) save_images(writer=self.writer, images=tensorboard_dict['target_inputs'], normalize=True, sigmoid=False, png=True, iteration=self.iterations, name='targets_inputs/{}'.format(split)) save_images(writer=self.writer, images=tensorboard_dict['inputstaug'], normalize=True, sigmoid=False, iteration=self.iterations, name='inputsaug/{}'.format(split)) save_images(writer=self.writer, images=tensorboard_dict['outputst'], normalize=False, sigmoid=True, iteration=self.iterations, name='outputs_target/{}'.format(split)) def load(self, checkpoint_path): self.starting_epoch = int(os.path.basename(checkpoint_path.split('.')[0]).split('_')[-1]) checkpoint = torch.load(checkpoint_path) self.seg_model = self.seg_model.load_state_dict(checkpoint['seg_model']) self.discriminator = self.discriminator.load_state_dict(checkpoint['discriminator']) self.optimizer_discriminator = self.optimizer_discriminator.load_state_dict(checkpoint['optimizer_discriminator']) self.seg_optimizer = self.seg_optimizer.load_state_dict(checkpoint['seg_optimizer']) def save(self): torch.save({'seg_model': self.seg_model.state_dict(), 'discriminator': self.discriminator.state_dict(), 'optimizer_discriminator': self.optimizer_discriminator.state_dict(), 'seg_optimizer': self.seg_optimizer.state_dict(), }, os.path.join(self.models_folder, self.run_name + '_{}.pt'.format(self.iterations))) def epoch_reset(self): self.correct = 0 self.num_of_subjects = 0
[ "functools.partial", "src.networks.Destilation_student_matchingInstance", "numpy.copy", "src.utils.apply_transform", "src.utils.generate_affine", "multiprocessing.Pool", "torch.optim.lr_scheduler.MultiStepLR" ]
[((797, 871), 'src.networks.Destilation_student_matchingInstance', 'Destilation_student_matchingInstance', (['(self.cf.labels - 1)', 'self.cf.channels'], {}), '(self.cf.labels - 1, self.cf.channels)\n', (833, 871), False, 'from src.networks import Destilation_student_matchingInstance\n'), ((1152, 1246), 'torch.optim.lr_scheduler.MultiStepLR', 'optim.lr_scheduler.MultiStepLR', (['self.seg_optimizer'], {'milestones': '[step_1, step_2]', 'gamma': '(0.1)'}), '(self.seg_optimizer, milestones=[step_1,\n step_2], gamma=0.1)\n', (1182, 1246), True, 'import torch.optim as optim\n'), ((1825, 1849), 'multiprocessing.Pool', 'multiprocessing.Pool', (['(10)'], {}), '(10)\n', (1845, 1849), False, 'import multiprocessing\n'), ((3283, 3449), 'src.utils.generate_affine', 'generate_affine', (['inputs_target_discriminator_aug'], {'degreeFreedom': 'self.cf.affine_rot_degree', 'scale': 'self.cf.affine_scale', 'shearingScale': 'self.cf.affine_shearing'}), '(inputs_target_discriminator_aug, degreeFreedom=self.cf.\n affine_rot_degree, scale=self.cf.affine_scale, shearingScale=self.cf.\n affine_shearing)\n', (3298, 3449), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((3566, 3621), 'src.utils.apply_transform', 'apply_transform', (['inputs_target_discriminator_aug', 'Theta'], {}), '(inputs_target_discriminator_aug, Theta)\n', (3581, 3621), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((5998, 6138), 'src.utils.generate_affine', 'generate_affine', (['inputstaug'], {'degreeFreedom': 'self.cf.affine_rot_degree', 'scale': 'self.cf.affine_scale', 'shearingScale': 'self.cf.affine_shearing'}), '(inputstaug, degreeFreedom=self.cf.affine_rot_degree, scale=\n self.cf.affine_scale, shearingScale=self.cf.affine_shearing)\n', (6013, 6138), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((6239, 6273), 'src.utils.apply_transform', 'apply_transform', (['inputstaug', 'Theta'], {}), '(inputstaug, Theta)\n', (6254, 6273), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((6417, 6449), 'src.utils.apply_transform', 'apply_transform', (['outputst', 'Theta'], {}), '(outputst, Theta)\n', (6432, 6449), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((9976, 10142), 'src.utils.generate_affine', 'generate_affine', (['inputs_target_discriminator_aug'], {'degreeFreedom': 'self.cf.affine_rot_degree', 'scale': 'self.cf.affine_scale', 'shearingScale': 'self.cf.affine_shearing'}), '(inputs_target_discriminator_aug, degreeFreedom=self.cf.\n affine_rot_degree, scale=self.cf.affine_scale, shearingScale=self.cf.\n affine_shearing)\n', (9991, 10142), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((10259, 10314), 'src.utils.apply_transform', 'apply_transform', (['inputs_target_discriminator_aug', 'Theta'], {}), '(inputs_target_discriminator_aug, Theta)\n', (10274, 10314), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((12339, 12479), 'src.utils.generate_affine', 'generate_affine', (['inputstaug'], {'degreeFreedom': 'self.cf.affine_rot_degree', 'scale': 'self.cf.affine_scale', 'shearingScale': 'self.cf.affine_shearing'}), '(inputstaug, degreeFreedom=self.cf.affine_rot_degree, scale=\n self.cf.affine_scale, shearingScale=self.cf.affine_shearing)\n', (12354, 12479), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((12580, 12614), 'src.utils.apply_transform', 'apply_transform', (['inputstaug', 'Theta'], {}), '(inputstaug, Theta)\n', (12595, 12614), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((12723, 12755), 'src.utils.apply_transform', 'apply_transform', (['outputst', 'Theta'], {}), '(outputst, Theta)\n', (12738, 12755), False, 'from src.utils import bland_altman_loss, dice_soft_loss, ss_loss, generate_affine, non_geometric_augmentations, apply_transform\n'), ((2912, 2990), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""bias"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='bias', norm_training_images=None)\n", (2919, 2990), False, 'from functools import partial\n'), ((3004, 3022), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (3011, 3022), True, 'import numpy as np\n'), ((3068, 3153), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""kspace"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='kspace', norm_training_images=None\n )\n", (3075, 3153), False, 'from functools import partial\n'), ((3162, 3180), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (3169, 3180), True, 'import numpy as np\n'), ((5648, 5726), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""bias"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='bias', norm_training_images=None)\n", (5655, 5726), False, 'from functools import partial\n'), ((5740, 5758), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (5747, 5758), True, 'import numpy as np\n'), ((5804, 5889), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""kspace"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='kspace', norm_training_images=None\n )\n", (5811, 5889), False, 'from functools import partial\n'), ((5898, 5916), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (5905, 5916), True, 'import numpy as np\n'), ((9606, 9684), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""bias"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='bias', norm_training_images=None)\n", (9613, 9684), False, 'from functools import partial\n'), ((9698, 9716), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (9705, 9716), True, 'import numpy as np\n'), ((9762, 9847), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""kspace"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='kspace', norm_training_images=None\n )\n", (9769, 9847), False, 'from functools import partial\n'), ((9856, 9874), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (9863, 9874), True, 'import numpy as np\n'), ((11989, 12067), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""bias"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='bias', norm_training_images=None)\n", (11996, 12067), False, 'from functools import partial\n'), ((12081, 12099), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (12088, 12099), True, 'import numpy as np\n'), ((12145, 12230), 'functools.partial', 'partial', (['non_geometric_augmentations'], {'method': '"""kspace"""', 'norm_training_images': 'None'}), "(non_geometric_augmentations, method='kspace', norm_training_images=None\n )\n", (12152, 12230), False, 'from functools import partial\n'), ((12239, 12257), 'numpy.copy', 'np.copy', (['batch_trs'], {}), '(batch_trs)\n', (12246, 12257), True, 'import numpy as np\n')]
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ BVT tests for network services on public IP's from different public IP range than that of associated source NAT IP of the network. Each IP associated with network from a different public IP range results in a new public interface on VR (eth3, eth4 etc) and iptable """ # Import Local Modules from marvin.codes import (FAILED) from marvin.cloudstackTestCase import cloudstackTestCase from marvin.cloudstackException import CloudstackAPIException from marvin.cloudstackAPI import rebootRouter from marvin.sshClient import SshClient from marvin.lib.utils import cleanup_resources, get_process_status from marvin.lib.base import (Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL) from marvin.lib.common import (get_domain, get_zone, get_template, list_hosts, list_routers) from nose.plugins.attrib import attr from ddt import ddt, data # Import System modules import socket import time import logging _multiprocess_shared_ = True logger = logging.getLogger('TestNetworkOps') stream_handler = logging.StreamHandler() logger.setLevel(logging.DEBUG) logger.addHandler(stream_handler) class TestPortForwarding(cloudstackTestCase): @classmethod def setUpClass(cls): testClient = super(TestPortForwarding, cls).getClsTestClient() cls.apiclient = testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() cls.hypervisor = testClient.getHypervisorInfo() # Get Zone, Domain and templates cls.domain = get_domain(cls.apiclient) cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests()) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["zoneid"] = cls.zone.id template = get_template( cls.apiclient, cls.zone.id, cls.services["ostype"] ) if template == FAILED: assert False, "get_template() failed to return template with description %s" % cls.services[ "ostype"] # Create an account, network, VM and IP addresses cls.account = Account.create( cls.apiclient, cls.services["account"], admin=True, domainid=cls.domain.id ) cls.services["publiciprange"]["zoneid"] = cls.zone.id cls.service_offering = ServiceOffering.create( cls.apiclient, cls.services["service_offerings"]["tiny"] ) cls.virtual_machine = VirtualMachine.create( cls.apiclient, cls.services["virtual_machine"], templateid=template.id, accountid=cls.account.name, domainid=cls.account.domainid, serviceofferingid=cls.service_offering.id ) cls._cleanup = [ cls.virtual_machine, cls.account, cls.service_offering ] def setUp(self): self.apiclient = self.testClient.getApiClient() self.cleanup = [] return @classmethod def tearDownClass(cls): try: cls.apiclient = super( TestPortForwarding, cls).getClsTestClient().getApiClient() cleanup_resources(cls.apiclient, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) def tearDown(self): cleanup_resources(self.apiclient, self.cleanup) return @attr(tags=["advanced", "smoke"], required_hardware="true") def test_port_forwarding_on_ip_from_non_src_nat_ip_range(self): """Test for port forwarding on a IP which is in pubic IP range different from public IP range that has source NAT IP associated with network """ # Validate the following: # 1. Create a new public IP range and dedicate to a account # 2. Acquire a IP from new public range # 3. create a port forwarding on acquired IP from new range # 4. Create a firewall rule to open up the port # 5. Test SSH works to the VM self.public_ip_range = PublicIpRange.create( self.apiclient, self.services["publiciprange"] ) logger.debug("Dedicating Public IP range to the account"); dedicate_public_ip_range_response = PublicIpRange.dedicate( self.apiclient, self.public_ip_range.vlan.id, account=self.account.name, domainid=self.account.domainid ) ip_address = PublicIPAddress.create( self.apiclient, self.account.name, self.zone.id, self.account.domainid, self.services["virtual_machine"] ) self.cleanup.append(ip_address) self.cleanup.append(self.public_ip_range) # Check if VM is in Running state before creating NAT and firewall rules vm_response = VirtualMachine.list( self.apiclient, id=self.virtual_machine.id ) self.assertEqual( isinstance(vm_response, list), True, "Check list VM returns a valid list" ) self.assertNotEqual( len(vm_response), 0, "Check Port Forwarding Rule is created" ) self.assertEqual( vm_response[0].state, 'Running', "VM state should be Running before creating a NAT rule." ) # Open up firewall port for SSH FireWallRule.create( self.apiclient, ipaddressid=ip_address.ipaddress.id, protocol=self.services["natrule"]["protocol"], cidrlist=['0.0.0.0/0'], startport=self.services["natrule"]["publicport"], endport=self.services["natrule"]["publicport"] ) # Create PF rule nat_rule = NATRule.create( self.apiclient, self.virtual_machine, self.services["natrule"], ip_address.ipaddress.id ) try: logger.debug("SSHing into VM with IP address %s with NAT IP %s" % ( self.virtual_machine.ipaddress, ip_address.ipaddress.ipaddress )) self.virtual_machine.get_ssh_client(ip_address.ipaddress.ipaddress) except Exception as e: self.fail( "SSH Access failed for %s: %s" % (self.virtual_machine.ipaddress, e) ) nat_rule.delete(self.apiclient) class TestStaticNat(cloudstackTestCase): @classmethod def setUpClass(cls): testClient = super(TestStaticNat, cls).getClsTestClient() cls.apiclient = testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() cls.hypervisor = testClient.getHypervisorInfo() # Get Zone, Domain and templates cls.domain = get_domain(cls.apiclient) cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests()) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["zoneid"] = cls.zone.id template = get_template( cls.apiclient, cls.zone.id, cls.services["ostype"] ) if template == FAILED: assert False, "get_template() failed to return template with description %s" % cls.services[ "ostype"] # Create an account, network, VM and IP addresses cls.account = Account.create( cls.apiclient, cls.services["account"], admin=True, domainid=cls.domain.id ) cls.services["publiciprange"]["zoneid"] = cls.zone.id cls.service_offering = ServiceOffering.create( cls.apiclient, cls.services["service_offerings"]["tiny"] ) cls.virtual_machine = VirtualMachine.create( cls.apiclient, cls.services["virtual_machine"], templateid=template.id, accountid=cls.account.name, domainid=cls.account.domainid, serviceofferingid=cls.service_offering.id ) cls.defaultNetworkId = cls.virtual_machine.nic[0].networkid cls._cleanup = [ cls.virtual_machine, cls.account, cls.service_offering ] def setUp(self): self.apiclient = self.testClient.getApiClient() self.cleanup = [] return @classmethod def tearDownClass(cls): try: cls.apiclient = super( TestStaticNat, cls).getClsTestClient().getApiClient() cleanup_resources(cls.apiclient, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) def tearDown(self): cleanup_resources(self.apiclient, self.cleanup) return @attr(tags=["advanced", "smoke"], required_hardware="true") def test_static_nat_on_ip_from_non_src_nat_ip_range(self): """Test for static nat on a IP which is in pubic IP range different from public IP range that has source NAT IP associated with network """ # Validate the following: # 1. Create a new public IP range and dedicate to a account # 2. Acquire a IP from new public range # 3. Enable static NAT on acquired IP from new range # 4. Create a firewall rule to open up the port # 5. Test SSH works to the VM self.public_ip_range = PublicIpRange.create( self.apiclient, self.services["publiciprange"] ) logger.debug("Dedicating Public IP range to the account"); dedicate_public_ip_range_response = PublicIpRange.dedicate( self.apiclient, self.public_ip_range.vlan.id, account=self.account.name, domainid=self.account.domainid ) ip_address = PublicIPAddress.create( self.apiclient, self.account.name, self.zone.id, self.account.domainid, self.services["virtual_machine"] ) self.cleanup.append(ip_address) self.cleanup.append(self.public_ip_range) # Check if VM is in Running state before creating NAT and firewall rules vm_response = VirtualMachine.list( self.apiclient, id=self.virtual_machine.id ) self.assertEqual( isinstance(vm_response, list), True, "Check list VM returns a valid list" ) self.assertNotEqual( len(vm_response), 0, "Check Port Forwarding Rule is created" ) self.assertEqual( vm_response[0].state, 'Running', "VM state should be Running before creating a NAT rule." ) # Open up firewall port for SSH FireWallRule.create( self.apiclient, ipaddressid=ip_address.ipaddress.id, protocol=self.services["natrule"]["protocol"], cidrlist=['0.0.0.0/0'], startport=self.services["natrule"]["publicport"], endport=self.services["natrule"]["publicport"] ) # Create Static NAT rule StaticNATRule.enable( self.apiclient, ip_address.ipaddress.id, self.virtual_machine.id, self.defaultNetworkId ) try: logger.debug("SSHing into VM with IP address %s with NAT IP %s" % ( self.virtual_machine.ipaddress, ip_address.ipaddress.ipaddress )) self.virtual_machine.get_ssh_client(ip_address.ipaddress.ipaddress) except Exception as e: self.fail( "SSH Access failed for %s: %s" % (self.virtual_machine.ipaddress, e) ) StaticNATRule.disable( self.apiclient, ip_address.ipaddress.id, self.virtual_machine.id ) class TestRouting(cloudstackTestCase): @classmethod def setUpClass(cls): testClient = super(TestRouting, cls).getClsTestClient() cls.apiclient = testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() cls.hypervisor = testClient.getHypervisorInfo() # Get Zone, Domain and templates cls.domain = get_domain(cls.apiclient) cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests()) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["zoneid"] = cls.zone.id template = get_template( cls.apiclient, cls.zone.id, cls.services["ostype"] ) if template == FAILED: assert False, "get_template() failed to return template with description %s" % cls.services[ "ostype"] # Create an account, network, VM and IP addresses cls.account = Account.create( cls.apiclient, cls.services["account"], admin=True, domainid=cls.domain.id ) cls.services["publiciprange"]["zoneid"] = cls.zone.id cls.service_offering = ServiceOffering.create( cls.apiclient, cls.services["service_offerings"]["tiny"] ) cls.hostConfig = cls.config.__dict__["zones"][0].__dict__["pods"][0].__dict__["clusters"][0].__dict__["hosts"][0].__dict__ cls.virtual_machine = VirtualMachine.create( cls.apiclient, cls.services["virtual_machine"], templateid=template.id, accountid=cls.account.name, domainid=cls.account.domainid, serviceofferingid=cls.service_offering.id ) cls._cleanup = [ cls.virtual_machine, cls.account, cls.service_offering ] def setUp(self): self.apiclient = self.testClient.getApiClient() self.cleanup = [] return @classmethod def tearDownClass(cls): try: cls.apiclient = super( TestRouting, cls).getClsTestClient().getApiClient() cleanup_resources(cls.apiclient, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) def tearDown(self): cleanup_resources(self.apiclient, self.cleanup) return @attr(tags=["advanced", "smoke"], required_hardware="true") def test_routing_tables(self): """Test routing table in case we have IP associated with a network which is in different pubic IP range from that of public IP range that has source NAT IP. When IP is associated we should see a new route table created. When IP is associated we should see a that route table is deleted. """ # Validate the following: # 1. Create a new public IP range and dedicate to a account # 2. Acquire a IP from new public range # 3. Create a firewall rule to open up the port, so that IP is associated with network # 5. Login to VR and verify routing tables, there should be Table_eth3 # 6. Delete firewall rule, since its last IP, routing table Table_eth3 should be deleted self.public_ip_range = PublicIpRange.create( self.apiclient, self.services["publiciprange"] ) self._cleanup.append(self.public_ip_range) logger.debug("Dedicating Public IP range to the account"); dedicate_public_ip_range_response = PublicIpRange.dedicate( self.apiclient, self.public_ip_range.vlan.id, account=self.account.name, domainid=self.account.domainid ) ip_address = PublicIPAddress.create( self.apiclient, self.account.name, self.zone.id, self.account.domainid, self.services["virtual_machine"] ) self.cleanup.append(ip_address) self.cleanup.append(self.public_ip_range) # Check if VM is in Running state before creating NAT and firewall rules vm_response = VirtualMachine.list( self.apiclient, id=self.virtual_machine.id ) self.assertEqual( isinstance(vm_response, list), True, "Check list VM returns a valid list" ) self.assertNotEqual( len(vm_response), 0, "Check Port Forwarding Rule is created" ) self.assertEqual( vm_response[0].state, 'Running', "VM state should be Running before creating Firewall rule." ) # Open up firewall port for SSH, this will associate IP with VR firewall_rule = FireWallRule.create( self.apiclient, ipaddressid=ip_address.ipaddress.id, protocol=self.services["natrule"]["protocol"], cidrlist=['0.0.0.0/0'], startport=self.services["natrule"]["publicport"], endport=self.services["natrule"]["publicport"] ) # Get the router details associated with account routers = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid, ) router = routers[0] if (self.hypervisor.lower() == 'vmware' or self.hypervisor.lower() == 'hyperv'): result = get_process_status( self.apiclient.connection.mgtSvr, 22, self.apiclient.connection.user, self.apiclient.connection.passwd, router.linklocalip, 'ip route list table Table_eth3', hypervisor=self.hypervisor ) else: hosts = list_hosts( self.apiclient, id=router.hostid, ) self.assertEqual( isinstance(hosts, list), True, "Check for list hosts response return valid data" ) host = hosts[0] host.user = self.hostConfig['username'] host.passwd = self.hostConfig['password'] try: result = get_process_status( host.ipaddress, 22, host.user, host.passwd, router.linklocalip, 'ip route list table Table_eth3' ) except KeyError: self.skipTest( "Provide a marvin config file with host\ credentials to run %s" % self._testMethodName) logger.debug("ip route list table Table_eth3: %s" % result) public_range_gateway = self.services["publiciprange"]["gateway"] default_route_rule = "default via " + public_range_gateway + " dev eth3 proto static" logger.debug("default route result: %s" % str(result[0])) self.assertEqual( default_route_rule, str(result[0]), "Check default route table entry for public ip range" ) res = str(result) self.assertEqual( res.count("throw") == 2, True, "Check routing rules to throw rest of the traffic. Count shoule be Atleast 2 for the control and guest traffic " ) firewall_rule.delete(self.apiclient) if (self.hypervisor.lower() == 'vmware' or self.hypervisor.lower() == 'hyperv'): result = get_process_status( self.apiclient.connection.mgtSvr, 22, self.apiclient.connection.user, self.apiclient.connection.passwd, router.linklocalip, 'ip route list table Table_eth3', hypervisor=self.hypervisor ) else: hosts = list_hosts( self.apiclient, id=router.hostid, ) self.assertEqual( isinstance(hosts, list), True, "Check for list hosts response return valid data" ) host = hosts[0] host.user = self.hostConfig['username'] host.passwd = self.hostConfig['password'] try: result = get_process_status( host.ipaddress, 22, host.user, host.passwd, router.linklocalip, 'ip route list table Table_eth3' ) except KeyError: self.skipTest( "Provide a marvin config file with host\ credentials to run %s" % self._testMethodName) logger.debug("ip route list table Table_eth3: %s" % result) res = str(result) self.assertEqual( res.count("default via"), 0, "Check to ensure there should not be any default rule" ) self.assertEqual( res.count("throw"), 0, "Check to ensure there should not be any throw rule" ) class TestIptables(cloudstackTestCase): @classmethod def setUpClass(cls): testClient = super(TestIptables, cls).getClsTestClient() cls.apiclient = testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() cls.hypervisor = testClient.getHypervisorInfo() # Get Zone, Domain and templates cls.domain = get_domain(cls.apiclient) cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests()) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["zoneid"] = cls.zone.id template = get_template( cls.apiclient, cls.zone.id, cls.services["ostype"] ) if template == FAILED: assert False, "get_template() failed to return template with description %s" % cls.services[ "ostype"] # Create an account, network, VM and IP addresses cls.account = Account.create( cls.apiclient, cls.services["account"], admin=True, domainid=cls.domain.id ) cls.services["publiciprange"]["zoneid"] = cls.zone.id cls.service_offering = ServiceOffering.create( cls.apiclient, cls.services["service_offerings"]["tiny"] ) cls.hostConfig = cls.config.__dict__["zones"][0].__dict__["pods"][0].__dict__["clusters"][0].__dict__["hosts"][0].__dict__ cls.virtual_machine = VirtualMachine.create( cls.apiclient, cls.services["virtual_machine"], templateid=template.id, accountid=cls.account.name, domainid=cls.account.domainid, serviceofferingid=cls.service_offering.id ) cls._cleanup = [ cls.virtual_machine, cls.account, cls.service_offering ] def setUp(self): self.apiclient = self.testClient.getApiClient() self.cleanup = [] return @classmethod def tearDownClass(cls): try: cls.apiclient = super( TestIptables, cls).getClsTestClient().getApiClient() cleanup_resources(cls.apiclient, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) def tearDown(self): cleanup_resources(self.apiclient, self.cleanup) return @attr(tags=["advanced", "smoke"], required_hardware="true") def test_iptable_rules(self): """Test iptable rules in case we have IP associated with a network which is in different pubic IP range from that of public IP range that has source NAT IP. When IP is associated we should see a rule '-i eth3 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT' in FORWARD table. When IP is dis-associated we should see a rule in the FORWARD table is deleted. """ # Validate the following: # 1. Create a new public IP range and dedicate to a account # 2. Acquire a IP from new public range # 3. Create a firewall rule to open up the port, so that IP is associated with network # 5. Login to VR and verify routing tables, there should be Table_eth3 # 6. Delete firewall rule, since its last IP, routing table Table_eth3 should be deleted self.public_ip_range = PublicIpRange.create( self.apiclient, self.services["publiciprange"] ) self._cleanup.append(self.public_ip_range) logger.debug("Dedicating Public IP range to the account"); dedicate_public_ip_range_response = PublicIpRange.dedicate( self.apiclient, self.public_ip_range.vlan.id, account=self.account.name, domainid=self.account.domainid ) ip_address = PublicIPAddress.create( self.apiclient, self.account.name, self.zone.id, self.account.domainid, self.services["virtual_machine"] ) self.cleanup.append(ip_address) # Check if VM is in Running state before creating NAT and firewall rules vm_response = VirtualMachine.list( self.apiclient, id=self.virtual_machine.id ) self.assertEqual( isinstance(vm_response, list), True, "Check list VM returns a valid list" ) self.assertNotEqual( len(vm_response), 0, "Check Port Forwarding Rule is created" ) self.assertEqual( vm_response[0].state, 'Running', "VM state should be Running before creating a NAT rule." ) # Open up firewall port for SSH firewall_rule = FireWallRule.create( self.apiclient, ipaddressid=ip_address.ipaddress.id, protocol=self.services["natrule"]["protocol"], cidrlist=['0.0.0.0/0'], startport=self.services["natrule"]["publicport"], endport=self.services["natrule"]["publicport"] ) # Get the router details associated with account routers = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid, ) router = routers[0] if (self.hypervisor.lower() == 'vmware' or self.hypervisor.lower() == 'hyperv'): result = get_process_status( self.apiclient.connection.mgtSvr, 22, self.apiclient.connection.user, self.apiclient.connection.passwd, router.linklocalip, 'iptables -t filter -L FORWARD -v', hypervisor=self.hypervisor ) else: hosts = list_hosts( self.apiclient, id=router.hostid, ) self.assertEqual( isinstance(hosts, list), True, "Check for list hosts response return valid data" ) host = hosts[0] host.user = self.hostConfig['username'] host.passwd = self.hostConfig['password'] try: result = get_process_status( host.ipaddress, 22, host.user, host.passwd, router.linklocalip, 'iptables -t filter -L FORWARD -v' ) except KeyError: self.skipTest( "Provide a marvin config file with host\ credentials to run %s" % self._testMethodName) logger.debug("iptables -t filter -L FORWARD -v: %s" % result) res = str(result) self.assertEqual( res.count("eth3 eth0 anywhere anywhere state RELATED,ESTABLISHED"), 1, "Check to ensure there is a iptable rule to accept the RELATED,ESTABLISHED traffic" ) firewall_rule.delete(self.apiclient) class TestVPCPortForwarding(cloudstackTestCase): @classmethod def setUpClass(cls): socket.setdefaulttimeout(60) testClient = super(TestVPCPortForwarding, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() # Get Zone, Domain and templates cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["vpc_offering"] = { "name": 'VPC off', "displaytext": 'VPC off', "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat', } cls.services["network_offering"] = { "name": 'VPC Network offering', "displaytext": 'VPC Network off', "guestiptype": 'Isolated', "supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL', "traffictype": 'GUEST', "availability": 'Optional', "useVpc": 'on', "serviceProviderList": { "Vpn": 'VpcVirtualRouter', "Dhcp": 'VpcVirtualRouter', "Dns": 'VpcVirtualRouter', "SourceNat": 'VpcVirtualRouter', "PortForwarding": 'VpcVirtualRouter', "Lb": 'VpcVirtualRouter', "UserData": 'VpcVirtualRouter', "StaticNat": 'VpcVirtualRouter', "NetworkACL": 'VpcVirtualRouter' }, } cls.services["network"] = { "name": "Test Network", "displaytext": "Test Network", "netmask": '255.255.255.0' } cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["virtual_machine"]["template"] = cls.template.id cls.services["publiciprange"]["zoneid"] = cls.zone.id cls.service_offering = ServiceOffering.create( cls.api_client, cls.services["service_offering"] ) cls._cleanup = [cls.service_offering] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.account = Account.create( self.apiclient, self.services["account"], admin=True, domainid=self.domain.id ) self.cleanup = [self.account] logger.debug("Creating a VPC offering..") self.vpc_off = VpcOffering.create( self.apiclient, self.services["vpc_offering"] ) self._cleanup.append(self.vpc_off) logger.debug("Enabling the VPC offering created") self.vpc_off.update(self.apiclient, state='Enabled') logger.debug("Creating a VPC network in the account: %s" % self.account.name) self.services["vpc"]["cidr"] = '10.1.0.0/16' self.vpc = VPC.create( self.apiclient, self.services["vpc"], vpcofferingid=self.vpc_off.id, zoneid=self.zone.id, account=self.account.name, domainid=self.account.domainid ) return def tearDown(self): try: #Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) except Exception as e: logger.debug("Warning: Exception during cleanup : %s" % e) return def check_ssh_into_vm(self, vm, public_ip, testnegative=False): logger.debug("Checking if we can SSH into VM=%s on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress)) try: vm.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress) if not testnegative: logger.debug("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress)) else: self.fail("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress)) except: if not testnegative: self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress)) else: logger.debug("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress)) def create_natrule(self, vm, public_ip, network, services=None): logger.debug("Creating NAT rule in network for vm with public IP") if not services: services = self.services["natrule"] nat_rule = NATRule.create(self.apiclient, vm, services, ipaddressid=public_ip.ipaddress.id, openfirewall=False, networkid=network.id, vpcid=self.vpc.id ) return nat_rule def acquire_publicip(self, network): logger.debug("Associating public IP for network: %s" % network.name) public_ip = PublicIPAddress.create(self.apiclient, accountid=self.account.name, zoneid=self.zone.id, domainid=self.account.domainid, networkid=network.id, vpcid=self.vpc.id ) logger.debug("Associated %s with network %s" % (public_ip.ipaddress.ipaddress, network.id )) return public_ip def create_network(self, net_offerring, gateway='10.1.1.1',vpc=None): try: logger.debug('Create NetworkOffering') net_offerring["name"] = "NET_OFF-" + str(gateway) nw_off = NetworkOffering.create(self.apiclient, net_offerring, conservemode=False ) # Enable Network offering nw_off.update(self.apiclient, state='Enabled') self._cleanup.append(nw_off) logger.debug('Created and Enabled NetworkOffering') self.services["network"]["name"] = "NETWORK-" + str(gateway) logger.debug('Adding Network=%s' % self.services["network"]) default_acl = NetworkACLList.list(self.apiclient, name="default_allow")[0] obj_network = Network.create(self.apiclient, self.services["network"], accountid=self.account.name, domainid=self.account.domainid, networkofferingid=nw_off.id, zoneid=self.zone.id, gateway=gateway, aclid=default_acl.id, vpcid=vpc.id if vpc else self.vpc.id ) logger.debug("Created network with ID: %s" % obj_network.id) return obj_network except Exception as e: self.fail('Unable to create a Network with offering=%s because of %s ' % (net_offerring, e)) def deployvm_in_network(self, network, host_id=None): try: logger.debug('Creating VM in network=%s' % network.name) vm = VirtualMachine.create( self.apiclient, self.services["virtual_machine"], accountid=self.account.name, domainid=self.account.domainid, serviceofferingid=self.service_offering.id, networkids=[str(network.id)], hostid=host_id ) logger.debug('Created VM=%s in network=%s' % (vm.id, network.name)) return vm except: self.fail('Unable to create VM in a Network=%s' % network.name) @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_network_services_VPC_CreatePF(self): """ Test Create VPC PF rules on acquired public ip when VpcVirtualRouter is Running """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Use the Create PF rule for vm in network1. # 6. Successfully ssh into the Guest VM using the PF rule network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) self.public_ip_range = PublicIpRange.create( self.apiclient, self.services["publiciprange"] ) self._cleanup.append(self.public_ip_range) logger.debug("Dedicating Public IP range to the account"); dedicate_public_ip_range_response = PublicIpRange.dedicate( self.apiclient, self.public_ip_range.vlan.id, account=self.account.name, domainid=self.account.domainid ) public_ip_1 = self.acquire_publicip(network_1) self.create_natrule( vm_1, public_ip_1, network_1) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.public_ip_range.release(self.apiclient) return class TestVPCStaticNat(cloudstackTestCase): @classmethod def setUpClass(cls): socket.setdefaulttimeout(60) testClient = super(TestVPCStaticNat, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() # Get Zone, Domain and templates cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["vpc_offering"] = { "name": 'VPC off', "displaytext": 'VPC off', "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat', } cls.services["network_offering"] = { "name": 'VPC Network offering', "displaytext": 'VPC Network off', "guestiptype": 'Isolated', "supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL', "traffictype": 'GUEST', "availability": 'Optional', "useVpc": 'on', "serviceProviderList": { "Vpn": 'VpcVirtualRouter', "Dhcp": 'VpcVirtualRouter', "Dns": 'VpcVirtualRouter', "SourceNat": 'VpcVirtualRouter', "PortForwarding": 'VpcVirtualRouter', "Lb": 'VpcVirtualRouter', "UserData": 'VpcVirtualRouter', "StaticNat": 'VpcVirtualRouter', "NetworkACL": 'VpcVirtualRouter' }, } cls.services["network"] = { "name": "Test Network", "displaytext": "Test Network", "netmask": '255.255.255.0' } cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["virtual_machine"]["template"] = cls.template.id cls.services["publiciprange"]["zoneid"] = cls.zone.id cls.service_offering = ServiceOffering.create( cls.api_client, cls.services["service_offering"] ) cls._cleanup = [cls.service_offering] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.account = Account.create( self.apiclient, self.services["account"], admin=True, domainid=self.domain.id ) self.cleanup = [self.account] logger.debug("Creating a VPC offering..") self.vpc_off = VpcOffering.create( self.apiclient, self.services["vpc_offering"] ) self._cleanup.append(self.vpc_off) logger.debug("Enabling the VPC offering created") self.vpc_off.update(self.apiclient, state='Enabled') logger.debug("Creating a VPC network in the account: %s" % self.account.name) self.services["vpc"]["cidr"] = '10.1.0.0/16' self.vpc = VPC.create( self.apiclient, self.services["vpc"], vpcofferingid=self.vpc_off.id, zoneid=self.zone.id, account=self.account.name, domainid=self.account.domainid ) return def tearDown(self): try: #Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) except Exception as e: logger.debug("Warning: Exception during cleanup : %s" % e) return def check_ssh_into_vm(self, vm, public_ip, testnegative=False): logger.debug("Checking if we can SSH into VM=%s on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress)) try: vm.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress) if not testnegative: logger.debug("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress)) else: self.fail("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress)) except: if not testnegative: self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress)) else: logger.debug("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress)) def acquire_publicip(self, network): logger.debug("Associating public IP for network: %s" % network.name) public_ip = PublicIPAddress.create(self.apiclient, accountid=self.account.name, zoneid=self.zone.id, domainid=self.account.domainid, networkid=network.id, vpcid=self.vpc.id ) logger.debug("Associated %s with network %s" % (public_ip.ipaddress.ipaddress, network.id )) return public_ip def create_network(self, net_offerring, gateway='10.1.1.1',vpc=None): try: logger.debug('Create NetworkOffering') net_offerring["name"] = "NET_OFF-" + str(gateway) nw_off = NetworkOffering.create(self.apiclient, net_offerring, conservemode=False ) # Enable Network offering nw_off.update(self.apiclient, state='Enabled') self._cleanup.append(nw_off) logger.debug('Created and Enabled NetworkOffering') self.services["network"]["name"] = "NETWORK-" + str(gateway) logger.debug('Adding Network=%s' % self.services["network"]) default_acl = NetworkACLList.list(self.apiclient, name="default_allow")[0] obj_network = Network.create(self.apiclient, self.services["network"], accountid=self.account.name, domainid=self.account.domainid, networkofferingid=nw_off.id, zoneid=self.zone.id, gateway=gateway, aclid=default_acl.id, vpcid=vpc.id if vpc else self.vpc.id ) logger.debug("Created network with ID: %s" % obj_network.id) return obj_network except Exception as e: self.fail('Unable to create a Network with offering=%s because of %s ' % (net_offerring, e)) def deployvm_in_network(self, network, host_id=None): try: logger.debug('Creating VM in network=%s' % network.name) vm = VirtualMachine.create( self.apiclient, self.services["virtual_machine"], accountid=self.account.name, domainid=self.account.domainid, serviceofferingid=self.service_offering.id, networkids=[str(network.id)], hostid=host_id ) logger.debug('Created VM=%s in network=%s' % (vm.id, network.name)) return vm except: self.fail('Unable to create VM in a Network=%s' % network.name) def create_StaticNatRule_For_VM(self, vm, public_ip, network, services=None): logger.debug("Enabling static NAT for IP: %s" %public_ip.ipaddress.ipaddress) if not services: services = self.services["natrule"] try: StaticNATRule.enable( self.apiclient, ipaddressid=public_ip.ipaddress.id, virtualmachineid=vm.id, networkid=network.id ) logger.debug("Static NAT enabled for IP: %s" % public_ip.ipaddress.ipaddress) logger.debug("Adding NetworkACL rules to make NAT rule accessible") except Exception as e: self.fail("Failed to enable static NAT on IP: %s - %s" % ( public_ip.ipaddress.ipaddress, e)) @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_network_services_VPC_CreatePF(self): """ Test Create VPC PF rules on acquired public ip when VpcVirtualRouter is Running """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Use the Create PF rule for vm in network1. # 6. Successfully ssh into the Guest VM using the PF rule network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) self.public_ip_range = PublicIpRange.create( self.apiclient, self.services["publiciprange"] ) self._cleanup.append(self.public_ip_range) logger.debug("Dedicating Public IP range to the account"); dedicate_public_ip_range_response = PublicIpRange.dedicate( self.apiclient, self.public_ip_range.vlan.id, account=self.account.name, domainid=self.account.domainid ) public_ip_1 = self.acquire_publicip(network_1) self.create_StaticNatRule_For_VM( vm_1, public_ip_1, network_1) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.public_ip_range.release(self.apiclient) return
[ "marvin.lib.utils.cleanup_resources", "marvin.lib.base.FireWallRule.create", "marvin.lib.base.Account.create", "marvin.lib.common.list_hosts", "marvin.lib.base.VPC.create", "marvin.lib.common.get_template", "marvin.lib.utils.get_process_status", "marvin.lib.base.ServiceOffering.create", "socket.setdefaulttimeout", "marvin.lib.common.get_domain", "marvin.lib.common.list_routers", "marvin.lib.base.StaticNATRule.disable", "marvin.lib.base.NATRule.create", "marvin.lib.base.NetworkOffering.create", "logging.StreamHandler", "marvin.lib.base.PublicIPAddress.create", "marvin.lib.base.VirtualMachine.list", "marvin.lib.base.VirtualMachine.create", "marvin.lib.base.PublicIpRange.dedicate", "marvin.lib.base.VpcOffering.create", "marvin.lib.base.NetworkACLList.list", "marvin.lib.base.PublicIpRange.create", "marvin.lib.base.StaticNATRule.enable", "marvin.lib.base.Network.create", "nose.plugins.attrib.attr", "logging.getLogger" ]
[((2451, 2486), 'logging.getLogger', 'logging.getLogger', (['"""TestNetworkOps"""'], {}), "('TestNetworkOps')\n", (2468, 2486), False, 'import logging\n'), ((2504, 2527), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2525, 2527), False, 'import logging\n'), ((4925, 4983), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (4929, 4983), False, 'from nose.plugins.attrib import attr\n'), ((10693, 10751), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (10697, 10751), False, 'from nose.plugins.attrib import attr\n'), ((16605, 16663), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (16609, 16663), False, 'from nose.plugins.attrib import attr\n'), ((26226, 26284), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'smoke']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'smoke'], required_hardware='true')\n", (26230, 26284), False, 'from nose.plugins.attrib import attr\n'), ((41159, 41221), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'intervlan'], required_hardware='true')\n", (41163, 41221), False, 'from nose.plugins.attrib import attr\n'), ((53085, 53147), 'nose.plugins.attrib.attr', 'attr', ([], {'tags': "['advanced', 'intervlan']", 'required_hardware': '"""true"""'}), "(tags=['advanced', 'intervlan'], required_hardware='true')\n", (53089, 53147), False, 'from nose.plugins.attrib import attr\n'), ((2983, 3008), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (2993, 3008), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((3210, 3274), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (3222, 3274), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((3564, 3659), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (3578, 3659), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((3806, 3891), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['tiny']"], {}), "(cls.apiclient, cls.services['service_offerings']['tiny']\n )\n", (3828, 3891), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((3951, 4155), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.apiclient, cls.services['virtual_machine'],\n templateid=template.id, accountid=cls.account.name, domainid=cls.\n account.domainid, serviceofferingid=cls.service_offering.id)\n", (3972, 4155), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((4856, 4903), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (4873, 4903), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((5569, 5637), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (5589, 5637), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((5855, 5986), 'marvin.lib.base.PublicIpRange.dedicate', 'PublicIpRange.dedicate', (['self.apiclient', 'self.public_ip_range.vlan.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.public_ip_range.vlan.id,\n account=self.account.name, domainid=self.account.domainid)\n', (5877, 5986), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((6242, 6374), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.account.name', 'self.zone.id', 'self.account.domainid', "self.services['virtual_machine']"], {}), "(self.apiclient, self.account.name, self.zone.id,\n self.account.domainid, self.services['virtual_machine'])\n", (6264, 6374), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((6634, 6697), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (6653, 6697), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((7227, 7481), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ip_address.ipaddress.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=ip_address.ipaddress.id,\n protocol=self.services['natrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['natrule']['publicport'], endport=self.services\n ['natrule']['publicport'])\n", (7246, 7481), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((7596, 7704), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'self.virtual_machine', "self.services['natrule']", 'ip_address.ipaddress.id'], {}), "(self.apiclient, self.virtual_machine, self.services[\n 'natrule'], ip_address.ipaddress.id)\n", (7610, 7704), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((8688, 8713), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (8698, 8713), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((8915, 8979), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (8927, 8979), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((9269, 9364), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (9283, 9364), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((9511, 9596), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['tiny']"], {}), "(cls.apiclient, cls.services['service_offerings']['tiny']\n )\n", (9533, 9596), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((9656, 9860), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.apiclient, cls.services['virtual_machine'],\n templateid=template.id, accountid=cls.account.name, domainid=cls.\n account.domainid, serviceofferingid=cls.service_offering.id)\n", (9677, 9860), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((10624, 10671), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (10641, 10671), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((11320, 11388), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (11340, 11388), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((11605, 11736), 'marvin.lib.base.PublicIpRange.dedicate', 'PublicIpRange.dedicate', (['self.apiclient', 'self.public_ip_range.vlan.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.public_ip_range.vlan.id,\n account=self.account.name, domainid=self.account.domainid)\n', (11627, 11736), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((11992, 12124), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.account.name', 'self.zone.id', 'self.account.domainid', "self.services['virtual_machine']"], {}), "(self.apiclient, self.account.name, self.zone.id,\n self.account.domainid, self.services['virtual_machine'])\n", (12014, 12124), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((12384, 12447), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (12403, 12447), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((12977, 13231), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ip_address.ipaddress.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=ip_address.ipaddress.id,\n protocol=self.services['natrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['natrule']['publicport'], endport=self.services\n ['natrule']['publicport'])\n", (12996, 13231), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((13343, 13457), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient', 'ip_address.ipaddress.id', 'self.virtual_machine.id', 'self.defaultNetworkId'], {}), '(self.apiclient, ip_address.ipaddress.id, self.\n virtual_machine.id, self.defaultNetworkId)\n', (13363, 13457), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((14029, 14121), 'marvin.lib.base.StaticNATRule.disable', 'StaticNATRule.disable', (['self.apiclient', 'ip_address.ipaddress.id', 'self.virtual_machine.id'], {}), '(self.apiclient, ip_address.ipaddress.id, self.\n virtual_machine.id)\n', (14050, 14121), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((14539, 14564), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (14549, 14564), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((14766, 14830), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (14778, 14830), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((15120, 15215), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (15134, 15215), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((15362, 15447), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['tiny']"], {}), "(cls.apiclient, cls.services['service_offerings']['tiny']\n )\n", (15384, 15447), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((15638, 15842), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.apiclient, cls.services['virtual_machine'],\n templateid=template.id, accountid=cls.account.name, domainid=cls.\n account.domainid, serviceofferingid=cls.service_offering.id)\n", (15659, 15842), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((16536, 16583), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (16553, 16583), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((17496, 17564), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (17516, 17564), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((17833, 17964), 'marvin.lib.base.PublicIpRange.dedicate', 'PublicIpRange.dedicate', (['self.apiclient', 'self.public_ip_range.vlan.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.public_ip_range.vlan.id,\n account=self.account.name, domainid=self.account.domainid)\n', (17855, 17964), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((18220, 18352), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.account.name', 'self.zone.id', 'self.account.domainid', "self.services['virtual_machine']"], {}), "(self.apiclient, self.account.name, self.zone.id,\n self.account.domainid, self.services['virtual_machine'])\n", (18242, 18352), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((18612, 18675), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (18631, 18675), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((19256, 19510), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ip_address.ipaddress.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=ip_address.ipaddress.id,\n protocol=self.services['natrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['natrule']['publicport'], endport=self.services\n ['natrule']['publicport'])\n", (19275, 19510), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((19656, 19748), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (19668, 19748), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((24159, 24184), 'marvin.lib.common.get_domain', 'get_domain', (['cls.apiclient'], {}), '(cls.apiclient)\n', (24169, 24184), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((24386, 24450), 'marvin.lib.common.get_template', 'get_template', (['cls.apiclient', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.apiclient, cls.zone.id, cls.services['ostype'])\n", (24398, 24450), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((24740, 24835), 'marvin.lib.base.Account.create', 'Account.create', (['cls.apiclient', "cls.services['account']"], {'admin': '(True)', 'domainid': 'cls.domain.id'}), "(cls.apiclient, cls.services['account'], admin=True, domainid\n =cls.domain.id)\n", (24754, 24835), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((24982, 25067), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.apiclient', "cls.services['service_offerings']['tiny']"], {}), "(cls.apiclient, cls.services['service_offerings']['tiny']\n )\n", (25004, 25067), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((25258, 25462), 'marvin.lib.base.VirtualMachine.create', 'VirtualMachine.create', (['cls.apiclient', "cls.services['virtual_machine']"], {'templateid': 'template.id', 'accountid': 'cls.account.name', 'domainid': 'cls.account.domainid', 'serviceofferingid': 'cls.service_offering.id'}), "(cls.apiclient, cls.services['virtual_machine'],\n templateid=template.id, accountid=cls.account.name, domainid=cls.\n account.domainid, serviceofferingid=cls.service_offering.id)\n", (25279, 25462), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((26157, 26204), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (26174, 26204), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((27192, 27260), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (27212, 27260), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((27529, 27660), 'marvin.lib.base.PublicIpRange.dedicate', 'PublicIpRange.dedicate', (['self.apiclient', 'self.public_ip_range.vlan.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.public_ip_range.vlan.id,\n account=self.account.name, domainid=self.account.domainid)\n', (27551, 27660), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((27916, 28048), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient', 'self.account.name', 'self.zone.id', 'self.account.domainid', "self.services['virtual_machine']"], {}), "(self.apiclient, self.account.name, self.zone.id,\n self.account.domainid, self.services['virtual_machine'])\n", (27938, 28048), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((28258, 28321), 'marvin.lib.base.VirtualMachine.list', 'VirtualMachine.list', (['self.apiclient'], {'id': 'self.virtual_machine.id'}), '(self.apiclient, id=self.virtual_machine.id)\n', (28277, 28321), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((28867, 29121), 'marvin.lib.base.FireWallRule.create', 'FireWallRule.create', (['self.apiclient'], {'ipaddressid': 'ip_address.ipaddress.id', 'protocol': "self.services['natrule']['protocol']", 'cidrlist': "['0.0.0.0/0']", 'startport': "self.services['natrule']['publicport']", 'endport': "self.services['natrule']['publicport']"}), "(self.apiclient, ipaddressid=ip_address.ipaddress.id,\n protocol=self.services['natrule']['protocol'], cidrlist=['0.0.0.0/0'],\n startport=self.services['natrule']['publicport'], endport=self.services\n ['natrule']['publicport'])\n", (28886, 29121), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((29266, 29358), 'marvin.lib.common.list_routers', 'list_routers', (['self.apiclient'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, account=self.account.name, domainid=self.\n account.domainid)\n', (29278, 29358), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((31340, 31368), 'socket.setdefaulttimeout', 'socket.setdefaulttimeout', (['(60)'], {}), '(60)\n', (31364, 31368), False, 'import socket\n'), ((31623, 31649), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (31633, 31649), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((31751, 31816), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (31763, 31816), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((33597, 33669), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (33619, 33669), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((34279, 34376), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (34293, 34376), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((34726, 34791), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (34744, 34791), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((35259, 35428), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=self.account.name, domainid=self.\n account.domainid)\n", (35269, 35428), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((37023, 37169), 'marvin.lib.base.NATRule.create', 'NATRule.create', (['self.apiclient', 'vm', 'services'], {'ipaddressid': 'public_ip.ipaddress.id', 'openfirewall': '(False)', 'networkid': 'network.id', 'vpcid': 'self.vpc.id'}), '(self.apiclient, vm, services, ipaddressid=public_ip.\n ipaddress.id, openfirewall=False, networkid=network.id, vpcid=self.vpc.id)\n', (37037, 37169), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((37637, 37807), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': 'self.vpc.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=self.vpc.id)\n', (37659, 37807), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((41912, 41980), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (41932, 41980), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((42248, 42379), 'marvin.lib.base.PublicIpRange.dedicate', 'PublicIpRange.dedicate', (['self.apiclient', 'self.public_ip_range.vlan.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.public_ip_range.vlan.id,\n account=self.account.name, domainid=self.account.domainid)\n', (42270, 42379), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((42963, 42991), 'socket.setdefaulttimeout', 'socket.setdefaulttimeout', (['(60)'], {}), '(60)\n', (42987, 42991), False, 'import socket\n'), ((43241, 43267), 'marvin.lib.common.get_domain', 'get_domain', (['cls.api_client'], {}), '(cls.api_client)\n', (43251, 43267), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((43369, 43434), 'marvin.lib.common.get_template', 'get_template', (['cls.api_client', 'cls.zone.id', "cls.services['ostype']"], {}), "(cls.api_client, cls.zone.id, cls.services['ostype'])\n", (43381, 43434), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((45215, 45287), 'marvin.lib.base.ServiceOffering.create', 'ServiceOffering.create', (['cls.api_client', "cls.services['service_offering']"], {}), "(cls.api_client, cls.services['service_offering'])\n", (45237, 45287), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((45897, 45994), 'marvin.lib.base.Account.create', 'Account.create', (['self.apiclient', "self.services['account']"], {'admin': '(True)', 'domainid': 'self.domain.id'}), "(self.apiclient, self.services['account'], admin=True,\n domainid=self.domain.id)\n", (45911, 45994), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((46344, 46409), 'marvin.lib.base.VpcOffering.create', 'VpcOffering.create', (['self.apiclient', "self.services['vpc_offering']"], {}), "(self.apiclient, self.services['vpc_offering'])\n", (46362, 46409), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((46877, 47046), 'marvin.lib.base.VPC.create', 'VPC.create', (['self.apiclient', "self.services['vpc']"], {'vpcofferingid': 'self.vpc_off.id', 'zoneid': 'self.zone.id', 'account': 'self.account.name', 'domainid': 'self.account.domainid'}), "(self.apiclient, self.services['vpc'], vpcofferingid=self.vpc_off\n .id, zoneid=self.zone.id, account=self.account.name, domainid=self.\n account.domainid)\n", (46887, 47046), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((48544, 48714), 'marvin.lib.base.PublicIPAddress.create', 'PublicIPAddress.create', (['self.apiclient'], {'accountid': 'self.account.name', 'zoneid': 'self.zone.id', 'domainid': 'self.account.domainid', 'networkid': 'network.id', 'vpcid': 'self.vpc.id'}), '(self.apiclient, accountid=self.account.name, zoneid=\n self.zone.id, domainid=self.account.domainid, networkid=network.id,\n vpcid=self.vpc.id)\n', (48566, 48714), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((53838, 53906), 'marvin.lib.base.PublicIpRange.create', 'PublicIpRange.create', (['self.apiclient', "self.services['publiciprange']"], {}), "(self.apiclient, self.services['publiciprange'])\n", (53858, 53906), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((54174, 54305), 'marvin.lib.base.PublicIpRange.dedicate', 'PublicIpRange.dedicate', (['self.apiclient', 'self.public_ip_range.vlan.id'], {'account': 'self.account.name', 'domainid': 'self.account.domainid'}), '(self.apiclient, self.public_ip_range.vlan.id,\n account=self.account.name, domainid=self.account.domainid)\n', (54196, 54305), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((4671, 4717), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (4688, 4717), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((10439, 10485), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (10456, 10485), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((16351, 16397), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (16368, 16397), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((19946, 20159), 'marvin.lib.utils.get_process_status', 'get_process_status', (['self.apiclient.connection.mgtSvr', '(22)', 'self.apiclient.connection.user', 'self.apiclient.connection.passwd', 'router.linklocalip', '"""ip route list table Table_eth3"""'], {'hypervisor': 'self.hypervisor'}), "(self.apiclient.connection.mgtSvr, 22, self.apiclient.\n connection.user, self.apiclient.connection.passwd, router.linklocalip,\n 'ip route list table Table_eth3', hypervisor=self.hypervisor)\n", (19964, 20159), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((20311, 20355), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'router.hostid'}), '(self.apiclient, id=router.hostid)\n', (20321, 20355), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((22104, 22317), 'marvin.lib.utils.get_process_status', 'get_process_status', (['self.apiclient.connection.mgtSvr', '(22)', 'self.apiclient.connection.user', 'self.apiclient.connection.passwd', 'router.linklocalip', '"""ip route list table Table_eth3"""'], {'hypervisor': 'self.hypervisor'}), "(self.apiclient.connection.mgtSvr, 22, self.apiclient.\n connection.user, self.apiclient.connection.passwd, router.linklocalip,\n 'ip route list table Table_eth3', hypervisor=self.hypervisor)\n", (22122, 22317), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((22469, 22513), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'router.hostid'}), '(self.apiclient, id=router.hostid)\n', (22479, 22513), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((25972, 26018), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.apiclient', 'cls._cleanup'], {}), '(cls.apiclient, cls._cleanup)\n', (25989, 26018), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((29556, 29772), 'marvin.lib.utils.get_process_status', 'get_process_status', (['self.apiclient.connection.mgtSvr', '(22)', 'self.apiclient.connection.user', 'self.apiclient.connection.passwd', 'router.linklocalip', '"""iptables -t filter -L FORWARD -v"""'], {'hypervisor': 'self.hypervisor'}), "(self.apiclient.connection.mgtSvr, 22, self.apiclient.\n connection.user, self.apiclient.connection.passwd, router.linklocalip,\n 'iptables -t filter -L FORWARD -v', hypervisor=self.hypervisor)\n", (29574, 29772), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((29924, 29968), 'marvin.lib.common.list_hosts', 'list_hosts', (['self.apiclient'], {'id': 'router.hostid'}), '(self.apiclient, id=router.hostid)\n', (29934, 29968), False, 'from marvin.lib.common import get_domain, get_zone, get_template, list_hosts, list_routers\n'), ((34009, 34056), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (34026, 34056), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((35773, 35820), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (35790, 35820), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((38504, 38577), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'net_offerring'], {'conservemode': '(False)'}), '(self.apiclient, net_offerring, conservemode=False)\n', (38526, 38577), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((39241, 39500), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'nw_off.id', 'zoneid': 'self.zone.id', 'gateway': 'gateway', 'aclid': 'default_acl.id', 'vpcid': '(vpc.id if vpc else self.vpc.id)'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=nw_off.\n id, zoneid=self.zone.id, gateway=gateway, aclid=default_acl.id, vpcid=\n vpc.id if vpc else self.vpc.id)\n", (39255, 39500), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((45627, 45674), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['cls.api_client', 'cls._cleanup'], {}), '(cls.api_client, cls._cleanup)\n', (45644, 45674), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((47391, 47438), 'marvin.lib.utils.cleanup_resources', 'cleanup_resources', (['self.apiclient', 'self.cleanup'], {}), '(self.apiclient, self.cleanup)\n', (47408, 47438), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((49411, 49484), 'marvin.lib.base.NetworkOffering.create', 'NetworkOffering.create', (['self.apiclient', 'net_offerring'], {'conservemode': '(False)'}), '(self.apiclient, net_offerring, conservemode=False)\n', (49433, 49484), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((50148, 50407), 'marvin.lib.base.Network.create', 'Network.create', (['self.apiclient', "self.services['network']"], {'accountid': 'self.account.name', 'domainid': 'self.account.domainid', 'networkofferingid': 'nw_off.id', 'zoneid': 'self.zone.id', 'gateway': 'gateway', 'aclid': 'default_acl.id', 'vpcid': '(vpc.id if vpc else self.vpc.id)'}), "(self.apiclient, self.services['network'], accountid=self.\n account.name, domainid=self.account.domainid, networkofferingid=nw_off.\n id, zoneid=self.zone.id, gateway=gateway, aclid=default_acl.id, vpcid=\n vpc.id if vpc else self.vpc.id)\n", (50162, 50407), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((52331, 52453), 'marvin.lib.base.StaticNATRule.enable', 'StaticNATRule.enable', (['self.apiclient'], {'ipaddressid': 'public_ip.ipaddress.id', 'virtualmachineid': 'vm.id', 'networkid': 'network.id'}), '(self.apiclient, ipaddressid=public_ip.ipaddress.id,\n virtualmachineid=vm.id, networkid=network.id)\n', (52351, 52453), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((20752, 20873), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', '(22)', 'host.user', 'host.passwd', 'router.linklocalip', '"""ip route list table Table_eth3"""'], {}), "(host.ipaddress, 22, host.user, host.passwd, router.\n linklocalip, 'ip route list table Table_eth3')\n", (20770, 20873), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((22910, 23031), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', '(22)', 'host.user', 'host.passwd', 'router.linklocalip', '"""ip route list table Table_eth3"""'], {}), "(host.ipaddress, 22, host.user, host.passwd, router.\n linklocalip, 'ip route list table Table_eth3')\n", (22928, 23031), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((30365, 30489), 'marvin.lib.utils.get_process_status', 'get_process_status', (['host.ipaddress', '(22)', 'host.user', 'host.passwd', 'router.linklocalip', '"""iptables -t filter -L FORWARD -v"""'], {}), "(host.ipaddress, 22, host.user, host.passwd, router.\n linklocalip, 'iptables -t filter -L FORWARD -v')\n", (30383, 30489), False, 'from marvin.lib.utils import cleanup_resources, get_process_status\n'), ((39150, 39207), 'marvin.lib.base.NetworkACLList.list', 'NetworkACLList.list', (['self.apiclient'], {'name': '"""default_allow"""'}), "(self.apiclient, name='default_allow')\n", (39169, 39207), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n'), ((50057, 50114), 'marvin.lib.base.NetworkACLList.list', 'NetworkACLList.list', (['self.apiclient'], {'name': '"""default_allow"""'}), "(self.apiclient, name='default_allow')\n", (50076, 50114), False, 'from marvin.lib.base import Account, VirtualMachine, ServiceOffering, NATRule, PublicIPAddress, StaticNATRule, FireWallRule, Network, NetworkOffering, LoadBalancerRule, PublicIpRange, Router, VpcOffering, VPC, NetworkACLList, NetworkACL\n')]
"""Some utility functions for working with headline of Markdown. Terminologies - Headline :: The headline entity OR the text of the headline - Content :: The content under the current headline. It stops after encountering a headline with the same or higher level OR EOF. """ # Author: <NAME> <<EMAIL>> import re import sublime try: from .utilities import is_region_void except ValueError: from utilities import is_region_void MATCH_PARENT = 1 # Match headlines at the same or higher level MATCH_CHILD = 2 # Match headlines at the same or lower level MATCH_SILBING = 3 # Only Match headlines at the same level. MATCH_ANY = 4 # Any headlines would be matched. ANY_LEVEL = -1 # level used when MATCH_ANY is used as match type def region_of_content_of_headline_at_point(view, from_point): """Extract the region of the content of under current headline.""" _, level = headline_and_level_at_point(view, from_point) if level == None: return None if is_content_empty_at_point(view, from_point): return None line_num, _ = view.rowcol(from_point) content_line_start_point = view.text_point(line_num + 1, 0) next_headline, _ = find_headline(view, \ content_line_start_point, \ level, \ True, \ MATCH_PARENT) if not is_region_void(next_headline): end_pos = next_headline.a - 1 else: end_pos = view.size() return sublime.Region(content_line_start_point, end_pos) def headline_and_level_at_point(view, from_point, search_above_and_down=False): """Return the current headline and level. If from_point is inside a headline, then return the headline and level. Otherwise depends on the argument it might search above and down. """ line_region = view.line(from_point) line_content = view.substr(line_region) # Update the level in case it's headline.ANY_LEVEL level = _extract_level_from_headline(line_content) # Search above and down if level is None and search_above_and_down: # Search above headline_region, _ = find_headline(view,\ from_point,\ ANY_LEVEL, False, skip_folded=True) if not is_region_void(headline_region): line_content, level = headline_and_level_at_point(view,\ headline_region.a) # Search down if level is None: headline_region, _ = find_headline(view,\ from_point,\ ANY_LEVEL, True, skip_folded=True) if not is_region_void(headline_region): line_content, level = headline_and_level_at_point(view, headline_region.a) return line_content, level def _extract_level_from_headline(headline): """Extract the level of headline, None if not found. """ re_string = _get_re_string(ANY_LEVEL, MATCH_ANY) match = re.match(re_string, headline) if match: return len(match.group(1)) else: return None def is_content_empty_at_point(view, from_point): """Check if the content under the current headline is empty. For implementation, check if next line is a headline a the same or higher level. """ _, level = headline_and_level_at_point(view, from_point) if level is None: raise ValueError("from_point must be inside a valid headline.") line_num, _ = view.rowcol(from_point) next_line_region = view.line(view.text_point(line_num + 1, 0)) next_line_content = view.substr(next_line_region) next_line_level = _extract_level_from_headline(next_line_content) # Note that EOF works too in this case. if next_line_level and next_line_level <= level: return True else: return False def find_headline(view, from_point, level, forward=True, \ match_type=MATCH_ANY, skip_headline_at_point=False, \ skip_folded=False): """Return the region of the next headline or EOF. Parameters ---------- view: sublime.view from_point: int From which to find. level: int The headline level to match. forward: boolean Search forward or backward match_type: int MATCH_SILBING, MATCH_PARENT, MATCH_CHILD or MATCH_ANY. skip_headline_at_point: boolean When searching whether skip the headline at point skip_folded: boolean Whether to skip the folded region Returns ------- match_region: int Matched region, or None if not found. match_level: int The level of matched headline, or None if not found. """ if skip_headline_at_point: # Move the point to the next line if we are # current in a headline already. from_point = _get_new_point_if_already_in_headline(view, from_point, forward) re_string = _get_re_string(level, match_type) if forward: match_region = view.find(re_string, from_point) else: all_match_regions = view.find_all(re_string) match_region = _nearest_region_among_matches_from_point(view, \ all_match_regions, \ from_point, \ False, \ skip_folded) if skip_folded: while (_is_region_folded(match_region, view)): from_point = match_region.b match_region = view.find(re_string, from_point) if not is_region_void(match_region): if not is_scope_headline(view, match_region.a): return find_headline(view, match_region.a, level, forward, \ match_type, True, skip_folded) else: ## Extract the level of matched headlines according to the region headline = view.substr(match_region) match_level = _extract_level_from_headline(headline) else: match_level = None return (match_region, match_level) def _get_re_string(level, match_type=MATCH_ANY): """Get regular expression string according to match type. Return regular expression string, rather than compiled string. Since sublime's view.find function needs string. Parameters ---------- match_type: int MATCH_SILBING, MATCH_PARENT, MATCH_CHILD or ANY_LEVEL. """ if match_type == MATCH_ANY: re_string = r'^(#+)\s.*' else: try: if match_type == MATCH_PARENT: re_string = r'^(#{1,%d})\s.*' % level elif match_type == MATCH_CHILD: re_string = r'^(#{%d,})\s.*' % level elif match_type == MATCH_SILBING: re_string = r'^(#{%d,%d})\s.*' % (level, level) except ValueError: print("match_type has to be specified if level isn't ANY_LEVE") return re_string def _get_new_point_if_already_in_headline(view, from_point, forward=True): line_content = view.substr(view.line(from_point)) if _extract_level_from_headline(line_content): line_num, _ = view.rowcol(from_point) if forward: return view.text_point(line_num + 1, 0) else: return view.text_point(line_num, 0) - 1 else: return from_point def is_scope_headline(view, from_point): return view.score_selector(from_point, "markup.heading") > 0 or \ view.score_selector(from_point, "meta.block-level.markdown") > 0 def _nearest_region_among_matches_from_point(view, all_match_regions, \ from_point, forward=False, skip_folded=True): """Find the nearest matched region among all matched regions. None if not found. """ nearest_region = None for r in all_match_regions: if not forward and r.b <= from_point and \ (not nearest_region or r.a > nearest_region.a): candidate = r elif forward and r.a >= from_point and \ (not nearest_region or r.b < nearest_region.b): candidate = r else: continue if skip_folded and not _is_region_folded(candidate, view): nearest_region = candidate return nearest_region def _is_region_folded(region, view): for i in view.folded_regions(): if i.contains(region): return True return False
[ "utilities.is_region_void", "sublime.Region", "re.match" ]
[((1554, 1603), 'sublime.Region', 'sublime.Region', (['content_line_start_point', 'end_pos'], {}), '(content_line_start_point, end_pos)\n', (1568, 1603), False, 'import sublime\n'), ((3340, 3369), 're.match', 're.match', (['re_string', 'headline'], {}), '(re_string, headline)\n', (3348, 3369), False, 'import re\n'), ((1434, 1463), 'utilities.is_region_void', 'is_region_void', (['next_headline'], {}), '(next_headline)\n', (1448, 1463), False, 'from utilities import is_region_void\n'), ((6101, 6129), 'utilities.is_region_void', 'is_region_void', (['match_region'], {}), '(match_region)\n', (6115, 6129), False, 'from utilities import is_region_void\n'), ((2467, 2498), 'utilities.is_region_void', 'is_region_void', (['headline_region'], {}), '(headline_region)\n', (2481, 2498), False, 'from utilities import is_region_void\n'), ((3007, 3038), 'utilities.is_region_void', 'is_region_void', (['headline_region'], {}), '(headline_region)\n', (3021, 3038), False, 'from utilities import is_region_void\n')]
import re text = input() pattern = r"\+359( |-)2\1\d{3}\1\d{4}\b" number = [object.group() for object in re.finditer(pattern, text)] print(', '.join(number))
[ "re.finditer" ]
[((106, 132), 're.finditer', 're.finditer', (['pattern', 'text'], {}), '(pattern, text)\n', (117, 132), False, 'import re\n')]
from twisted.web.error import Error from twisted.web.http import NOT_ALLOWED from twisted.web.static import File class NoListingFile(File): """ Serve files, but disallow directory listing. """ def directoryListing(self): # type: () -> None raise Error(NOT_ALLOWED, b"Not allowed")
[ "twisted.web.error.Error" ]
[((281, 315), 'twisted.web.error.Error', 'Error', (['NOT_ALLOWED', "b'Not allowed'"], {}), "(NOT_ALLOWED, b'Not allowed')\n", (286, 315), False, 'from twisted.web.error import Error\n')]
import inspect import logging import os from itertools import product from multiprocessing import JoinableQueue, Process from queue import Empty import numpy as np import torch import torch.nn.functional as F from pandas import DataFrame from fonduer.learning.models.marginal import Marginal logger = logging.getLogger(__name__) # ########################################################### # # General Learning Utilities # ########################################################### def save_marginals(session, X, marginals, training=True): """Save marginal probabilities for a set of Candidates to db. :param X: A list of arbitrary objects with candidate ids accessible via a .id attrib :param marginals: A dense M x K matrix of marginal probabilities, where K is the cardinality of the candidates, OR a M-dim list/array if K=2. :param training: If True, these are training marginals / labels; else they are saved as end model predictions. Note: The marginals for k=0 are not stored, only for k = 1,...,K """ logger = logging.getLogger(__name__) # Make sure that we are working with a numpy array try: shape = marginals.shape except Exception as e: marginals = np.array(marginals) shape = marginals.shape # Handle binary input as M x 1-dim array; assume elements represent # poksitive (k=1) class values if len(shape) == 1: marginals = np.vstack([1 - marginals, marginals]).T # Only add values for classes k=1,...,K marginal_tuples = [] for i in range(shape[0]): for k in range(1, shape[1] if len(shape) > 1 else 2): if marginals[i, k] > 0: marginal_tuples.append((i, k, marginals[i, k])) # NOTE: This will delete all existing marginals of type `training` session.query(Marginal).filter(Marginal.training == training).delete( synchronize_session="fetch" ) # Prepare bulk INSERT query q = Marginal.__table__.insert() # Prepare values insert_vals = [] for i, k, p in marginal_tuples: cid = X[i].id insert_vals.append( { "candidate_id": cid, "training": training, "value": k, # We cast p in case its a numpy type, which psycopg2 does not handle "probability": float(p), } ) # Execute update session.execute(q, insert_vals) session.commit() logger.info("Saved {%d} marginals".format(len(marginals))) def reshape_marginals(marginals): """Returns correctly shaped marginals as np array""" # Make sure training marginals are a numpy array first try: shape = marginals.shape except Exception as e: marginals = np.array(marginals) shape = marginals.shape # Set cardinality + marginals in proper format for binary v. categorical if len(shape) != 1: # If k = 2, make sure is M-dim array if shape[1] == 2: marginals = marginals[:, 1].reshape(-1) return marginals class LabelBalancer(object): def __init__(self, y): """Utility class to rebalance training labels For example, to get the indices of a training set with labels y and around 90 percent negative examples, LabelBalancer(y).get_train_idxs(rebalance=0.1) """ self.y = np.ravel(y) def _get_pos(self, split): return np.where(self.y > (split + 1e-6))[0] def _get_neg(self, split): return np.where(self.y < (split - 1e-6))[0] def _try_frac(self, m, n, pn): # Return (a, b) s.t. a <= m, b <= n # and b / a is as close to pn as possible r = int(round(float(pn * m) / (1.0 - pn))) s = int(round(float((1.0 - pn) * n) / pn)) return (m, r) if r <= n else ((s, n) if s <= m else (m, n)) def _get_counts(self, nneg, npos, frac_pos): if frac_pos > 0.5: return self._try_frac(nneg, npos, frac_pos) else: return self._try_frac(npos, nneg, 1.0 - frac_pos)[::-1] def get_train_idxs(self, rebalance=False, split=0.5, rand_state=None): """Get training indices based on @y @rebalance: bool or fraction of positive examples desired If True, default fraction is 0.5. If False no balancing. @split: Split point for positive and negative classes """ rs = np.random if rand_state is None else rand_state pos, neg = self._get_pos(split), self._get_neg(split) if rebalance: if len(pos) == 0: raise ValueError("No positive labels.") if len(neg) == 0: raise ValueError("No negative labels.") p = 0.5 if rebalance else rebalance n_neg, n_pos = self._get_counts(len(neg), len(pos), p) pos = rs.choice(pos, size=n_pos, replace=False) neg = rs.choice(neg, size=n_neg, replace=False) idxs = np.concatenate([pos, neg]) rs.shuffle(idxs) return idxs # ########################################################## # # Advanced Scoring Classes # ########################################################## class Scorer(object): """Abstract type for scorers""" def __init__(self, test_candidates, test_labels, gold_candidate_set=None): """ :param test_candidates: A *list of Candidates* corresponding to test_labels :param test_labels: A *csrLabelMatrix* of ground truth labels for the test candidates :param gold_candidate_set: (optional) A *CandidateSet* containing the full set of gold labeled candidates """ self.test_candidates = test_candidates self.test_labels = test_labels self.gold_candidate_set = gold_candidate_set def _get_cardinality(self, marginals): """Get the cardinality based on the marginals returned by the model.""" if len(marginals.shape) == 1 or marginals.shape[1] < 3: cardinality = 2 else: cardinality = marginals.shape[1] return cardinality def score(self, test_marginals, **kwargs): cardinality = self._get_cardinality(test_marginals) if cardinality == 2: return self._score_binary(test_marginals, **kwargs) else: return self._score_categorical(test_marginals, **kwargs) def _score_binary( self, test_marginals, train_marginals=None, b=0.5, set_unlabeled_as_neg=True, display=True, ): raise NotImplementedError() def _score_categorical(self, test_marginals, train_marginals=None, display=True): raise NotImplementedError() def summary_score(self, test_marginals, **kwargs): """Return the F1 score (for binary) or accuracy (for categorical).""" raise NotImplementedError() class MentionScorer(Scorer): """Scorer for mention level assessment""" def _score_binary( self, test_marginals, train_marginals=None, b=0.5, set_unlabeled_as_neg=True, set_at_thresh_as_neg=True, display=True, **kwargs ): """ Return scoring metric for the provided marginals, as well as candidates in error buckets. :param test_marginals: array of marginals for test candidates :param train_marginals (optional): array of marginals for training candidates :param b: threshold for labeling :param set_unlabeled_as_neg: set test labels at the decision threshold of b as negative labels :param set_at_b_as_neg: set marginals at the decision threshold exactly as negative predictions :param display: show calibration plots? """ test_label_array = [] tp = set() fp = set() tn = set() fn = set() for i, candidate in enumerate(self.test_candidates): # Handle either a LabelMatrix or else assume test_labels array is in # correct order i.e. same order as test_candidates try: test_label_index = self.test_labels.get_row_index(candidate) test_label = self.test_labels[test_label_index, 0] except AttributeError: test_label = self.test_labels[i] # Set unlabeled examples to -1 by default if test_label == 0 and set_unlabeled_as_neg: test_label = -1 # Bucket the candidates for error analysis test_label_array.append(test_label) if test_label != 0: if test_marginals[i] > b: if test_label == 1: tp.add(candidate) else: fp.add(candidate) elif test_marginals[i] < b or set_at_thresh_as_neg: if test_label == -1: tn.add(candidate) else: fn.add(candidate) if display: # Calculate scores unadjusted for TPs not in our candidate set print_scores( len(tp), len(fp), len(tn), len(fn), title="Scores (Un-adjusted)" ) # If gold candidate set is provided calculate recall-adjusted scores if self.gold_candidate_set is not None: gold_fn = [ c for c in self.gold_candidate_set if c not in self.test_candidates ] logger.info("\n") print_scores( len(tp), len(fp), len(tn), len(fn) + len(gold_fn), title="Corpus Recall-adjusted Scores", ) # If training and test marginals provided print calibration plots if train_marginals is not None and test_marginals is not None: raise NotImplementedError("Invalid code here.") return tp, fp, tn, fn def _score_categorical( self, test_marginals, train_marginals=None, display=True, **kwargs ): """ Return scoring metric for the provided marginals, as well as candidates in error buckets. :param test_marginals: array of marginals for test candidates :param train_marginals (optional): array of marginals for training candidates :param display: show calibration plots? """ test_label_array = [] correct = set() incorrect = set() # Get predictions test_pred = test_marginals.argmax(axis=1) + 1 # Bucket the candidates for error analysis for i, candidate in enumerate(self.test_candidates): # Handle either a LabelMatrix or else assume test_labels array is in # correct order i.e. same order as test_candidates try: test_label_index = self.test_labels.get_row_index(candidate) test_label = self.test_labels[test_label_index, 0] except AttributeError: test_label = self.test_labels[i] test_label_array.append(test_label) if test_label != 0: if test_pred[i] == test_label: correct.add(candidate) else: incorrect.add(candidate) if display: nc, ni = len(correct), len(incorrect) logger.info("Accuracy: {}".format(nc / float(nc + ni))) # If gold candidate set is provided calculate recall-adjusted scores if self.gold_candidate_set is not None: gold_missed = [ c for c in self.gold_candidate_set if c not in self.test_candidates ] logger.info( "Coverage: {}".format((nc + ni) / (nc + ni + len(gold_missed))) ) return correct, incorrect def summary_score(self, test_marginals, **kwargs): """ Return the F1 score (for binary) or accuracy (for categorical). Also return the label as second argument. """ error_sets = self.score(test_marginals, display=False, **kwargs) if len(error_sets) == 4: _, _, f1 = binary_scores_from_counts(*map(len, error_sets)) return f1, "F1 Score" else: nc, ninc = map(len, error_sets) return nc / float(nc + ninc), "Accuracy" def binary_scores_from_counts(ntp, nfp, ntn, nfn): """Precision, recall, and F1 scores from counts of TP, FP, TN, FN. Example usage:: p, r, f1 = binary_scores_from_counts(*map(len, error_sets)) """ prec = ntp / float(ntp + nfp) if ntp + nfp > 0 else 0.0 rec = ntp / float(ntp + nfn) if ntp + nfn > 0 else 0.0 f1 = (2 * prec * rec) / (prec + rec) if prec + rec > 0 else 0.0 return prec, rec, f1 def print_scores(ntp, nfp, ntn, nfn, title="Scores"): prec, rec, f1 = binary_scores_from_counts(ntp, nfp, ntn, nfn) pos_acc = ntp / float(ntp + nfn) if ntp + nfn > 0 else 0.0 neg_acc = ntn / float(ntn + nfp) if ntn + nfp > 0 else 0.0 logger.info("========================================") logger.info(title) logger.info("========================================") logger.info("Pos. class accuracy: {:.3}".format(pos_acc)) logger.info("Neg. class accuracy: {:.3}".format(neg_acc)) logger.info("Precision {:.3}".format(prec)) logger.info("Recall {:.3}".format(rec)) logger.info("F1 {:.3}".format(f1)) logger.info("----------------------------------------") logger.info("TP: {} | FP: {} | TN: {} | FN: {}".format(ntp, nfp, ntn, nfn)) logger.info("========================================\n") # ########################################################## # # Grid search # ########################################################## class GridSearch(object): """ A class for running a hyperparameter grid search. :param model_class: The model class being trained :param parameter_dict: A dictionary of (hyperparameter name, list of values) pairs. Note that the hyperparameter name must correspond to a keyword argument in the `model_class.train` method. :param X_train: The training datapoints :param Y_train: If applicable, the training labels / marginals :param model_class_params: Keyword arguments to pass into model_class construction. Note that a new model is constructed for each new combination of hyperparameters. :param model_hyperparams: Hyperparameters for the model- all must be keyword arguments to the `model_class.train` method. Any that are included in the grid search will be overwritten. :param save_dir: Note that checkpoints will be saved in save_dir/grid_search """ def __init__( self, model_class, parameter_dict, X_train, Y_train=None, model_class_params={}, model_hyperparams={}, save_dir="checkpoints", ): self.model_class = model_class self.parameter_dict = parameter_dict self.param_names = list(parameter_dict) self.X_train = X_train self.Y_train = Y_train self.model_class_params = model_class_params self.model_hyperparams = model_hyperparams self.save_dir = os.path.join(save_dir, "grid_search") def search_space(self): return product(*[self.parameter_dict[pn] for pn in self.param_names]) def fit( self, X_valid, Y_valid, b=0.5, beta=1, set_unlabeled_as_neg=True, n_threads=1, eval_batch_size=None, ): """ Runs grid search, constructing a new instance of model_class for each hyperparameter combination, training on (self.X_train, self.Y_train), and validating on (X_valid, Y_valid). Selects the best model according to F1 score (binary) or accuracy (categorical). :param b: Scoring decision threshold (binary) :param beta: F_beta score to select model by (binary) :param set_unlabeled_as_neg: Set labels = 0 -> -1 (binary) :param n_threads: Parallelism to use for the grid search :param eval_batch_size: The batch_size for model evaluation """ if n_threads > 1: opt_model, run_stats = self._fit_mt( X_valid, Y_valid, b=b, beta=beta, set_unlabeled_as_neg=set_unlabeled_as_neg, n_threads=n_threads, eval_batch_size=eval_batch_size, ) else: opt_model, run_stats = self._fit_st( X_valid, Y_valid, b=b, beta=beta, set_unlabeled_as_neg=set_unlabeled_as_neg, eval_batch_size=eval_batch_size, ) return opt_model, run_stats def _fit_st( self, X_valid, Y_valid, b=0.5, beta=1, set_unlabeled_as_neg=True, eval_batch_size=None, ): """Single-threaded implementation of `GridSearch.fit`.""" # Iterate over the param values run_stats = [] run_score_opt = -1.0 for k, param_vals in enumerate(self.search_space()): hps = self.model_hyperparams.copy() # Initiate the model from scratch each time # Some models may have seed set in the init procedure model = self.model_class(**self.model_class_params) model_name = "{0}_{1}".format(model.name, k) # Set the new hyperparam configuration to test for pn, pv in zip(self.param_names, param_vals): hps[pn] = pv logger.info("=" * 60) NUMTYPES = float, int, np.float64 logger.info( "[%d] Testing %s" % ( k + 1, ", ".join( [ "%s = %s" % (pn, ("%0.2e" % pv) if isinstance(pv, NUMTYPES) else pv) for pn, pv in zip(self.param_names, param_vals) ] ), ) ) logger.info("=" * 60) # Train the model train_args = [self.X_train] if self.Y_train is not None: train_args.append(self.Y_train) # Pass in the dev set to the train method if applicable, for dev set # score printing, best-score checkpointing # Note: Need to set the save directory since passing in # (X_dev, Y_dev) will by default trigger checkpoint saving try: model.train( *train_args, X_dev=X_valid, Y_dev=Y_valid, save_dir=self.save_dir, **hps ) except Exception as e: model.train(*train_args, **hps) # Test the model run_scores = model.score( X_valid, Y_valid, b=b, beta=beta, set_unlabeled_as_neg=set_unlabeled_as_neg, batch_size=eval_batch_size, ) if model.cardinality > 2: run_score, run_score_label = run_scores, "Accuracy" run_scores = [run_score] else: run_score = run_scores[-1] run_score_label = "F-{0} Score".format(beta) # Add scores to running stats, print, and set as optimal if best logger.info("[{0}] {1}: {2}".format(model.name, run_score_label, run_score)) run_stats.append(list(param_vals) + list(run_scores)) if run_score > run_score_opt or k == 0: model.save(model_name=model_name, save_dir=self.save_dir) # Also save a separate file for easier access model.save( model_name="{0}_best".format(model.name), save_dir=self.save_dir ) opt_model_name = model_name run_score_opt = run_score # Set optimal parameter in the learner model opt_model = self.model_class(**self.model_class_params) opt_model.load(opt_model_name, save_dir=self.save_dir) # Return optimal model & DataFrame of scores f_score = "F-{0}".format(beta) run_score_labels = ( ["Acc."] if opt_model.cardinality > 2 else ["Prec.", "Rec.", f_score] ) sort_by = "Acc." if opt_model.cardinality > 2 else f_score self.results = DataFrame.from_records( run_stats, columns=self.param_names + run_score_labels ).sort_values(by=sort_by, ascending=False) return opt_model, self.results def _fit_mt( self, X_valid, Y_valid, b=0.5, beta=1, set_unlabeled_as_neg=True, n_threads=2, eval_batch_size=None, ): """Multi-threaded implementation of `GridSearch.fit`.""" # First do a preprocessing pass over the data to make sure it is all # non-lazily loaded # TODO: Better way to go about it than this!! logger.info("Loading data...") model = self.model_class(**self.model_class_params) model._preprocess_data(self.X_train) model._preprocess_data(X_valid) # Create queue of hyperparameters to test logger.info("Launching jobs...") params_queue = JoinableQueue() param_val_sets = [] for k, param_vals in enumerate(self.search_space()): param_val_sets.append(param_vals) hps = self.model_hyperparams.copy() for pn, pv in zip(self.param_names, param_vals): hps[pn] = pv params_queue.put((k, hps)) # Create a queue to store output results scores_queue = JoinableQueue() # Start UDF Processes ps = [] for i in range(n_threads): p = ModelTester( self.model_class, self.model_class_params, params_queue, scores_queue, self.X_train, X_valid, Y_valid, Y_train=self.Y_train, b=b, save_dir=self.save_dir, set_unlabeled_as_neg=set_unlabeled_as_neg, eval_batch_size=eval_batch_size, ) p.start() ps.append(p) # Collect scores run_stats = [] while any([p.is_alive() for p in ps]): while True: try: scores = scores_queue.get(True, QUEUE_TIMEOUT) k = scores[0] param_vals = param_val_sets[k] run_stats.append([k] + list(param_vals) + list(scores[1:])) logger.info("Model {0} Done; score: {1}".format(k, scores[-1])) scores_queue.task_done() except Empty: break # Terminate the processes for p in ps: p.terminate() # Load best model; first element in each row of run_stats is the model # index, last one is the score to sort by # Note: the models may be returned out of order! i_opt = np.argmax([s[-1] for s in run_stats]) k_opt = run_stats[i_opt][0] model = self.model_class(**self.model_class_params) model.load("{0}_{1}".format(model.name, k_opt), save_dir=self.save_dir) # Also save the best model as separate file model.save(model_name="{0}_best".format(model.name), save_dir=self.save_dir) # Return model and DataFrame of scores # Test for categorical vs. binary in hack-ey way for now... f_score = "F-{0}".format(beta) categorical = len(scores) == 2 labels = ["Acc."] if categorical else ["Prec.", "Rec.", f_score] sort_by = "Acc." if categorical else f_score self.results = DataFrame.from_records( run_stats, columns=["Model"] + self.param_names + labels ).sort_values(by=sort_by, ascending=False) return model, self.results QUEUE_TIMEOUT = 3 class ModelTester(Process): def __init__( self, model_class, model_class_params, params_queue, scores_queue, X_train, X_valid, Y_valid, Y_train=None, b=0.5, beta=1, set_unlabeled_as_neg=True, save_dir="checkpoints", eval_batch_size=None, ): Process.__init__(self) self.model_class = model_class self.model_class_params = model_class_params self.params_queue = params_queue self.scores_queue = scores_queue self.X_train = X_train self.Y_train = Y_train self.X_valid = X_valid self.Y_valid = Y_valid self.scorer_params = { "b": b, "beta": beta, "set_unlabeled_as_neg": set_unlabeled_as_neg, "batch_size": eval_batch_size, } self.save_dir = save_dir def run(self): while True: # Get a new configuration from the queue try: k, hps = self.params_queue.get(True, QUEUE_TIMEOUT) # Initiate the model from scratch each time # Some models may have seed set in the init procedure model = self.model_class(**self.model_class_params) model_name = "{0}_{1}".format(model.name, k) # Pass in the dev set to the train method if applicable, for dev # set score printing, best-score checkpointing if "X_dev" in inspect.getargspec(model.train): hps["X_dev"] = self.X_valid hps["Y_dev"] = self.Y_valid # Train model with given hyperparameters if self.Y_train is not None: model.train(self.X_train, self.Y_train, **hps) else: model.train(self.X_train, **hps) # Save the model # NOTE: Currently, we have to save every model because we are # testing asynchronously. This is obviously memory inefficient, # although probably not that much of a problem in practice... model.save(model_name=model_name, save_dir=self.save_dir) # Test the model run_scores = model.score( self.X_valid, self.Y_valid, **self.scorer_params ) run_scores = [run_scores] if model.cardinality > 2 else list(run_scores) # Append score to out queue self.scores_queue.put([k] + run_scores, True, QUEUE_TIMEOUT) except Empty: break class RandomSearch(GridSearch): """ A GridSearch over a random subsample of the hyperparameter search space. :param seed: A seed for the GridSearch instance """ def __init__( self, model_class, parameter_dict, X_train, Y_train=None, n=10, model_class_params={}, model_hyperparams={}, seed=123, save_dir="checkpoints", ): """Search a random sample of size n from a parameter grid""" self.rand_state = np.random.RandomState() self.rand_state.seed(seed) self.n = n super(RandomSearch, self).__init__( model_class, parameter_dict, X_train, Y_train=Y_train, model_class_params=model_class_params, model_hyperparams=model_hyperparams, save_dir=save_dir, ) def search_space(self): return list( zip( *[ self.rand_state.choice(self.parameter_dict[pn], self.n) for pn in self.param_names ] ) ) # ########################################################## # # Loss functions # ########################################################## def SoftCrossEntropyLoss(input, target): """ Calculate the CrossEntropyLoss with soft targets :param input: prediction logicts :param target: target probabilities """ total_loss = torch.tensor(0.0) for i in range(input.size(1)): cls_idx = torch.full((input.size(0),), i, dtype=torch.long) loss = F.cross_entropy(input, cls_idx, reduce=False) total_loss += target[:, i].dot(loss) return total_loss / input.shape[0]
[ "numpy.concatenate", "numpy.ravel", "numpy.argmax", "torch.nn.functional.cross_entropy", "logging.getLogger", "numpy.random.RandomState", "multiprocessing.Process.__init__", "numpy.where", "numpy.array", "inspect.getargspec", "pandas.DataFrame.from_records", "itertools.product", "numpy.vstack", "multiprocessing.JoinableQueue", "fonduer.learning.models.marginal.Marginal.__table__.insert", "os.path.join", "torch.tensor" ]
[((304, 331), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (321, 331), False, 'import logging\n'), ((1080, 1107), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1097, 1107), False, 'import logging\n'), ((1986, 2013), 'fonduer.learning.models.marginal.Marginal.__table__.insert', 'Marginal.__table__.insert', ([], {}), '()\n', (2011, 2013), False, 'from fonduer.learning.models.marginal import Marginal\n'), ((28785, 28802), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (28797, 28802), False, 'import torch\n'), ((3411, 3422), 'numpy.ravel', 'np.ravel', (['y'], {}), '(y)\n', (3419, 3422), True, 'import numpy as np\n'), ((5022, 5048), 'numpy.concatenate', 'np.concatenate', (['[pos, neg]'], {}), '([pos, neg])\n', (5036, 5048), True, 'import numpy as np\n'), ((15552, 15589), 'os.path.join', 'os.path.join', (['save_dir', '"""grid_search"""'], {}), "(save_dir, 'grid_search')\n", (15564, 15589), False, 'import os\n'), ((15634, 15696), 'itertools.product', 'product', (['*[self.parameter_dict[pn] for pn in self.param_names]'], {}), '(*[self.parameter_dict[pn] for pn in self.param_names])\n', (15641, 15696), False, 'from itertools import product\n'), ((21880, 21895), 'multiprocessing.JoinableQueue', 'JoinableQueue', ([], {}), '()\n', (21893, 21895), False, 'from multiprocessing import JoinableQueue, Process\n'), ((22281, 22296), 'multiprocessing.JoinableQueue', 'JoinableQueue', ([], {}), '()\n', (22294, 22296), False, 'from multiprocessing import JoinableQueue, Process\n'), ((23734, 23771), 'numpy.argmax', 'np.argmax', (['[s[-1] for s in run_stats]'], {}), '([s[-1] for s in run_stats])\n', (23743, 23771), True, 'import numpy as np\n'), ((24999, 25021), 'multiprocessing.Process.__init__', 'Process.__init__', (['self'], {}), '(self)\n', (25015, 25021), False, 'from multiprocessing import JoinableQueue, Process\n'), ((27818, 27841), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (27839, 27841), True, 'import numpy as np\n'), ((28921, 28966), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['input', 'cls_idx'], {'reduce': '(False)'}), '(input, cls_idx, reduce=False)\n', (28936, 28966), True, 'import torch.nn.functional as F\n'), ((1251, 1270), 'numpy.array', 'np.array', (['marginals'], {}), '(marginals)\n', (1259, 1270), True, 'import numpy as np\n'), ((1455, 1492), 'numpy.vstack', 'np.vstack', (['[1 - marginals, marginals]'], {}), '([1 - marginals, marginals])\n', (1464, 1492), True, 'import numpy as np\n'), ((2792, 2811), 'numpy.array', 'np.array', (['marginals'], {}), '(marginals)\n', (2800, 2811), True, 'import numpy as np\n'), ((3470, 3502), 'numpy.where', 'np.where', (['(self.y > split + 1e-06)'], {}), '(self.y > split + 1e-06)\n', (3478, 3502), True, 'import numpy as np\n'), ((3554, 3586), 'numpy.where', 'np.where', (['(self.y < split - 1e-06)'], {}), '(self.y < split - 1e-06)\n', (3562, 3586), True, 'import numpy as np\n'), ((20986, 21064), 'pandas.DataFrame.from_records', 'DataFrame.from_records', (['run_stats'], {'columns': '(self.param_names + run_score_labels)'}), '(run_stats, columns=self.param_names + run_score_labels)\n', (21008, 21064), False, 'from pandas import DataFrame\n'), ((24429, 24514), 'pandas.DataFrame.from_records', 'DataFrame.from_records', (['run_stats'], {'columns': "(['Model'] + self.param_names + labels)"}), "(run_stats, columns=['Model'] + self.param_names + labels\n )\n", (24451, 24514), False, 'from pandas import DataFrame\n'), ((26154, 26185), 'inspect.getargspec', 'inspect.getargspec', (['model.train'], {}), '(model.train)\n', (26172, 26185), False, 'import inspect\n')]
#!/usr/bin/env python """A QR and BWM Find SCU application. For sending Query/Retrieve (QR) and Basic Worklist Modality (BWM) C-FIND requests to a QR/BWM - Find SCP. """ import argparse import sys from pydicom.dataset import Dataset from pydicom.uid import ( ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian, generate_uid, ) from pynetdicom import ( AE, QueryRetrievePresentationContexts, BasicWorklistManagementPresentationContexts, PYNETDICOM_UID_PREFIX, PYNETDICOM_IMPLEMENTATION_UID, PYNETDICOM_IMPLEMENTATION_VERSION, ) from pynetdicom.apps.common import create_dataset, setup_logging from pynetdicom._globals import DEFAULT_MAX_LENGTH from pynetdicom.pdu_primitives import SOPClassExtendedNegotiation from pynetdicom.sop_class import ( ModalityWorklistInformationFind, PatientRootQueryRetrieveInformationModelFind, StudyRootQueryRetrieveInformationModelFind, PatientStudyOnlyQueryRetrieveInformationModelFind, ) __version__ = "0.2.0" def _setup_argparser(): """Setup the command line arguments""" # Description parser = argparse.ArgumentParser( description=( "The findscu application implements a Service Class User " "(SCU) for the Query/Retrieve (QR) and Basic Worklist Management " "(BWM) Service Classes. findscu only supports query functionality " "using the C-FIND message. It sends query keys to an SCP and " "waits for a response. The application can be used to test SCPs " "of the QR and BWM Service Classes." ), usage="findscu [options] addr port", ) # Parameters req_opts = parser.add_argument_group("Parameters") req_opts.add_argument( "addr", help="TCP/IP address or hostname of DICOM peer", type=str ) req_opts.add_argument("port", help="TCP/IP port number of peer", type=int) # General Options gen_opts = parser.add_argument_group("General Options") gen_opts.add_argument( "--version", help="print version information and exit", action="store_true" ) output = gen_opts.add_mutually_exclusive_group() output.add_argument( "-q", "--quiet", help="quiet mode, print no warnings and errors", action="store_const", dest="log_type", const="q", ) output.add_argument( "-v", "--verbose", help="verbose mode, print processing details", action="store_const", dest="log_type", const="v", ) output.add_argument( "-d", "--debug", help="debug mode, print debug information", action="store_const", dest="log_type", const="d", ) gen_opts.add_argument( "-ll", "--log-level", metavar="[l]", help=("use level l for the logger (fatal, error, warn, info, debug, " "trace)"), type=str, choices=["fatal", "error", "warn", "info", "debug", "trace"], ) parser.set_defaults(log_type="v") # Network Options net_opts = parser.add_argument_group("Network Options") net_opts.add_argument( "-aet", "--calling-aet", metavar="[a]etitle", help="set my calling AE title (default: FINDSCU)", type=str, default="FINDSCU", ) net_opts.add_argument( "-aec", "--called-aet", metavar="[a]etitle", help="set called AE title of peer (default: ANY-SCP)", type=str, default="ANY-SCP", ) net_opts.add_argument( "-ta", "--acse-timeout", metavar="[s]econds", help="timeout for ACSE messages (default: 30 s)", type=float, default=30, ) net_opts.add_argument( "-td", "--dimse-timeout", metavar="[s]econds", help="timeout for DIMSE messages (default: 30 s)", type=float, default=30, ) net_opts.add_argument( "-tn", "--network-timeout", metavar="[s]econds", help="timeout for the network (default: 30 s)", type=float, default=30, ) net_opts.add_argument( "-pdu", "--max-pdu", metavar="[n]umber of bytes", help=( f"set max receive pdu to n bytes (0 for unlimited, " f"default: {DEFAULT_MAX_LENGTH})" ), type=int, default=DEFAULT_MAX_LENGTH, ) # Query information model choices qr_group = parser.add_argument_group("Query Information Model Options") qr_model = qr_group.add_mutually_exclusive_group() qr_model.add_argument( "-P", "--patient", help="use patient root information model (default)", action="store_true", ) qr_model.add_argument( "-S", "--study", help="use study root information model", action="store_true" ) qr_model.add_argument( "-O", "--psonly", help="use patient/study only information model", action="store_true", ) qr_model.add_argument( "-W", "--worklist", help="use modality worklist information model", action="store_true", ) qr_query = parser.add_argument_group("Query Options") qr_query.add_argument( "-k", "--keyword", metavar="[k]eyword: (gggg,eeee)=str, keyword=str", help=( "add or override a query element using either an element tag as " "(group,element) or the element's keyword (such as PatientName)" ), type=str, action="append", ) qr_query.add_argument( "-f", "--file", metavar="path to [f]ile", help=( "use a DICOM file as the query dataset, if " "used with -k then the elements will be added to or overwrite " "those present in the file" ), type=str, ) out_opts = parser.add_argument_group("Output Options") out_opts.add_argument( "-w", "--write", help=("write the responses to file as rsp000001.dcm, rsp000002.dcm, ..."), action="store_true", ) ext_neg = parser.add_argument_group("Extended Negotiation Options") ext_neg.add_argument( "--relational-query", help="request the use of relational queries", action="store_true", ) ext_neg.add_argument( "--dt-matching", help="request the use of date-time matching", action="store_true", ) ext_neg.add_argument( "--fuzzy-names", help="request the use of fuzzy semantic matching of person names", action="store_true", ) ext_neg.add_argument( "--timezone-adj", help="request the use of timezone query adjustment", action="store_true", ) ext_neg.add_argument( "--enhanced-conversion", help="request the use of enhanced multi-frame image conversion", action="store_true", ) ns = parser.parse_args() if ns.version: pass elif not bool(ns.file) and not bool(ns.keyword): parser.error("-f and/or -k must be specified") return ns def get_file_meta(assoc, query_model): """Return a Dataset containing sufficient File Meta elements for conformance. """ cx = assoc._get_valid_context(query_model, "", "scu") file_meta = Dataset() file_meta.TransferSyntaxUID = cx.transfer_syntax[0] file_meta.MediaStorageSOPClassUID = query_model file_meta.MediaStorageSOPInstanceUID = generate_uid(prefix=PYNETDICOM_UID_PREFIX) file_meta.ImplementationClassUID = PYNETDICOM_IMPLEMENTATION_UID file_meta.ImplementationVersionName = PYNETDICOM_IMPLEMENTATION_VERSION return file_meta def generate_filename(): """Return a `str` filename for extracted C-FIND responses.""" ii = 1 while True: yield f"rsp{ii:06d}.dcm" ii += 1 def main(args=None): """Run the application.""" if args is not None: sys.argv = args args = _setup_argparser() if args.version: print(f"findscu.py v{__version__}") sys.exit() APP_LOGGER = setup_logging(args, "findscu") APP_LOGGER.debug(f"findscu.py v{__version__}") APP_LOGGER.debug("") # Create query (identifier) dataset try: # If you're looking at this to see how QR Find works then `identifer` # is a pydicom Dataset instance with your query keys, e.g.: # identifier = Dataset() # identifier.QueryRetrieveLevel = 'PATIENT' # identifier.PatientName = '' identifier = create_dataset(args, APP_LOGGER) except Exception as exc: APP_LOGGER.exception(exc) sys.exit(1) # Create application entity # Binding to port 0 lets the OS pick an available port ae = AE(ae_title=args.calling_aet) # Set timeouts ae.acse_timeout = args.acse_timeout ae.dimse_timeout = args.dimse_timeout ae.network_timeout = args.network_timeout # Set the Presentation Contexts we are requesting the Find SCP support ae.requested_contexts = ( QueryRetrievePresentationContexts + BasicWorklistManagementPresentationContexts ) # Query/Retrieve Information Models if args.worklist: query_model = ModalityWorklistInformationFind elif args.study: query_model = StudyRootQueryRetrieveInformationModelFind elif args.psonly: query_model = PatientStudyOnlyQueryRetrieveInformationModelFind else: query_model = PatientRootQueryRetrieveInformationModelFind # Extended Negotiation ext_neg = [] ext_opts = [ args.relational_query, args.dt_matching, args.fuzzy_names, args.timezone_adj, args.enhanced_conversion, ] if not args.worklist and any(ext_opts): app_info = b"" for option in ext_opts: app_info += b"\x01" if option else b"\x00" item = SOPClassExtendedNegotiation() item.sop_class_uid = query_model item.service_class_application_information = app_info ext_neg = [item] elif args.worklist and any([args.fuzzy_names, args.timezone_adj]): app_info = b"\x01\x01" for option in [args.fuzzy_names, args.timezone_adj]: app_info += b"\x01" if option else b"\x00" item = SOPClassExtendedNegotiation() item.sop_class_uid = query_model item.service_class_application_information = app_info ext_neg = [item] # Request association with (QR/BWM) Find SCP assoc = ae.associate( args.addr, args.port, ae_title=args.called_aet, max_pdu=args.max_pdu, ext_neg=ext_neg, ) if assoc.is_established: # Send C-FIND request, `responses` is a generator responses = assoc.send_c_find(identifier, query_model) # Used to generate filenames if args.write used fname = generate_filename() for (status, rsp_identifier) in responses: # If `status.Status` is one of the 'Pending' statuses then # `rsp_identifier` is the C-FIND response's Identifier dataset if status and status.Status in [0xFF00, 0xFF01]: if args.write: rsp_identifier.file_meta = get_file_meta(assoc, query_model) rsp_identifier.save_as(next(fname), write_like_original=False) # Release the association assoc.release() else: sys.exit(1) if __name__ == "__main__": main()
[ "argparse.ArgumentParser", "pydicom.dataset.Dataset", "pynetdicom.apps.common.setup_logging", "pynetdicom.pdu_primitives.SOPClassExtendedNegotiation", "pynetdicom.AE", "pynetdicom.apps.common.create_dataset", "pydicom.uid.generate_uid", "sys.exit" ]
[((1121, 1549), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""The findscu application implements a Service Class User (SCU) for the Query/Retrieve (QR) and Basic Worklist Management (BWM) Service Classes. findscu only supports query functionality using the C-FIND message. It sends query keys to an SCP and waits for a response. The application can be used to test SCPs of the QR and BWM Service Classes."""', 'usage': '"""findscu [options] addr port"""'}), "(description=\n 'The findscu application implements a Service Class User (SCU) for the Query/Retrieve (QR) and Basic Worklist Management (BWM) Service Classes. findscu only supports query functionality using the C-FIND message. It sends query keys to an SCP and waits for a response. The application can be used to test SCPs of the QR and BWM Service Classes.'\n , usage='findscu [options] addr port')\n", (1144, 1549), False, 'import argparse\n'), ((7413, 7422), 'pydicom.dataset.Dataset', 'Dataset', ([], {}), '()\n', (7420, 7422), False, 'from pydicom.dataset import Dataset\n'), ((7574, 7616), 'pydicom.uid.generate_uid', 'generate_uid', ([], {'prefix': 'PYNETDICOM_UID_PREFIX'}), '(prefix=PYNETDICOM_UID_PREFIX)\n', (7586, 7616), False, 'from pydicom.uid import ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian, generate_uid\n'), ((8190, 8220), 'pynetdicom.apps.common.setup_logging', 'setup_logging', (['args', '"""findscu"""'], {}), "(args, 'findscu')\n", (8203, 8220), False, 'from pynetdicom.apps.common import create_dataset, setup_logging\n'), ((8866, 8895), 'pynetdicom.AE', 'AE', ([], {'ae_title': 'args.calling_aet'}), '(ae_title=args.calling_aet)\n', (8868, 8895), False, 'from pynetdicom import AE, QueryRetrievePresentationContexts, BasicWorklistManagementPresentationContexts, PYNETDICOM_UID_PREFIX, PYNETDICOM_IMPLEMENTATION_UID, PYNETDICOM_IMPLEMENTATION_VERSION\n'), ((8161, 8171), 'sys.exit', 'sys.exit', ([], {}), '()\n', (8169, 8171), False, 'import sys\n'), ((8649, 8681), 'pynetdicom.apps.common.create_dataset', 'create_dataset', (['args', 'APP_LOGGER'], {}), '(args, APP_LOGGER)\n', (8663, 8681), False, 'from pynetdicom.apps.common import create_dataset, setup_logging\n'), ((10000, 10029), 'pynetdicom.pdu_primitives.SOPClassExtendedNegotiation', 'SOPClassExtendedNegotiation', ([], {}), '()\n', (10027, 10029), False, 'from pynetdicom.pdu_primitives import SOPClassExtendedNegotiation\n'), ((11533, 11544), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (11541, 11544), False, 'import sys\n'), ((8753, 8764), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (8761, 8764), False, 'import sys\n'), ((10392, 10421), 'pynetdicom.pdu_primitives.SOPClassExtendedNegotiation', 'SOPClassExtendedNegotiation', ([], {}), '()\n', (10419, 10421), False, 'from pynetdicom.pdu_primitives import SOPClassExtendedNegotiation\n')]
#!/usr/bin/env python import sys import argparse import math from typing import List, Tuple from pysam import Fastafile, Samfile from rgt.Util import ErrorHandler, HmmData, GenomeData, OverlapType from rgt.HINT.signalProcessing import GenomicSignal from rgt.HINT.biasTable import BiasTable from .constants import * def expandRegion(chromosome, start, end, name = None, w = 500, strand = '.'): m = (math.ceil if strand == '-' else math.floor)((int(start) + int(end)) / 2) return chromosome, m - w, m + w, name, strand def regionDict(k, forward, reverse): chromosome, start, end, name, strand = k return { "chromosome": chromosome, "start": start, "end": end, "forward": forward, "reverse": reverse, "name": name, "strand": strand } def footprint(bam: str, bed: str, assembly: str = "hg38", w: int = 500, dnase: bool = False, bias_type = "SH"): # load HMM and bias parameters for ATAC-seq g = GenomeData(organism = assembly) hmm_data = HmmData() if dnase: hmm_file = hmm_data.get_default_hmm_dnase_bc() if bias_type == 'SH': table_F = hmm_data.get_default_bias_table_F_SH() table_R = hmm_data.get_default_bias_table_R_SH() bias_table = BiasTable().load_table(table_file_name_F = table_F, table_file_name_R = table_R) elif bias_type == 'DH': table_F = hmm_data.get_default_bias_table_F_DH() table_R = hmm_data.get_default_bias_table_R_DH() bias_table = BiasTable().load_table(table_file_name_F = table_F, table_file_name_R = table_R) else: hmm_file = hmm_data.get_default_hmm_atac_paired() table_F = hmm_data.get_default_bias_table_F_ATAC() table_R = hmm_data.get_default_bias_table_R_ATAC() bias_table = BiasTable().load_table(table_file_name_F = table_F, table_file_name_R = table_R) # load reads from BAM reads_file = GenomicSignal(bam) reads_file.load_sg_coefs(SG_WINDOW_SIZE) # open data and sequence bam = Samfile(bam, "rb") fasta = Fastafile(g.get_genome()) # load and expand regions with open(bed, 'r') as f: regions = [ expandRegion( *tuple(line.strip().split()[:3]), line.strip().split()[3] if len(line.strip().split()) >= 4 else None, w, line.strip().split()[4] if len(line.strip().split()) >= 5 else '.' ) for line in f ] # load signal forward = []; reverse = []; failed = 0 get_reads = reads_file.get_signal_atac if not dnase else reads_file.get_signal for i, x in enumerate(regions): try: chromosome, start, end, _, strand = x atac_norm_f, atac_slope_f, atac_norm_r, atac_slope_r = get_reads( chromosome, start, end, 0, 0, FORWARD_SHIFT if not dnase else 0, REVERSE_SHIFT if not dnase else 0, 1000 if dnase else 150, 98, 98, bias_table, g.get_genome() ) atac_norm_f = [ float(x) for x in atac_norm_f ] atac_norm_r = [ float(x) for x in atac_norm_r ] if strand == '-': atac_norm_f.reverse() atac_norm_r.reverse() forward.append(atac_norm_f if strand != '-' else atac_norm_r) reverse.append(atac_norm_r if strand != '-' else atac_norm_f) if i % 500 == 0: print("INFO: aggregating region %d of %d" % (i, len(regions)), file = sys.stderr) except: if len(forward) <= i: forward.append(None) if len(reverse) <= i: reverse.append(None) failed += 1 if failed > 0: print("WARNING: failed to generate bias-corrected signal profiles for %d regions" % failed, file = sys.stderr) return [ regionDict(regions[i], forward[i], reverse[i]) for i in range(len(regions)) if forward[i] is not None and reverse[i] is not None ]
[ "pysam.Samfile", "rgt.HINT.signalProcessing.GenomicSignal", "rgt.HINT.biasTable.BiasTable", "rgt.Util.HmmData", "rgt.Util.GenomeData" ]
[((983, 1012), 'rgt.Util.GenomeData', 'GenomeData', ([], {'organism': 'assembly'}), '(organism=assembly)\n', (993, 1012), False, 'from rgt.Util import ErrorHandler, HmmData, GenomeData, OverlapType\n'), ((1030, 1039), 'rgt.Util.HmmData', 'HmmData', ([], {}), '()\n', (1037, 1039), False, 'from rgt.Util import ErrorHandler, HmmData, GenomeData, OverlapType\n'), ((1959, 1977), 'rgt.HINT.signalProcessing.GenomicSignal', 'GenomicSignal', (['bam'], {}), '(bam)\n', (1972, 1977), False, 'from rgt.HINT.signalProcessing import GenomicSignal\n'), ((2063, 2081), 'pysam.Samfile', 'Samfile', (['bam', '"""rb"""'], {}), "(bam, 'rb')\n", (2070, 2081), False, 'from pysam import Fastafile, Samfile\n'), ((1834, 1845), 'rgt.HINT.biasTable.BiasTable', 'BiasTable', ([], {}), '()\n', (1843, 1845), False, 'from rgt.HINT.biasTable import BiasTable\n'), ((1286, 1297), 'rgt.HINT.biasTable.BiasTable', 'BiasTable', ([], {}), '()\n', (1295, 1297), False, 'from rgt.HINT.biasTable import BiasTable\n'), ((1546, 1557), 'rgt.HINT.biasTable.BiasTable', 'BiasTable', ([], {}), '()\n', (1555, 1557), False, 'from rgt.HINT.biasTable import BiasTable\n')]
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from typing import List from abc import ABC, abstractmethod from ai_flow.graph.ai_node import AINode from ai_flow.workflow.job_context import JobContext from ai_flow.udf.function_context import FunctionContext from ai_flow.meta.example_meta import ExampleMeta from ai_flow.graph.ai_nodes.example import Example from pyflink.table.table import Table from pyflink.dataset import ExecutionEnvironment from pyflink.table import TableConfig, BatchTableEnvironment, TableEnvironment, StatementSet class FlinkFunctionContext(FunctionContext): def __init__(self, exec_env, t_env: TableEnvironment, statement_set: StatementSet, node_spec: AINode, job_context: JobContext) -> None: super().__init__(node_spec, job_context) self.exec_env = exec_env self.t_env = t_env self.statement_set = statement_set if isinstance(node_spec, Example): self.example_meta = node_spec.example_meta else: self.example_meta = None def get_exec_env(self): return self.exec_env def get_table_env(self) -> TableEnvironment: return self.t_env def get_statement_set(self) -> StatementSet: return self.statement_set def get_example_meta(self) -> ExampleMeta: return self.example_meta class Executor(ABC): def __init__(self) -> None: super().__init__() @abstractmethod def execute(self, function_context: FlinkFunctionContext, input_list: List[Table]) -> List[Table]: pass def setup(self, function_context: FlinkFunctionContext): pass def close(self, function_context: FlinkFunctionContext): pass class SourceExecutor(ABC): def __init__(self) -> None: super().__init__() @abstractmethod def execute(self, function_context: FlinkFunctionContext) -> Table: pass def setup(self, function_context: FlinkFunctionContext): pass def close(self, function_context: FlinkFunctionContext): pass class SinkExecutor(ABC): def __init__(self) -> None: super().__init__() @abstractmethod def execute(self, function_context: FlinkFunctionContext, input_table: Table) -> None: pass def setup(self, function_context: FlinkFunctionContext): pass def close(self, function_context: FlinkFunctionContext): pass class TableEnvCreator(ABC): def create_table_env(self): exec_env = ExecutionEnvironment.get_execution_environment() exec_env.set_parallelism(1) t_config = TableConfig() t_env = BatchTableEnvironment.create(exec_env, t_config) statement_set = t_env.create_statement_set() return exec_env, t_env, statement_set
[ "pyflink.table.TableConfig", "pyflink.table.BatchTableEnvironment.create", "pyflink.dataset.ExecutionEnvironment.get_execution_environment" ]
[((3244, 3292), 'pyflink.dataset.ExecutionEnvironment.get_execution_environment', 'ExecutionEnvironment.get_execution_environment', ([], {}), '()\n', (3290, 3292), False, 'from pyflink.dataset import ExecutionEnvironment\n'), ((3348, 3361), 'pyflink.table.TableConfig', 'TableConfig', ([], {}), '()\n', (3359, 3361), False, 'from pyflink.table import TableConfig, BatchTableEnvironment, TableEnvironment, StatementSet\n'), ((3378, 3426), 'pyflink.table.BatchTableEnvironment.create', 'BatchTableEnvironment.create', (['exec_env', 't_config'], {}), '(exec_env, t_config)\n', (3406, 3426), False, 'from pyflink.table import TableConfig, BatchTableEnvironment, TableEnvironment, StatementSet\n')]
from argparse import ArgumentParser import numpy as np import requests from mmcls.apis import inference_model, init_model, show_result_pyplot def parse_args(): parser = ArgumentParser() parser.add_argument('img', help='Image file') parser.add_argument('config', help='Config file') parser.add_argument('checkpoint', help='Checkpoint file') parser.add_argument('model_name', help='The model name in the server') parser.add_argument( '--inference-addr', default='127.0.0.1:8080', help='Address and port of the inference server') parser.add_argument( '--device', default='cuda:0', help='Device used for inference') args = parser.parse_args() return args def main(args): # Inference single image by native apis. model = init_model(args.config, args.checkpoint, device=args.device) model_result = inference_model(model, args.img) show_result_pyplot(model, args.img, model_result, title='pytorch_result') # Inference single image by torchserve engine. url = 'http://' + args.inference_addr + '/predictions/' + args.model_name with open(args.img, 'rb') as image: response = requests.post(url, image) server_result = response.json() show_result_pyplot(model, args.img, server_result, title='server_result') assert np.allclose(model_result['pred_score'], server_result['pred_score']) print('Test complete, the results of PyTorch and TorchServe are the same.') if __name__ == '__main__': args = parse_args() main(args)
[ "argparse.ArgumentParser", "numpy.allclose", "mmcls.apis.inference_model", "mmcls.apis.show_result_pyplot", "requests.post", "mmcls.apis.init_model" ]
[((177, 193), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (191, 193), False, 'from argparse import ArgumentParser\n'), ((798, 858), 'mmcls.apis.init_model', 'init_model', (['args.config', 'args.checkpoint'], {'device': 'args.device'}), '(args.config, args.checkpoint, device=args.device)\n', (808, 858), False, 'from mmcls.apis import inference_model, init_model, show_result_pyplot\n'), ((878, 910), 'mmcls.apis.inference_model', 'inference_model', (['model', 'args.img'], {}), '(model, args.img)\n', (893, 910), False, 'from mmcls.apis import inference_model, init_model, show_result_pyplot\n'), ((915, 988), 'mmcls.apis.show_result_pyplot', 'show_result_pyplot', (['model', 'args.img', 'model_result'], {'title': '"""pytorch_result"""'}), "(model, args.img, model_result, title='pytorch_result')\n", (933, 988), False, 'from mmcls.apis import inference_model, init_model, show_result_pyplot\n'), ((1244, 1317), 'mmcls.apis.show_result_pyplot', 'show_result_pyplot', (['model', 'args.img', 'server_result'], {'title': '"""server_result"""'}), "(model, args.img, server_result, title='server_result')\n", (1262, 1317), False, 'from mmcls.apis import inference_model, init_model, show_result_pyplot\n'), ((1330, 1398), 'numpy.allclose', 'np.allclose', (["model_result['pred_score']", "server_result['pred_score']"], {}), "(model_result['pred_score'], server_result['pred_score'])\n", (1341, 1398), True, 'import numpy as np\n'), ((1178, 1203), 'requests.post', 'requests.post', (['url', 'image'], {}), '(url, image)\n', (1191, 1203), False, 'import requests\n')]
# # https://stackoverflow.com/a/47983927/1832058 # import tkinter as tk root = tk.Tk() root.geometry('250x250') root.title('Canvas') canvas = tk.Canvas(root, width=250, height=250) canvas.pack() img = tk.PhotoImage(file='hal_9000.gif') canvas.create_image((0, 0), image=img, anchor='nw') canvas.create_text((10, 100), text='Username', anchor='w', fill='white', font=('Arial', 10)) canvas.create_text((10, 150), text='Password', anchor='w', fill='white', font=('Arial', 10)) name_entry = tk.Entry(canvas) password_entry = tk.Entry(canvas, show='*') canvas.create_window((240, 100), window=name_entry, anchor='e') canvas.create_window((240, 150), window=password_entry, anchor='e') root.mainloop()
[ "tkinter.Canvas", "tkinter.PhotoImage", "tkinter.Entry", "tkinter.Tk" ]
[((84, 91), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (89, 91), True, 'import tkinter as tk\n'), ((148, 186), 'tkinter.Canvas', 'tk.Canvas', (['root'], {'width': '(250)', 'height': '(250)'}), '(root, width=250, height=250)\n', (157, 186), True, 'import tkinter as tk\n'), ((208, 242), 'tkinter.PhotoImage', 'tk.PhotoImage', ([], {'file': '"""hal_9000.gif"""'}), "(file='hal_9000.gif')\n", (221, 242), True, 'import tkinter as tk\n'), ((497, 513), 'tkinter.Entry', 'tk.Entry', (['canvas'], {}), '(canvas)\n', (505, 513), True, 'import tkinter as tk\n'), ((531, 557), 'tkinter.Entry', 'tk.Entry', (['canvas'], {'show': '"""*"""'}), "(canvas, show='*')\n", (539, 557), True, 'import tkinter as tk\n')]